0% found this document useful (0 votes)
5 views

Create Simple Image Using PHP

Uploaded by

poerwantono
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Create Simple Image Using PHP

Uploaded by

poerwantono
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Create Simple Image using PHP

Webslesson 02:20 php 1 comment

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().'" />';
?>

You might also like