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.
<?php $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); imagepng($img); imagedestroy($img); ?>
- 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]
- 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]
- 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]
- 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]
- 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]
- In last step, we deallocate all resources used in the program with imagedestroy() function. This is optional. [LOC 9]