Home >Backend Development >PHP Tutorial >PHP code that perfectly implements GIF animated thumbnails_PHP tutorial
下面通过一个取自CS警匪游戏的GIF动画来说明问题:
为了让问题更加清晰,我们先还原动画各帧:
选择一:用PHP中的Imagick模块:
结果得到GIF动画各帧示意图如下所示:
可以明显的看到,GIF动画为了压缩,会以第一帧为模板,其余各帧按照适当的偏移量依次累加,并只保留不同的像素,结果是导致各帧尺寸不尽相同,为缩略图造成障碍。
下面看看如何用PHP中的Imagick模块来完美实现GIF动画缩略图:
代码里最关键的是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动画缩略图:
生成的new.gif如下:
There is a detail issue: the convert version will be smaller than the php version, which is caused by inconsistent API implementation.
In addition, if the size of the thumbnail does not match the proportion of the original image, in order to avoid deformation, cropping or padding must be considered. Since this article mainly discusses the particularity of GIF animated thumbnails, we will not continue to discuss these issues. Interested Just do it yourself.