Create solid color image in PHP

Not related to teaching, but I needed a little snippet of code earlier this week that would create a PNG image using PHP for another site that I’m working on.  I was working on creating open graph tags for several of the pages and wanted to use solid color swatches.

The GD library made it pretty easy.

$red = 100;
$blue = 150;
$green = 200; 
$my_img = imagecreate( 1000, 1000 );
$background = imagecolorallocate( $my_img, $red, $green, $blue );
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $my_img, $background );
imagedestroy( $my_img );

The first 3 lines define the red, green and blue values in the range between 0 and 255, inclusive. For the actual site I used mod_rewrite so that the filename matched the color requested. But for a demo, this is close enough.

imagecreate creates an empty image that’s then filled with the defined color.

A content-type header of image/png is sent to the browser so that it knows it’s a PNG image.

The data is then sent, the image is destroyed and the script ends with die. Newsletter

Want to stay in touch and keep up to date with the latest posts @

Leave a Reply

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