Create image
from text on fly -Image processing in PHP
Before you start this lesson, before read the lesson PHP
Image processing introduction and make sure you enable GD library.
This tutorial will demonstrate how to create image from
client input text and shows the image on the same input page. See
the following working demo.
Input Form
First, we create a Form to accept input from users.
(If you have read Working with Forms ,
you should be feel familiar with $_POST[]).
<html>
<body>
<form action="" method="post">
<input type="text" name="inputtext" maxlength="20">
<input type="submit" name="create" value="create">
</form>
<?php
if(isset($_POST['create']))
{
//trim space from ends of input
$input=trim($_POST['inputtext']);
//basic input checking
if(strlen($input)==0)
echo "Empty String";
else
echo "<img src=\"createimage.php?text=$input\">";
}
?>
</body>
</html> |
After we get user's input, we remove the trailing spaces
from the input and check if input text length is 0 or not. If it is
0, we print out "Empty String". Otherwise, we present the image created
from the input.
Create image from text input
The following is PHP code to create image on fly. Save it as createimage.php.
<?php
// 200 is width / 30 is height
$TheImage = Imagecreate("200", "30");
// Color image background blue.
$ColorImage = imagecolorallocate($TheImage, 0,0,255);
// Color the text white
$ColorText = imagecolorallocate($TheImage, 255, 255, 255);
//get user input text
$text=$_GET['text'];
//select font file
$font="arial.ttf";
//add grey shadow
$grey = imagecolorallocate($TheImage, 128, 128, 128); //grey
shadow
imagettftext($TheImage, 14, 0, 6, 21, $grey, $font, $text);
//add text to image
imagettftext($TheImage, 14, 0, 5, 20, $ColorText, $font, $text);
// Let the browser know that it is an
PNG image..
header("Content-Type: image/png");
imagepng($TheImage); // output to browser.
?>
|
The above code created an image of 200 * 30, with blue background
, white foreground and grey shadow. The reason we print out PNG image
is that PNG image is sharper.
You may use imagejpg(),imagegif() to
print out JPG or GIF file to browser. Just remember to change header()
correspondingly like header("Content-Type: image/jpg")
or header("Content-Type:
image/gif").
The fond file is arial.ttf, which is TrueType
font. You may use any font file your choose so that you could customize
the result image.
You may use the above code to create dynamic buttons on fly. This
is an easy trick in PHP image processing. |