Dynamic PHP Images

Posted on September 11th, 2006 by davelms.
Categories: PHP, Web Design.

I’ve done this kind of thing in the past *, and it’s very easy! But, shame on me, I forgot… ooops. Basically, all I wanted to do was take an existing image and use PHP to write text (dynamic, created by my script) over the top and return the updated image to the browser.

(* I created a last.fm / audioscrobbler script that picked up my latest tracks from their feeds, created an image from it, and displayed in my forum signatures. This was before the days that last.fm did this kind of thing themselves!! Bit redundant now though.)

Aaaaanyway… simple really, here’s what I did.

I created an image template and saved it to my server (as a PNG in this example, but I could have chosen GIF or JPG).

PNG Template

In addition to the image, I decided that I wanted to write my text in verdana, so copied to my server the verdana.ttf file.

Firstly, I used imagecreatefrompng() to bring in my PNG template image:

$im = imagecreatefrompng(”scarborough.png”);

If I had wanted to create a blank image canvas, I could have used imagecreate() instead, for example:

$im = imagecreate(400, 50); /* Create a blank image */

Then I set a few colour variables using imagecolorallocate():

$bgc = imagecolorallocate($im, 255, 255, 255); /* background colour */
$tc = imagecolorallocate($im, 102, 102, 102); /* text colour */
$tc2 = imagecolorallocate($im, 204, 204, 204); /* secondary text colour */

And set up the path to my verdana font file:

$font = “./verdana.ttf”;

Now I assign my output text using imagettftext():

$text = “Scarborough 0-0 Test Team”;
imagettftext($im, 11, 0, 60, 25, $tc, $font, $text);
$text = “Latest Alert: Game Added”;
imagettftext($im, 8, 0, 60, 40, $tc2, $font, $text);

Finally, I output the image usingimagepng():

imagepng($im);
imagedestroy($im);

(a quick reminder to set the correct header Content-type for the image format chosen, in this instance it’s image/png)

And there you have it:

Dynamic PHP Image

0 comments.

Leave a comment

Comments can contain some xhtml. Names and emails are required (emails aren't displayed), url's are optional.