【问题标题】:PHP+GD creating random black thumbnailsPHP+GD 创建随机黑色缩略图
【发布时间】:2011-03-02 21:11:42
【问题描述】:

这个函数会创建一些随机的黑色图像,比如 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);
    }

提前致谢!

【问题讨论】:

  • 你确定你启用了错误日志吗?
  • 失败是确定性的吗? IE。同一个输入文件的输出总是一样的吗?

标签: php gd


【解决方案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会根据文件头自动为你检测文件类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多