如何使用 PHP (ImageMagick) 降低动画 gif 的质量(文件大小)?

How to reduce quality (filesize) for animated gif with PHP (ImageMagick)?

我想降低动画 GIF 的质量以减小 GIF 文件大小。动画和尺寸应保持不变。

这可能吗?

我尝试了各种 Imagemagick 函数,但没有成功。也许有人这样做过?

这只是一种逻辑思维,但如果像这样的方法可行,那就太酷了:

$gif = new Imagick($tempFilePath);
$gif = $gif->coalesceImages();

foreach ($gif as $frame) {                                  
    $frame->setImageCompression(8);
    $frame->setImageCompressionQuality(10);
}

$gif = $gif->deconstructImages();
$gif->writeImages($tempFilePath, true);```

GIF 不使用压缩。所以你的压缩参数不会做任何事情。在 ImageMagick 命令行中,最简单的方法就是减少动画中的颜色数量。

输入(圣海伦斯山彩色):

convert animation.gif -coalesce +dither -colors 64 -layers optimize animation2.gif


我不是 Imagick 专家,但我认为您想要的是 quantizeImages, which I believe will reduce colors for an animation or set of images. See also the example at quantizeImage 减少单个图像的颜色。

请注意,我首先使用 -coalesce 来填充帧。我使用 +dither 来避免在减少颜色时抖动。最后我重新优化了动画。

但是,更好的方法 是对所有帧使用一个通用颜色图,并使用尽可能少的颜色。然后还要对动画做图层优化。这可以在这个简单的(极小的数字)三色示例中按如下方式完成。

输入(圣海伦斯山彩色):

三色颜色Table(放大查看):

convert xc:red xc:green1 xc:blue +append colortable.gif


convert animation.gif -coalesce +dither -remap colortable.gif -layers optimize new_animation.gif


更实用,你可以创建一个减少的颜色table通过收集所有组合动画帧的所有颜色,减少颜色然后得到独特的颜色.例如:

convert animation.gif -coalesce +append +dither -colors 64 -unique-colors -depth 8 colortable2.gif


然后将此颜色table应用到动画

convert animation.gif -coalesce +dither -remap colortable2.gif -layers optimize new_animation2.gif


文件大小为:

animation.gif ---  481 K
animation2.gif (64 colors) --- 479 K
new_animation (3 colors) --- 57 K
new_animation2 (64 colors) --- 393 K

对于Imagick,见以下方法:

coalesce

remap

append

uniquecolors

quantizeimage for reduced colors