Dynamic Images with PHP
You may or may not have noticed that my headerchanges slightly everytime you load the page. If you want to check it out, go ahead I’ll wait.
Ok, so now that you have checked it out, I will show you how it is done using php (I’m sure that some of you are curious).
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php $text[1] = "Squirrel Hacker"; //this is so that you can have it do a random font every time if you want $fontfile[1] = "sidewalk.ttf"; //size of the image $width = 760; $height = 100; //create the image $im = ImageCreate ( $width, $height ); //set the background ImageColorAllocate ( $im , 0, 0, 0 ); //this way if you wanted, you could use a random colour $colours[1] = ImageColorAllocate ( $im , 255 , 255 , 255 ); header("Content-Type: image/png"); srand(time()); //random font size $size=rand(20,40); //random location of the text $x=rand(0,200); $y=rand(50,100); //put the text on the image ImageTTFText ($im, $size, 0, $x, $y, $colours[1], $fontfile[1], $text[1]); //return the image ImagePNG($im); ?> |
Most of it is self explanatory, but some of the interesting lines are 9, where we create the image with the set width and height and store it in a variable called $im, then on 11 we fill the image with an rgb value (0,0,0) in this case. Line 14 then creates a variable using teh ImageColorAllocate function, which was previously used to fill the background. This variable is later used to colour the text that is added to the image. We also have to tell the browser what kind of image it is (line 16), this unfortunately means that it is more difficult to add to a webpage (without it spitting out header already sent errors). To get around those errors, you display the image using:
<img src="imagegenerator.php" alt="My image" width="760" height="150" />
Finally we built the rest of the image on line 25 and display it on 27 using the ImagePNG function (because we told the browser it was a png on line 16). Nice and simple.
Man, I should really test these things out locally before putting them on my site… the problem is that the header image needs to be absolutely referenced apparently, so that the image shows up…
All fixed!