|

GIF動(dòng)畫(huà)圖片:old.gif
為了讓問(wèn)題更加清晰,我們先還原動(dòng)畫(huà)各幀:
選擇一:用php中的Imagick模塊:
復(fù)制代碼 代碼如下:
<?php
$image = new Imagick('old.gif');
$i = 0;
foreach ($image as $frame) {
$frame->writeImage('old_' . $i++ . '.gif');
}
?>
選擇二:用ImageMagick提供的convert命令:
復(fù)制代碼 代碼如下:
shell> convert old.gif old_%d.gif
結(jié)果得到GIF動(dòng)畫(huà)各幀示意圖如下所示:

GIF動(dòng)畫(huà)各幀示意圖
可以明顯的看到,GIF動(dòng)畫(huà)為了壓縮,會(huì)以第一幀為模板,其余各幀按照適當(dāng)?shù)钠屏恳来卫奂樱⒅槐A舨煌南袼兀Y(jié)果是導(dǎo)致各幀尺寸不盡相同,為縮略圖造成障礙。
下面看看如何用php中的Imagick模塊來(lái)完美實(shí)現(xiàn)GIF動(dòng)畫(huà)縮略圖:
復(fù)制代碼 代碼如下:
<?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方法,它確保各幀尺寸一致,用手冊(cè)里的話來(lái)說(shuō)就是:
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.
同時(shí)要注意optimizeImageLayers方法,它刪除重復(fù)像素內(nèi)容,用手冊(cè)里的話來(lái)說(shuō)就是:
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:如果要求更完美一點(diǎn),可以使用quantizeImages方法進(jìn)一步壓縮。
注意:不管是coalesceimages,還是optimizeImageLayers,都是返回新的Imagick對(duì)象!
如果你更習(xí)慣操作shell的話,那么可以這樣實(shí)現(xiàn)GIF動(dòng)畫(huà)縮略圖:
復(fù)制代碼 代碼如下:
shell> convert old.gif -coalesce -thumbnail 50x50 -layers optimize new.gif
生成的new.gif如下:

new.gif
有個(gè)細(xì)節(jié)問(wèn)題:convert版本會(huì)比php版本小一些,這是API實(shí)現(xiàn)不一致所致。
另外,如果縮略圖尺寸不符合原圖比例,為了避免變形,還要考慮裁剪或者是補(bǔ)白,由于本文主要討論GIF動(dòng)畫(huà)縮略圖的特殊性,就不再繼續(xù)討論這些問(wèn)題了,有興趣的自己搞定吧。
php技術(shù):完美實(shí)現(xiàn)GIF動(dòng)畫(huà)縮略圖的php代碼,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。