This tutorial will show you to use GD Library in PHP. GD is used to create a dynamic image using PHP. You can make anti-bot security image, charts and so on. First of all, make sure that your server supports this library using:
<?php
phpinfo();
?>
I am using GD library because it’s very easy to use.
In order to insert an image made using PHP GD library you can do the following:
HTML:
<img src="img.php" alt="First image using GD library">
Now let’s create our first image:
<?php
header ("Content-type: image/jpeg");
$img = ImageCreate (100,100);
$fond = ImageColorAllocate ($img,0,0,0);
ImageJPEG ($img, '', 100);
?>
First I’m creating the image (a square with 100×100 dimension) using ImageCreate and I’m keeping it in $img. After that in $fond I’m putting image’s color (black) using 0, 0 , 0 combination. The format is RGB from 0 to 255 decimal numbers. After that I show the image in browser using ImageJPEG which means the image displayed will be a jpeg with “best quality” – 100.
Next:
<?php
header ("Content-type: image/jpeg");
$img = ImageCreate (100,100);
$fond = ImageColorAllocate ($img,0,0,0);
$text = ImageColorAllocate ($img,255,255,255);
ImageString ($img,5,5,5,"test",$text);
ImageJPEG ($img, '', 100);
?>
Now I added text to the previous image.
$text variable keeps the font color. After that I can add the text using ImageString that receives as parameter:
$img = the image
Three digits separated by “,” = first digit the size of the font; second and third – position on X and Y.
“test” = the text written on the image.
You can also:
- create lines inside the image using ImageLine.
- create ellipses using ImageEllipse.
- create images using from another image.
<?php
header("Content-Type: image/jpeg");
$im = ImageCreateFromJpeg("image.jpg");
$text="Test";
$color = ImageColorAllocate($im, 0, 0, 0);
$start_x = 20;
$start_y = 80;
Imagettftext($im, 18, 10, $start_x, $start_y, $color, 'verdana.ttf', $text);
Imagejpeg($im, ' ', 100);
ImageDestroy($im);
?>
With this I am creating a new image that has image.jpg as background an adding text which has black font, verdana type, positioned at 20px on X and 80px on Y.
Also the text has a “turning” of 10 degrees.
Check:
http://php.net/manual/en/book.image.php
for a complete list of available functions.
In a future tutorial I will show you how to use this and create a security image.
I hope you enjoyed this tutorial that showed a little about GD library in PHP.
Leave a Reply