Create an image in PHP

create image in php aj tutorials

This tutorial will show you how to create a simple image with PHP’s GD Library

First we will create a 200×200 canvas for the image with a background color


$image = imagecreate( 200, 200 );
$background = imagecolorallocate( $image, 255, 125, 0 );

The ‘imagecolorallocate’ is the GD Library function used to define a colour for an element

now we will add some text in the image


$text_color = imagecolorallocate( $image, 160, 0, 0 );
imagestring( $image, 5, 20, 80, "ajarunthomas.com", $text_color );

Here 5 is the font-size of the text. You can provide values ranging from 1 To 5. 20 and 80 are the x and y cordinates representing the point
from where the text should appear.

Lets add a line above and below the text


$line_color = imagecolorallocate( $image, 55, 55, 55 );
imagesetthickness ( $image, 2 );
imageline( $image, 10, 20, 170, 20, $line_color );
imageline( $image, 10, 180, 170, 180, $line_color );

‘imagesetthickness’ sets the thickness for the line and ‘imageline’ draws the line

The second and third parameters in ‘imageline’ denotes the x,y coordinate where the line starts and the fifth,sixth parameters denotes the
coordinates where the line ends.

And finally to generate the image


header( "Content-type: image/png" );
imagepng( $image );

So the final code looks as below


$image = imagecreate( 200, 200 );
$background = imagecolorallocate( $image, 255, 125, 0 );

$text_color = imagecolorallocate( $image, 160, 0, 0 );
imagestring( $image, 5, 20, 80, "ajarunthomas.com", $text_color );

$line_color = imagecolorallocate( $image, 55, 55, 55 );
imagesetthickness ( $image, 2 );
imageline( $image, 10, 20, 170, 20, $line_color );
imageline( $image, 10, 180, 170, 180, $line_color );

header( "Content-type: image/png" );
imagepng( $image );

If you want to save the file, then


imagepng( $image, "php_image.png" );

If you want to generate elements on an existing image, then instead of creating a blank canvas you can load an image at the first place


$image = imagecreatefrompng ("random_image.png");

Leave a Reply

Your email address will not be published.