Create an image with PHP

April 26, 2014 | Last tested: May 2015 | 892 views | Comments

With the help of the GD library, it is possible to create a JPG, GIF, or PNG image in PHP. Either output the generated image to a browser or to a file.

For example.

Create a JPG image and output it directly on the browser on an img tag.

Create two files, one PHP file which will generate the image, and one HTML file that will display the generated image.

1. PHP file, save as image.php

/*
 * save this as image.php
 */

//set the desired width and height
$width = 400;
$height = 300;

//create a new palette based image
$newImg = imagecreate($width,$height);

//set the image background color to red
$bgColor = imagecolorallocate($newImg, 255, 0, 0);

//set the header content type
header("Content-Type: image/jpeg");

//output the image
imagejpeg($newImg);

//destroy the image
imagedestroy($newImg);

2. HTML file, save as image.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Create an image with PHP - ConsistentCoder.com</title>
	</head>

	<body>
		<!--
		 * save this as image.html
		 -->

		<!-- generate and load the image -->
		<img src="image.php">
	</body>
</html>

Once the file image.html is opened, the result will be like the one below.

Please mouse over here to view the image.

 

Other Example

Create a GIF image and save it as myImage.gif.

//set the desired width and height
$width = 200;
$height = 300;

//create a new palette based image
$newImg = imagecreate($width,$height);

//set the image background color to blue
$bgColor = imagecolorallocate($newImg, 0, 0, 255);

//save the image
imagegif($newImg,"myImage.gif");

//destroy the image
imagedestroy($newImg);

Result.

Please mouse over here to view the image.

 

To save the image inside a folder or directory named images.

  • Change this.
    //save the image
    imagegif($newImg,"myImage.gif");
    
  • To this.
    //save the image
    imagegif($newImg,"images/myImage.gif");
    

 

Notes:

Differences between outputting the image to a browser and saving it to a file.

  • The header Content-Type is not needed when saving the image to a file.
    //this line is not needed when saving the image to a file
    header("Content-Type: image/gif");
    
  • When saving the image to a file, a second parameter is required upon creating the image (imagegif() for example), where it has the name and the path where to save the file.
    //myImage.gif is required if the image should be saved
    imagegif($newImg,"myImage.gif");