In this post we will see how to create an image in PHP. Creating an image is comes in use when we think to generate captcha in PHP. Before we create an image there many function about which have to know and understand its functionality. Here in this tutorial we will discuss about each function and its functionality. It is also possible when create an image we can define height, width , background and text colour etc.
Before we discuss about snippet we see each function which will be used to generate an image.
Have a look.
imagecreate ($width , $height) – Create an image with given width and height.
Imagecolorallocate(resource $image , int $red , int $green , int $blue ) — allocate a color for resource image with RGB components.
imagestring(resource $image , int $font , int $x , int $y , string $string , int$color ) — Draw a string horizontally
In above snippet $x and $y are co-ordinates of upper left corner which is used to fix the position of string.
$image is resource in which $string value be will written.
$color is used here to define text color of string.
imagepng (resource $image ) – it used to output a PNG image either to browser or a file.
imagedestroy(resource $image ) – It is used to destroy an image.
Now see the snippet to understand better for create an image in PHP.
<?php $myimg = imagecreate (200,50); $background = imagecolorallocate ($myimg,50, 50, 160); // background color $text_color = imagecolorallocate ($myimg, 255, 260, 0); // text color imagestring($myimg,50,15,15,"Vikash Kumar Singh",$text_color); // string added to image header ("Content-type: image/png"); imagepng ($myimg); // image displayed imagedestroy($myimg); // destroy an image to remove allocated memory. ?>
Above code will successfully create a PNG image of width(200) and height(50). This image can be called to any webpage with reference of PHP file in which image is created. File in which image is created we named it image.php and we can simply call to any other page .See below code to understand it.
<img src="image.php" alt="Image created from PHP Script">
This will get image to be display where we put this code with php file path. Here we create an index.html file and call this image from PHP file. That’s all. By follow these steps we can create in PHP.
If you liked this article 🙂 please share with your friends and colleagues 🙂 . If you have any query please write in comment.