完美实现GIF动画缩略图的php代码
2019/6/30 15:26:10
本文主要是介绍完美实现GIF动画缩略图的php代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
为了让问题更加清晰,我们先还原动画各帧:
选择一:用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动画为了压缩,会以第一帧为模板,其余各帧按照适当的偏移量依次累加,并只保留不同的像素,结果是导致各帧尺寸不尽相同,为缩略图造成障碍。
下面看看如何用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如下:
有个细节问题:convert版本会比php版本小一些,这是API实现不一致所致。
另外,如果缩略图尺寸不符合原图比例,为了避免变形,还要考虑裁剪或者是补白,由于本文主要讨论GIF动画缩略图的特殊性,就不再继续讨论这些问题了,有兴趣的自己搞定吧。
这篇关于完美实现GIF动画缩略图的php代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28怎么把PHP程序打包?-icode9专业技术文章分享
- 2024-09-28怎么用Phar打包PHP程序?-icode9专业技术文章分享
- 2024-09-13手动在github上下载的mfpt包,怎么放到thinkphp5.0框架并正常使用-icode9专业技术文章分享
- 2024-09-05python的<class 'bytearray'>相当于php的哪个数据类型-icode9专业技术文章分享
- 2024-09-05php 导出银行卡号避免科学技术法的方法-icode9专业技术文章分享
- 2024-08-30什么样的php代码质量差被称为垃圾代码-icode9专业技术文章分享
- 2024-08-30用 PHP 调用拼多多的接口以获取订单状态消息的步骤方法和代码示例-icode9专业技术文章分享
- 2024-08-27phpunit单元测试框架的入门和使用方法介绍-icode9专业技术文章分享
- 2024-08-24PHP 中date("w") 周一是多少-icode9专业技术文章分享
- 2024-08-14thinkphp8.0获取域名或主机名方法-icode9专业技术文章分享