完美实现GIF动画缩略图(GIF压缩使用C++、shell命令、php)

缩略图是个很常用的功能。它的实现并不复杂,但如果原图是GIF动画的话,问题就会变得繁琐一点。因为GIF(动画)由多个图片组成,需要先解压单独图片->图片压缩->图片组合动画。

 

 


使用C++,需要安装

 

[c-sharp] view plain copy
  1. Blob blob((void*)data, len);  
  2. list<Image> imageList;  
  3. list<Image> coalescedList;  
  4. list<Image> resizeList;  
  5. readImages(&imageList, blob);  
  6. coalesceImages(&coalescedList, imageList.begin(), imageList.end());  
  7. list<Image>::iterator it = imageList.begin();  
  8. it = coalescedList.begin();  
  9. while(it != coalescedList.end()){  
  10. Image image = (*it);  
  11. image.zoom("100x100");  
  12. resizeList.push_back(image);  
  13. ++it;  
  14. }   
  15. writeImages(resizeList.begin(), resizeList.end(), "smaller.gif");  
 

 

  
  

用ImageMagick提供的convert命令:

  shell> convert old.gif old_%d.gif
  结果得到GIF动画各帧示意图如下所示:


  可以明显的看到,GIF动画为了压缩,会以第一帧为模板,其余各帧按照适当的偏移量依次累加,并只保留不同的像素,结果是导致各帧尺寸不尽相同,为缩略图造成障碍。下面看看如何用PHP中的Imagick模块来完美实现GIF动画缩略图:

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

  生成的new.gif如下:

  

 

 


用PHP中的Imagick模块:

[c-sharp] view plain copy
  1. <?php  
  2. $image = new Imagick('old.gif');  
  3. $image = $image->coalesceImages();  
  4. foreach ($image as $frame) {  
  5.     $frame->thumbnailImage(50, 50);  
  6. }  
  7. $image = $image->optimizeImageLayers();  
  8. $image->writeImages('new.gif'true);  
  9. ?>  
 

 

   
   
代码里最关键的是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动画缩略图:

 

有个细节问题:convert版本会比php版本小一些,这是API实现不一致所致。另外,如果缩略图尺寸不符合原图比例,为了避免变形,还要考虑裁剪或者是补白。

 

 

 

/*************************************************/

 

参考:

http://kb.cnblogs.com/page/87154/

http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=2&t=15172


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值