【问题标题】:PHP resizing working for PNGs and JPGs but not GIFsPHP 调整大小适用于 PNG 和 JPEG,但不适用于 GIF
【发布时间】:2013-11-25 10:42:10
【问题描述】:

我有一个调整上传图片大小的脚本。它适用于 PNG 和 JPG,但不适用于 GIF。对于 GIF,它应该将它们转换为 JPG,然后调整它们的大小。转换有效,但无法调整大小...

function resize_image($file, $maxWidth, $maxHeight) {
    $jpgFile = substr_replace($file, 'jpeg', -3);
    $fileType = strtolower(substr($file, -3));
    ...
    if ($fileType == 'gif') {
        $test = imagecreatefromgif($file);
        imagejpeg($test, $jpgFile);
        $src = imagecreatefromjpeg($jpgFile);
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
        imagejpeg($dst, $jpgfile);
    }  
}

【问题讨论】:

标签: php image-processing gif


【解决方案1】:

我认为您不需要在从 gif 创建图像后输出图像 - imagecreatefromgif 将图像读入内存,您应该可以这样做:

$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
imagejpeg($dst, $jpgfile);

【讨论】:

    【解决方案2】:

    您使用的是什么版本的 GD 库?根据the official PHP documentation

    从 1.6 版的 GD 库中删除了对 GIF 的支持,并添加了 回到版本 2.0.28。此功能在这些之间不可用 版本。

    【讨论】:

    • 它是 1.0 版,所以我认为这不是问题,但谢谢
    【解决方案3】:

    我最终绕过了 GIF 到 JPG 的转换,并直接调整了 GIF 的大小。但是,为了保持透明度(默认情况下,它会将透明背景变为黑色,这就是我最初在调整大小之前先将其转换为 JPG 的原因),我不得不添加一些说明。

        $src = imagecreatefromgif($file);
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
        imagegif($dst, $file);
    

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 1970-01-01
      • 2010-10-17
      • 2019-05-16
      • 1970-01-01
      • 2012-06-04
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多