Creating Images with PHP-Part 3
Written by admin on December 21, 2008 – 8:45 pm -
Its been a while since I wrote part 2 of this series and its time to move full speed ahead and go all out with user input to create images with the help of php. In this article, we will accept nothing but user input to create an image. We will want the user to be able to:
- Choose the width and height
- OR choose a pre made background image
- Choose the font-type (we will embed fonts today!) and font-size
- Choose the background color and font color
- Choose the text and text starting position
Dont be put off be all this options, it actually doesnt require as much code and time as you might think!
1. Create the basic HTML setup
So first things first, we will set up the basic markup of our form and html page, it wont be pretty yet, but you can handle that later
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="author" content="Drew Douglass" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>Create Image via php Form!</title> <style type="text/css" media="screen"></style> </head> <body> <h1>Use the form below to create your own custom image via php!</h1> <form name="rgb" method="post" action="<?php echo $_SERVER['php_self']?>"> <p><strong>Image Size</strong></p> <p>Width: <input type="text" name="width" /> Height:<input type="text" name="height" /></p> <p><strong>OR...Choose your own BG Image</strong></p> Enter the image URL (must be PNG only):<input type="text" name="url" /> <p><strong>Background Color</strong></p> Enter the Hex value and click convert: <input type="text" name="hex" value="FFFFFF" /> <input type="button" name="btn" value="Convert to RGB" onCLick="this.form.r.value=HexToR(this.form.hex.value); this.form.g.value=HexToG(this.form.hex.value); this.form.b.value=HexToB(this.form.hex.value);"> <p>Red<input type="text" name="r" /> Green <input type="text" name="g" /> Blue <input type="text" name="b" /></p> <p><strong>Text Color:</strong></p> Enter the Hex value and click convert: <input type="text" name="hex2" value="FFFFFF" /> <input type="button" name="btn" value="Convert to RGB" onCLick="this.form.r2.value=HexToR(this.form.hex2.value); this.form.g2.value=HexToG(this.form.hex2.value); this.form.b2.value=HexToB(this.form.hex2.value);"> <p>Red<input type="text" name="r2" /> Green <input type="text" name="g2" /> Blue <input type="text" name="b2" /></p> <p><strong>Font Size:</strong></p> <p> <select name="fontSize"> <option value="10">10</option> <option value="15">15</option> <option value="20">20</option> <option value="25">25</option> <option value="30">30</option> <option value="35">35</option> <option value="40">40</option> <option value="45">45</option> <option value="50">50</option> <option value="55">55</option> <option value="60">60</option> <option value="65">65</option> </select> <p><strong>Font Type</strong></p> <select name="fontType"> <option value="GeosansLight.ttf">Default (clean and simple).</option> <option value="SPETETRIAL.ttf">Grungy</option> <option value="ALBA.TTF">Retro</option> <option value="Jellyka_Estrya_Handwriting.ttf">Handwritten</option> <option value="FontdinerdotcomSparkly.ttf">Sparkly</option> </select> </p> <p><strong>Text Position</strong></p> <p>X-axis:<input type="text" name="x" /> Y-axis<input type="text" name="y" /></p> <p><strong>Text String</strong></p> <p><input type="text" name="string" /></p> <p><input type="submit" name="submit" value="Submit!" /></p> </form> </body> </html>
Dont worry about any of the Javascript onclick functions you see yet. We will get to those soon.
Take some time to go over all the html above and you should see all of the options we are going to accept. You will also note every name section is unique so we can identify it with php when the form is submitted.
2. Some help from Javascript
If you think back to the previous lessons, you will remember most of the php functions we use to create the images accept color values in RGB format. This is fine, but most designers know colors by their hex value. Rather than making them covert it themselves, we will use some simple javascript to covert it for the user. A simple google search reveals this script that we will use. Insert the below into the head section of your html file.
<script type="text/javascript">
<!--
//Thanks to http://www.javascripter.net/faq/hextorgb.htm for this great script!
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) { return parseInt((cutHex(h)).substring(0,2),16) }
function HexToG(h) { return parseInt((cutHex(h)).substring(2,4),16) }
function HexToB(h) { return parseInt((cutHex(h)).substring(4,6),16) }
function cutHex(h) { return (h.charAt(0)=="#") ? h.substring(1,7) : h}
//-->
</script>
The onclick values will now work as expected with our new javascript
3. Inserting the PHP
First we need to find out if the form is being submitted or not, so add this above all of your html.
<?php
if(!isset($_POST['submit'])){
?>
Now at the very bottom of your page insert this:
<?php }
Basically what we did was display the form if it is not being submitted or else perform other functions (which we will do now).
4. Creating the image
Lets add on to the last snippet of php we added to give us this:
<?php }
else {
$url=$_POST['url'];
//Create Image
if(!empty($_POST['url'])){
$ourImage=ImageCreateFromPng($url);
}
else {
$ourImage=ImageCreate($_POST['width'], $_POST['height']);
}
You will remember that we are giving the user the option to use a premade image as the background or choose their own color. So, above we set the $ourimage variable depending on wether or not they are using a premade image.
5. Set up the colors and text string.
Moving on, lets set up the colors via the user input and text stringby adding on to our exisiting code.
//Set up Colors $bgImage=ImageColorAllocate($ourImage,$_POST['r'], $_POST['g'], $_POST['b']); $textColor=ImageColorAllocate($ourImage,$_POST['r2'], $_POST['g2'], $_POST['b2']); //Create String on BG imagettftext($ourImage, $_POST['fontSize'], 0, $_POST['x'], $_POST['y'], $textColor, $_POST['fontType'], $_POST['string']);
6. Clean up and output the image
Believe it or not thats all we need to create a basic image and achieve all of our goals. Now we just need to clean up and finish the script:
//Output header
header("Content-type:image/png");
ImagePNG($ourImage);
//Clear up memory
ImageDestroy($ourImage);
}
?>
A note about the fonts.
You will notice we had some cool font effects and options. We used php to embed the font and draw it into the image via the “imagettftext()” function. We also uploaded the true type fonts onto our server so php had access to them. Read more about using true type fonts with php at the manual.
Full Code
Here is our full working php and html code
<?php
if(!isset($_POST['submit'])){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" content="Drew Douglass" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<title>Create Image via php Form!</title>
<script type="text/javascript">
<!--
//Thanks to http://www.javascripter.net/faq/hextorgb.htm for this great script!
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) { return parseInt((cutHex(h)).substring(0,2),16) }
function HexToG(h) { return parseInt((cutHex(h)).substring(2,4),16) }
function HexToB(h) { return parseInt((cutHex(h)).substring(4,6),16) }
function cutHex(h) { return (h.charAt(0)=="#") ? h.substring(1,7) : h}
//-->
</script>
<style type="text/css" media="screen"></style>
</head>
<body>
<h1>Use the form below to create your own custom image via php!</h1>
<form name="rgb" method="post" action="<?php echo $_SERVER['php_self']?>">
<p><strong>Image Size</strong></p>
<p>Width: <input type="text" name="width" />
Height:<input type="text" name="height" /></p>
<p><strong>OR...Choose your own BG Image</strong></p>
Enter the image URL (must be PNG only):<input type="text" name="url" />
<p><strong>Background Color</strong></p>
Enter the Hex value and click convert:
<input type="text" name="hex" value="FFFFFF" />
<input type="button" name="btn" value="Convert to RGB"
onCLick="this.form.r.value=HexToR(this.form.hex.value);
this.form.g.value=HexToG(this.form.hex.value);
this.form.b.value=HexToB(this.form.hex.value);">
<p>Red<input type="text" name="r" /> Green <input type="text" name="g" /> Blue <input type="text" name="b" /></p>
<p><strong>Text Color:</strong></p>
Enter the Hex value and click convert:
<input type="text" name="hex2" value="FFFFFF" />
<input type="button" name="btn" value="Convert to RGB"
onCLick="this.form.r2.value=HexToR(this.form.hex2.value);
this.form.g2.value=HexToG(this.form.hex2.value);
this.form.b2.value=HexToB(this.form.hex2.value);">
<p>Red<input type="text" name="r2" /> Green <input type="text" name="g2" /> Blue <input type="text" name="b2" /></p>
<p><strong>Font Size:</strong></p>
<p>
<select name="fontSize">
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
</select>
<p><strong>Font Type</strong></p>
<select name="fontType">
<option value="GeosansLight.ttf">Default (clean and simple).</option>
<option value="SPETETRIAL.ttf">Grungy</option>
<option value="ALBA.TTF">Retro</option>
<option value="Jellyka_Estrya_Handwriting.ttf">Handwritten</option>
<option value="FontdinerdotcomSparkly.ttf">Sparkly</option>
</select>
</p>
<p><strong>Text Position</strong></p>
<p>X-axis:<input type="text" name="x" />
Y-axis<input type="text" name="y" /></p>
<p><strong>Text String</strong></p>
<p><input type="text" name="string" /></p>
<p><input type="submit" name="submit" value="Submit!" /></p>
</form>
</body>
</html>
<?php }
else {
$url=$_POST['url'];
//Create Image
if(!empty($_POST['url'])){
$ourImage=ImageCreateFromPng($url);
}
else {
$ourImage=ImageCreate($_POST['width'], $_POST['height']);
}
//Set up Colors
$bgImage=ImageColorAllocate($ourImage,$_POST['r'], $_POST['g'], $_POST['b']);
$textColor=ImageColorAllocate($ourImage,$_POST['r2'], $_POST['g2'], $_POST['b2']);
//Create String on BG
imagettftext($ourImage, $_POST['fontSize'], 0, $_POST['x'], $_POST['y'], $textColor, $_POST['fontType'], $_POST['string']);
//Output header
header("Content-type:image/png");
ImagePNG($ourImage);
//Clear up memory
ImageDestroy($ourImage);
}
?>
Demo has been removed. You’ll need to test this on your own server and sanitize the user input before going live with it. Sorry for any inconvenience but I don’t want to take the security risk.
Extra Credit
You’ll notice the only URL type accepted is a .png, you could clean up and validate all file type for a more versatile script. Also style it up and make it look nice, then link to it and the comments and show it off
I hope you enjoyed this part. Depending on the response and questions, I am considering continuing this series, let me know what you think!
Continues Below...
Posted in PHP Tutorials, Web Development |






December 23rd, 2008 at 3:09 pm
Excellent content here and a nice writing style too - keep up the great work!
December 23rd, 2008 at 7:14 pm
Might I suggest having default values. You get a whole crap load of errors in the demo if you don’t enter all the values.
December 23rd, 2008 at 7:17 pm
Hi Vasili,
Yes your correct, sorry about that. I got so wrapped up in writing the code I didnt put any thought into blank fields. I think a part 4 is probably necessary
Thanks for your comment.
January 2nd, 2009 at 12:05 pm
Not only default values, also descent error handling. Error handling needs to be implanted at the moment you are writing code.
You should also turn php errors of on a live running server.
January 9th, 2009 at 9:47 am
I cant download it. It just opens it as a test file, and when I right click and “Save Link As” it saves as html… but I copied the code into notepad, and uploaded to my site, it won’t work because I dont have the fonts.
January 9th, 2009 at 2:11 pm
@brenden-
Sorry, it looks like the download link got a little messed up, I’ll put it back up.