[Tutorial] How to make an image with PHP

Reputation
0
You might have been making PHP images before, but each time you want to one you have to look up a source.
Well I'm here to change that. I'm going to try to make this tutorial as HQ, understandable, step-by-step and organized as possible.
Let's get started.

1. The first tings you need (Required)
To make the browser understand that it is an image you're sending, and not HTML, you have to modify the headers being sent to the browser.
That can easily be done by doing this:
PHP:
header("Content-type: image/png");

Now for the actual image.
You have two options. You can either make an image with a flat color as background, or you can load an already existing image.
I will show you both methods.

Create blank image
PHP:
$img = imagecreatetruecolor($width, $height);

Create an image from an already existing file
PHP:
$img = imagecreatefrompng($filename);

2. Adding elements to the image (Optional)
Specifying a color
PHP:
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$blue = imagecolorallocate($img, 0, 0, 255);
$yellow = imagecolorallocate($img, 255, 255, 0);
$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);

Text
PHP:
imagettftext($img, $size, $angle, $x, $y, $color, $font, "Text here");
// Font has to be a TTF file, e.g. font.ttf

Line
PHP:
imageline($img, $firstPointX, $firstPointY, $secondPointX, $secondPointY, $color);

Rectangle
PHP:
imagerectangle($img, $firstPointX, $firstPointY, $secondPointX, $secondPointY, $color);

Fill
PHP:
imagefill($img, $startX, $startY, $color);

3. The final stuff (Required)
Save the image to the server *
PHP:
imagepng($img, $location);

Output the image to the browser *
PHP:
imagepng($img);

Clean up
PHP:
imagedestroy($img);

* Choose one of the methods with a green asterisk.

Here's the final script
PHP:
<?php
	header("Content-type: image/png");
	$img = imagecreatetruecolor(250,40);

	$green = imagecolorallocate($img, 0, 255, 0);
	$red = imagecolorallocate($img, 255, 0, 0);

	imagefill($img, 0, 0, $green);
	imagettftext($img, 20, 0, 5, 25, $red, "font.ttf", "A PHP image? :o");

	imagepng($img);
	imagedestroy($img);
?>

I hope this will help someone
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…