Reputation: 10219
I'm using the following ImageMagick script (with Imagick for PHP) to generate an image of a font. This script takes about 0.1 seconds to generate an image of about 30 characters at size 48. The target speed is about 0.01 seconds. I'm afraid switching to the GD library may be the only way to achieve this (I read here that text generation is much faster in GD). However, without features like gravity and trim, it's much more cumbersome to generate this type of image using GD. Does anyone see an obvious bottleneck in this code, or is it time to switch libraries?
$image = new Imagick();
$draw = new ImagickDraw();
$background = new ImagickPixel('none');
$draw->setFont($font);
$draw->setFontSize($size);
$draw->setFillColor(new ImagickPixel('#'.$color));
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->annotation(0, 0, $text);
$image->newImage(5*mb_strlen($text, 'UTF-8')*$size, 5*$size, $background);
$image->setImageFormat('png');
$image->drawImage($draw);
$image->trimImage(0);
$image->writeImage($path_server['dirname'].'/'.$path_server['basename']);
Upvotes: 2
Views: 1331
Reputation: 10219
The answer was to switch libraries, but not to GD. Rather, I switched to GraphicsMagick, which is a fork of ImageMagick that focuses on efficiency and optimization. According to the GraphicsMagick website, it's used by some of the world's largest photo sites including Flickr and Etsy. The following GraphicsMagick code runs about 10 times faster than the corresponding ImageMagick code, which allowed me to hit my target of 0.01 seconds per operation (actually it's closer to 0.008 seconds):
$image = new Gmagick();
$draw = new GmagickDraw();
$draw->setfont($font);
$draw->setfontsize($size);
$draw->setfillcolor('#'.$color);
$draw->setgravity(Gmagick::GRAVITY_CENTER);
$draw->annotate(0, 0, mb_ereg_replace('%', '%%', $text));
$image->newimage(5*mb_strlen($text)*$size, 5*$size, 'none', 'png');
$image->drawimage($draw);
$image->trimimage(0);
$image->writeimage($path_server['dirname'].'/'.$path_server['basename']);
You'll notice that there are a few other nice features as well. For example, instead of having to define a color by creating an ImagickPixel
object, most functions simply take a color as a string. Also, the function names seem more self-consistent in GraphicsMagick (annotate instead of annotation). Needless to say, I'm pretty happy with it.
Upvotes: 7