您的位置:首页 > 其它

加速ImageMagick gif图像处理

2010-11-18 12:19 1266 查看

使用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选项,处理的速度还可以进一步提升

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: