完美实现GIF动画缩略图的php代码

yipeiwu_com5年前PHP代码库
下面通过一个取自CS警匪游戏的GIF动画来说明问题:
GIF动画图片:old.gif

GIF动画图片:old.gif

为了让问题更加清晰,我们先还原动画各帧:

选择一:用PHP中的Imagick模块:

复制代码 代码如下:

<?php
$image = new Imagick('old.gif');
$i = 0;
foreach ($image as $frame) {
$frame->writeImage('old_' . $i++ . '.gif');
}
?>

选择二:用ImageMagick提供的convert命令:
复制代码 代码如下:

shell> convert old.gif old_%d.gif

结果得到GIF动画各帧示意图如下所示:

GIF动画各帧示意图

GIF动画各帧示意图

可以明显的看到,GIF动画为了压缩,会以第一帧为模板,其余各帧按照适当的偏移量依次累加,并只保留不同的像素,结果是导致各帧尺寸不尽相同,为缩略图造成障碍。

下面看看如何用PHP中的Imagick模块来完美实现GIF动画缩略图:

复制代码 代码如下:

<?php
$image = new Imagick('old.gif');
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->thumbnailImage(50, 50);
}
$image = $image->optimizeImageLayers();
$image->writeImages('new.gif', true);
?>

代码里最关键的是coalesceimages方法,它确保各帧尺寸一致,用手册里的话来说就是:

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

同时要注意optimizeImageLayers方法,它删除重复像素内容,用手册里的话来说就是:

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation.

BTW:如果要求更完美一点,可以使用quantizeImages方法进一步压缩。

注意:不管是coalesceimages,还是optimizeImageLayers,都是返回新的Imagick对象!

如果你更习惯操作shell的话,那么可以这样实现GIF动画缩略图:

复制代码 代码如下:

shell> convert old.gif -coalesce -thumbnail 50x50 -layers optimize new.gif

生成的new.gif如下:

 

new.gif

new.gif

有个细节问题:convert版本会比php版本小一些,这是API实现不一致所致。

另外,如果缩略图尺寸不符合原图比例,为了避免变形,还要考虑裁剪或者是补白,由于本文主要讨论GIF动画缩略图的特殊性,就不再继续讨论这些问题了,有兴趣的自己搞定吧。

相关文章

Laravel中正确地返回HTTP状态码方法示例

Laravel中正确地返回HTTP状态码方法示例

在 API 中返回状态码是很重要的,因为响应处理程序是工作在 API 的响应状态码之上的。 写 API 时其中有一个重要的地方是更好的处理响应状态码。以前,我一般会使用不常用的 Int...

php Notice: Undefined index 错误提示解决方法

第一种方法:如果不影响程序的正常执行,可以采用屏蔽的方法可以在代码的第一行 加上 error_reporting(E_ALL ^ E_NOTICE); 关闭掉 NOTICE错误的警告第二...

Linux下PHP加速器APC的安装与配置笔记

当前我用的是APC-3.1.9 stable ,可以自己到 http://pecl.php.net/package/APC 下载最新版。 1、安装 复制代码 代码如下: wget htt...

PHP文件打开、关闭、写入的判断与执行代码

PHP文件打开、关闭、写入的判断与执行代码

如何准确的控制和判断成了PHP中的一个“小问题”,下面是从书上摘抄下来的语句。 复制代码 代码如下: <?php $filename = "html/cache.txt"; $co...

php数组函数序列之asort() - 对数组的元素值进行升序排序,保持索引关系

asort() 定义和用法 asort() 函数对数组进行排序并保持索引关系。主要用于对那些单元顺序很重要的结合数组进行排序。 可选的第二个参数包含了附加的排序标识。 如果成功则返回 T...