Create Image using PHP

Total Views : 43
Zoom In Zoom Out Read Later Print

In this tutorial, we learn how to create a simple image using PHP GD Library. Generating a dynamic image using PHP can be useful for many purposes e.g. default profile image using the name of the user, a captcha code image.

For this code to work you should have PHP GD extension enabled. if you are using XAMPP you need to look for extension=gd2 and remove ';' from the front of it. if you are on a shared server you can ask the provider to enable if it is not or from cPanel.

Functions Used

1. ImageCreate(width, height) : Create image with width and height provided in the parameter.
2. ImageFill(image source, 0, 0, color) : Background color of image.
3. ImageString(image source, font size, angle, x axis, y aixs, text color, font path, string) : Function for display text on an image.
4. ImageJpeg(image source) : Output the newly created image in jpeg format.
5. ImageDestroy(image source) : Free up resources.

ImageCreate()

//Create the image resource
$image = ImageCreate($width, $height); 

ImageFill()

//Make the background white
ImageFill($image, 0, 0, $white);

ImageString

//Add randomly generated string in black to the image
ImageString($image, 36, 80, 40, $pass, $black); 

header

//Tell the browser what kind of file is come in 
header("Content-Type: image/jpeg"); 

ImageJpeg

//Output the newly created image in jpeg format
ImageJpeg($image);

ImageDestroy

//Free up resources
ImageDestroy($image);

index.php

<?php
	function create_image() {
 
		//Let's generate a totally random string using md5
		$md5 = md5(rand(0,999)); 
		 
		//We don't need a 32 character string so we trim it down to 5
		$pass = substr($md5, 10, 5); 
		 
		//Set the image width and height
		$width = 200;
		$height = 100; 
		 
		//Create the image resource
		$image = ImageCreate($width, $height);  
		 
		//We are making three colors, white, black and gray
		 
		$white = ImageColorAllocate($image, 255, 255, 255);
		 
		$black = ImageColorAllocate($image, 0, 0, 0);
		 
		$grey = ImageColorAllocate($image, 204, 204, 204);
		 
		//Make the background white
		ImageFill($image, 0, 0, $white); 
		 
		//Add randomly generated string in black to the image
		ImageString($image, 36, 80, 40, $pass, $black); 
		 
		//Throw in some lines to make it a little bit harder for any bots to break
		ImageRectangle($image,0,0,$width-1,$height-1,$grey); 
		
		//Horizontal line
		imageline($image, 0, $height/2, $width, $height/2, $grey); 
		
		//Vertical line
		imageline($image, $width/2, 0, $width/2, $height, $grey); 
		 
		//Tell the browser what kind of file it is 
		header("Content-Type: image/jpeg"); 
		 
		//Output the newly created image in jpeg format
		ImageJpeg($image);
		   
		//Free up resources
		ImageDestroy($image);
	}
 
	create_image();
?>

You can download the PHP project from below link.

See More

Latest Photos