How can I generate images with PHP?

I’d like to have an image on my website that gets updated with different text based on the current user. My website is built in PHP. Can I do this?


I got a question from a friend who works for a web development company and was building a website for an insurance firm. He was preparing a page that showed off car insurance and wanted to have an image with a dynamically generated value on it showing different savings based on user input.

Producing an image with PHP isn’t all that hard. Here’s some sample code that we’ll use as reference:
< ?php
header("Content-type: image/png");
$print_value = "Save 15%"; // this can be changed as needed
$img = imagecreatefrompng("backdrop.png");
$orange = imagecolorallocate($img, 220, 210, 60);
$new_pic = (imagesx($img) - 7.5 * strlen($print_value)) / 2;
imagestring($img, 3, $new_pic, 9, $print_value, $orange);
imagepng($img);
imagedestroy($img);
?>

That’s not too many lines of code, is it? And calling it is just as easy. Let’s say the code above is saved in a file called make_image.php. All you have to do is add the tag <img src=”make_image.php”/> to your HTML code, and you’re done!

Here’s a quick explanation of what the code does. The first line sets your HTTP header so that a browser will interpret the data coming from the PHP file as an image (.PNG to be exact). It then proceeds to build the image based on a background image and some text that is specified in the code. This is then output to the browser and memory used for the image cleared at the end of the process. It’s quite easy to adapt this to your needs once you understand what the code is doing.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.