2010-06-11 83 views
2

此功能正在创建一些随机黑色图像,如.. 10%的时间, 并不多,但..你知道..应该发生。在error_log中给出PHP + GD创建随机黑色缩略图

class ImgResizer { 
private $originalFile = ''; 
public function __construct($originalFile = '') { 
    $this -> originalFile = $originalFile; 
} 
public function resize($newWidth, $targetFile) { 
    if (empty($newWidth) || empty($targetFile)) { 
     return false; 
    } 
    $src = imagecreatefromjpeg($this -> originalFile); 
    list($width, $height) = getimagesize($this -> originalFile); 
    $newHeight = ($height/$width) * $newWidth; 

    if ($newHeight<'335') { 
     //$newHeight='335'; 
    } 
    $tmp = imagecreatetruecolor($newWidth, $newHeight); 
    #$tmp = imagecreate($newWidth, $newHeight); 
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    if (file_exists($targetFile)) { 
     unlink($targetFile); 
    } 
    imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious 
} 

}

没有错误。这里是gd_info():

Array(
[GD Version] => bundled (2.0.34 compatible) 
[FreeType Support] => 
[T1Lib Support] => 
[GIF Read Support] => 1 
[GIF Create Support] => 1 
[JPG Support] => 1 
[PNG Support] => 1 
[WBMP Support] => 1 
[XPM Support] => 1 
[XBM Support] => 1 
[JIS-mapped Japanese Font Support] =>)1 

服务器是linux。函数被这样调用: 假设$ imagen是实际的源图像,$ imagendestino是新缩略图的路径和文件名。

if (!file_exists($imagendestino)) { 
     $work = new ImgResizer($imagen); 
     $work -> resize(475, $imagendestino); 
    } 

在此先感谢!

+0

您确定您启用了错误日志记录吗? – 2010-06-12 11:57:30

+0

失败的确定性?即输出文件的输出总是相同的吗? – 2011-02-21 13:30:58

回答

1

很可能是您传递非JPEG图像。

由于JPEG功能无法读取不同的图像格式,因此会产生无效的图像。结果是空白图像,即全零,这产生黑色图像。通过

imagecreatetruecolor($newWidth, $newHeight); 

创建时,我碰到你的类传递一个PNG图像文件,它给这些警告并创建一个黑色图像:

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'filename' is not a valid JPEG file 
Warning: imagecopyresampled(): supplied argument is not a valid Image resource 

最有可能你已经警告无效,所以你不要不会得到这些消息。

尝试使用

imagecreatefromstring(file_get_contents(filename)) 

代替

imagecreatefromjpeg(filename) 

这样GD自动检测基于对你的文件头的文件类型。