php imagick simple font rendering with automatic image canvas size

I have been working with the image imagick library for PHP (ImageMagick) for some time now. I figure its time to share what I have discovered and figured out. There is very little documentation on this amazing library for PHP, but hopefully my hours of trial and error can help those who are interested in using it. For my first post, I will share a script I wrote which will render a png image for text using a ttf font.

The script uses imagick’s ImagickDraw object to first load the font, set the font size, orientation (GRAVITY_CENTER in this example, but you could set it to GRAVITY_NORTHWEST, or GRAVITY_SOUTHEAST), and fill color. Then the script gets the proper canvas size for the Imagick image object before the image is created, so you don’t need to worry about having to “know” what size the image needs to be. I have found that the metrics ImagickDraw outputs is not always perfect, so I have added a bit of padding to the image size that is calculated.

Next, the script creates a new Imagick image object and sets it’s size to what was calculated in the first step. It then “draws” the font that was set up in the first step. Once this is done, the script sets the image format (“PNG” in this example, but it could be a gif, or jpg if you want). The script finally saves the cache file, then sets the content type header and outputs the image to the browser.

<?php
 
$fontpath = "path/to/your/fontfile.ttf";
if(!file_exists($fontpath)) die("Error!  Font file does not exist at '".$fontpath."'");
 
$cachefile = "path/to/your/cachefile.png";
$text = "ABCD abcd 1234";
$fillcolor = "#999999";
 
 
if (!file_exists($cachefile)) {
 
	try{
 
		$draw = new ImagickDraw();
		$draw->setFont($fontpath);
		$draw->setFontSize(20);
		$draw->setGravity(Imagick::GRAVITY_CENTER);
		$draw->setFillColor($fillcolor);
 
		$canvas = new Imagick();
 
		$metrics = $canvas->queryFontMetrics($draw,$text);
 
		$canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png");
		$canvas->annotateImage($draw,0,0,0,$text);
 
		$canvas->setImageFormat('PNG');
		$canvas->writeImage($cachefile);
 
		header("Content-Type: image/png");
		echo $canvas;
 
		$canvas->clear();
		$canvas->destroy();
 
		$draw->clear();
		$draw->destroy();
 
	}catch(Exception $e){
		echo 'Error: ',  $e->getMessage(), "";
	}
 
} else {
 
	$canvas = new Imagick($cachefile);
	header("Content-Type: image/png");
	echo $canvas;
 
}
 
die();
 
?>

NOTES: Your cache file path must be writable by the server.

6 Comments to php imagick simple font rendering with automatic image canvas size

  1. October 6, 2010 at 10:40 am | Permalink

    Wow, this page frequently sucks up 50% CPU time (and more) and 85MB of RAM in Chrome on Mac OS X Snow Leopard. Does anyone else experience this?

  2. james's Gravatar james
    October 6, 2010 at 11:53 pm | Permalink

    Its the background polar animation that is sucking all the CPU. I recognize this isn’t ideal, but it just didn’t look as cool at lower frame rates 😉 You can also change the background color with the little colorwheel icon in the top right…

  3. June 23, 2012 at 4:09 am | Permalink

    Thanks James! I’ve been looking for a solution for rendering a wide variety of font formats in a PHP environment – the imagettftext() function just wasn’t cutting it. This worked great for me!

  4. nikul's Gravatar nikul
    September 26, 2012 at 2:06 am | Permalink

    how to make font bold or italic?
    i tried,
    $draw = new ImagickDraw();
    $draw->setFontStyle(2);
    and
    $draw->setFontStyle(Imagick:: STYLE_ITALIC);

    but not working…

    please help me on this

    thanks a lot

  5. james's Gravatar james
    September 26, 2012 at 3:03 am | Permalink

    You would have to specify the italic font file rather than try and use imagick to manipulate the font you’ve specified. imagick just uses the vector information from the font file and cannot actually change the font information unless its already a bitmap image.

  6. February 1, 2014 at 11:16 am | Permalink

    nice use full

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>