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

PHP+;GD创建随机黑色缩略图,php,gd,Php,Gd,此函数正在创建一些随机的黑色图像,如。。10%的时间, 不多,但是。。你知道的。。不应该发生 class ImgResizer { private $originalFile = ''; public function __construct($originalFile = '') { $this -> originalFile = $originalFile; } public function resize($newWidth, $targetFile) { if (e

此函数正在创建一些随机的黑色图像,如。。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
}
服务器是linux。函数的调用方式如下: 假设$imagen是实际的源图像,$imagendestino是新缩略图的路径和文件名

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

提前谢谢

最有可能是您传递了一张非JPEG图像

JPEG可以重新调整大小,但是由于函数无法读取不同的图像格式,因此会生成无效图像。结果是一个空白图像,即全零,这将产生一个黑色图像。创建人

imagecreatetruecolor($newWidth, $newHeight);
当我运行you类并将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会根据文件头自动检测文件类型。

是否确实启用了错误日志记录?失败是否确定?即,同一输入文件的输出是否始终相同?
imagecreatefromjpeg(filename)