Friday, 29 January 2016

Create Simple Image using PHP



Hello Friends today we learn how to create simple Image using PHP GD Library. This type of generating dynamic image using php can be useful for many purpose e.g. Captcha Code Image
First we sholud enable php gd2 php extension.
I will use following php function for generating Image using PHP
  • imagecreate(width, height)
  • imagecolorallocate(image source, R, G, B)
  • imagettftext(image source, font size, angle, x axis, y aixs, text color, font path, string)
  • imagepng(image source)
  • imagedestroy(image source)
Now I write PHP code.
First I define Image using image create function with width 200 and height 80.

 $image = imagecreate(200, 80);  

Then after I define background color using image color allocate function. In this function first parameter is image source and other parameter is value of RGB color.

 imagecolorallocate($image, 240, 56, 125);  

Now I define textcolor using imagecolorallocate function.

 $textcolor = imagecolorallocate($image, 255,255,255);  
I will use imagettftext() function for display text on string. For this we want to download font and store in our working folder.
Now I use imagettftext function for display text on Image. In this function first parameter is image source, second is font size, third is angle, fourth is x axis, fifth is y axis, sixth is text color, seventh is font path and last is string.


 imagettftext($image, 28, 0, 55, 55, $textcolor, 'arial.ttf', rand(1000, 9999));  

Now I define content type using header function.

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

Now I define image type using imagepng function.

 imagepng($image);  

Lastly I use image destroy function for destroy image.

 imagedestroy($image);  

Finally I have function for create image.
Now we want to display image in image html tag by calling this function.

 echo '<img scr="'.create_image().'" />';  


Complete PHP Code



 <?php  
 function create_image()  
 {  
      $image = imagecreate(200, 80);  
      imagecolorallocate($image, 240, 56, 125);  
      $textcolor = imagecolorallocate($image, 255,255,255);  
      imagettftext($image, 28, 0, 55, 55, $textcolor, 'arial.ttf', rand(1000, 9999));  
      header("Content-type: image/png");  
      imagepng($image);  
      imagedestroy($image);  
 }  
 echo '<img scr="'.create_image().'" />';  
 ?>  

1 comment:

  1. Hello sir. My problem is i write your commands but this screen came https://i.hizliresim.com/va5lW4.png

    ReplyDelete