Create an image with custom text in PHP

May 03, 2014 | Last tested: May 2015 | 1063 views | Comments

Write custom text in a generated image with PHP using the function imagestring().

For example.

Create a PNG image, write some text on it, and save it to a file.

//set the desired width and height
$width = 500;
$height = 300;

//set the font size | possible values 1,2,3,4, and 5, where 5 is the biggest
$fontSize = 4;

//set the text
$text = "";

//set the x and y positions of the text
$xPosition = 0;
$yPosition = 0;

//create a new palette based image
$newImg = imagecreate($width,$height);

//set the image background color to black
$bgColor = imagecolorallocate($newImg, 0, 0, 0);

//set the font color to red
$fontColor = imagecolorallocate($newImg, 255, 0, 0);

//write the text on the created image
imagestring($newImg, $fontSize, $xPosition, $yPosition, $text, $fontColor);

//output the image to a file

//destroy an image


Please mouse over here to view the image.