加速ImageMagick gif图像处理

本文介绍了在Linux平台上,如何通过优化代码和编译选项来加速使用ImageMagick进行gif图像处理,特别是添加文本注释时,速度可提升近6倍,同时讨论了在牺牲较小图像质量前提下的可接受性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用ImageMagick是linux平台下,进行图像处理的一种较好的办法,相对GD库来说,功能要强大一些。

但是由于ImageMagick的目标是图像处理的质量,所以对于速度不是第一优先的考虑,很多例子程序的代码也偏重于图像质量的编码,或者没有给出进行加速的办法。

下面以图像添加文本注释为例,介绍一下怎么提升处理速度

添加文本注释的示例代码:

        $font = "./arial.ttf";
        $draw = new ImagickDraw();
        $draw->setFont($font);
        $draw->setFontSize($fontsize);
        $draw->setFillColor (new ImagickPixel($color));//set the color of font

        $image=new Imagick();
        $imgpath ="./test.gif";
        $image->readImage($imgpath);
        $unitl = $image->getNumberImages();
        $numimage = new Imagick();
        $numimage->newImage(200, 200, new ImagickPixel('none'));
        $numimage->setImageFormat('gif');
        $numimage->annotateImage($draw,$today_x,$today_y,0,$today);
        $numimage->annotateImage($draw,$yes_x,$yes_y,0,$yes);
        $numimage->annotateImage($draw,$total_x,$total_y,0,$total);

        for ($i=0; $i<$unitl; $i++) {
                $image->setImageIndex($i);
                $image->compositeImage($numimage,  Imagick::COMPOSITE_OVER, 0,0);
        }

        $image->writeImages('./33.gif', true);
但是这段代码的速度是不能让人满意的,经过对ImageMagick的源码分析,我们发现大量的时间是消耗在图像色彩量化阶段(quantizeImage),因此将代码更改为:
        $font = "./arial.ttf";
        $draw = new ImagickDraw();
        $draw->setFont($font);
        $draw->setFontSize($fontsize);
        $draw->setFillColor (new ImagickPixel($color));//set the color of font

        $image=new Imagick();
        $imgpath ="./test.gif";
        $image->readImage($imgpath);
        $unitl = $image->getNumberImages();
        $numimage = new Imagick();
        $numimage->newImage(200, 200, new ImagickPixel('none'));
        $numimage->setImageFormat('gif');
        $numimage->annotateImage($draw,$today_x,$today_y,0,$today);
        $numimage->annotateImage($draw,$yes_x,$yes_y,0,$yes);
        $numimage->annotateImage($draw,$total_x,$total_y,0,$total);

        for ($i=0; $i<$unitl; $i++) {
                $image->setImageIndex($i);
                $image->compositeImage($numimage,  Imagick::COMPOSITE_OVER, 0,0);
                //降低色彩量化的质量
                $image->quantizeImage(256, imagick::COLORSPACE_RGB, 4, false, false);
        }

        $image->writeImages('./33.gif', true);

处理的速度能有将近6倍的提升:),但是对于web用户来说损失的gif图像质量基本上是可以接受的

如果你的ImageMagick只用来进行gif的处理,那么你在编译ImageMagick的时候还可以加上--with-quantum-depth=8选项,处理的速度还可以进一步提升


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值