PHP + GD创建随机黑色缩略图

时间:2010-06-11 22:27:11

标签: php gd

此功能正在创建一些随机的黑色图像,如... 10%的时间, 并不多,但是......你知道......不应该发生。

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
}

}

error_log中没有给出错误。这是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);
    }

提前致谢!

1 个答案:

答案 0 :(得分: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会根据您的文件标题自动检测文件类型。