Code to dynamically create image in PHP

  1. Previous
  2. Next
  3. Recent

    1. Signs 'He' May be Cheating on You
    2. 7 Vows of Hindu Marriage - Know What 'Saat Vachans' Mean
    3. RuPay vs Visa vs Mastercard vs American Express- A Comparison
    4. What is RuPay? Everything You Need to Know About India's Domestic Payment System!
    5. Top 10 Online Portals to Find a High Paying Job in India
    6. Top Indians who Revolutionized the IT Sector in India
    7. 8 Initiatives by Narendra Modi that Could Change the Future of the Nation
    8. 8 Work-from-home Jobs for Housewives, Students, and Part timers
    9. Complete Company Registration Process in India - Explained
    10. Change Name in India in 5 Steps - Filing Affidavit, Newspaper Ad & Gazette Notification

PHP is probably the most used programming language simply because of the ease with which it allows you to different things. One such awesome use is creating image dynamically with just a few lines of code.

The code


 $img=imagecreate(265,25) or die("Image failed to create");
 $b_color=imagecolorallocate($img, 50, 94, 174);
 $t_color=imagecolorallocate($img, 255, 255, 255);
 header("Content-Type: image/png");
 imagestring($img, 3, 5, 5, "This is text string", $t_color);



dynamically create image in php

Code Explained

  1. First we call the imagecreate(x, y) function that takes the height and width of image as parameter. Program execution terminates with die() function if the image fails to create at this step. [LOC 3]
  2. In the next two steps we set colors with imagecolorallocate(image_id, R, G, B). One will be the background and the other one will be text color. We can also set background-shadow color for the text using imagettftext(). You can read more about this on the php website. [LOC 4-5]
  3. In the example, we will be displaying the image. So we need to tell the browser that an image byte code is to be displayed as image, not the usual text data. So we put header(“Content-Type: image/png”) in the code. [LOC 6]
  4. imagestring() function writes string to the image. It takes 6 parameters – image identifier, font-size, font x-coordinate, font y-coordinate, text_string, text_color. [LOC 7]
  5. imagepng() function will create image. This is only for png images. For jpeg, we have imagejpeg(), and there are similar functions for other image formats as well. [LOC 8]
  6. In last step, we deallocate all resources used in the program with imagedestroy() function. This is optional. [LOC 9]
blog comments powered by Disqus