完美實現(xiàn)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
結(jié)果得到GIF動畫各幀示意圖如下所示:
可以明顯的看到,GIF動畫為了壓縮,會以第一幀為模板,其余各幀按照適當(dāng)?shù)钠屏恳来卫奂樱⒅槐A舨煌南袼?,結(jié)果是導(dǎo)致各幀尺寸不盡相同,為縮略圖造成障礙。
下面看看如何用PHP中的Imagick模塊來完美實現(xiàn)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);
?>
代碼里最關(guān)鍵的是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方法,它刪除重復(fù)像素內(nèi)容,用手冊里的話來說就是:
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對象!
如果你更習(xí)慣操作shell的話,那么可以這樣實現(xiàn)GIF動畫縮略圖:
shell> convert old.gif -coalesce -thumbnail 50x50 -layers optimize new.gif
生成的new.gif如下:
有個細(xì)節(jié)問題:convert版本會比php版本小一些,這是API實現(xiàn)不一致所致。
另外,如果縮略圖尺寸不符合原圖比例,為了避免變形,還要考慮裁剪或者是補白,由于本文主要討論GIF動畫縮略圖的特殊性,就不再繼續(xù)討論這些問題了,有興趣的自己搞定吧。
相關(guān)文章
PHP商品秒殺問題解決方案實例詳解【mysql與redis】
這篇文章主要介紹了PHP商品秒殺問題解決方案,結(jié)合實例形式詳細(xì)分析了php結(jié)合mysql與redis實現(xiàn)商品秒殺功能的相關(guān)操作技巧及注意事項,需要的朋友可以參考下2019-07-07PHP使用三種方法實現(xiàn)數(shù)據(jù)采集
這篇文章主要介紹了PHP使用三種方法實現(xiàn)數(shù)據(jù)采集,對數(shù)據(jù)采集感興趣的同學(xué),可以參考下2021-04-04PHP的命令行擴展Readline相關(guān)函數(shù)的使用
PHP 作為一個 Web 開發(fā)語言,相對來說,命令行程序并不是它的主戰(zhàn)場。所以很多年輕的 PHP 開發(fā)者可能連命令行腳本都沒有寫過,更別提交互式的命令操作了。而今天,我們帶來的這個擴展就是針對 PHP 的交互式命令行操作的2021-05-05