Dynamic images with PHP

marshian

New Member
Messages
526
Reaction score
9
Points
0
Introduction to dynamic images using PHP.
Based on the creation of this example:
ipimg.png


Required knowledge:
- PHP at more then average level
- An image manipulation program (eg. GIMP or PSP X2)
- The ability to be able to use this program

Index:
== Introcuction ==
== Makeing it ==
== Tips & Tricks ==
== FAQ ==

== Introduction ==

Ok, in this tutorial I'm going to show you how to create dynamic images using PHP.
First of all, what are dynamic images?
- An example of dynamic images is the image shown above. This image shows your ip, isp, and some other text, but if you see it on different computers, or even on the same computer, but with a different ip, ... there's a difference in the image. You could try downloading the image, and then you'ld notice it doesn't work any more. 'Why doesn't it work any more?' is then the logical question. The answer is easy, you're not looking at an image, you're looking at the result of a PHP script.

'PHP is for webpages.'
- Clearly you've never heard of the header() function... This will be explained later on.

== Makeing it ==

First of all we should determine what we need. In this particular example, we want an image of a crazy (maybe a little stoned) guy and there's supposed to appear text on the image, depending on information from the user.
This tells us the following:
- We need a static background (of the crazy guy)
- We need dynamic text

So first things first, we can't add dynamic text to nothing, so we'll need to make a background. This is the part where you're supposed to be creative, but as I can't wait for you to make an image, I'll just give you my own background:
background.png

Note: in this example, we use png.

Ok, now we have a background, so we need text. How are we going to make this text? I've said it 10 times before, we're going to use PHP.

First comes the basic PHP, making some strings based on the user's IP. I suppose you know how to do this, so there's not really much of an explenation here.
(Note: the code of this example has been simplified a little, the origional source is MINE :p )

PHP:
<?php
$ip = $_SERVER["REMOTE_ADDR"];
$ihn = gethostbyaddr($ip);
$isp_temp = explode(".", $ihn);
$isp_temp = array_reverse($isp_temp);
$isp = "";
$continue = true;
$i = 0;
foreach($isp_temp as $piece) {
	if($i > 4)
		$continue = false;
	if(!$continue)
		break;
	if(strlen($piece) > 3) {
		$isp = $piece.".".$isp;
		$continue = false;
		break;
	}
	if($i > 0)
		$isp = ".".$isp;
	$isp = $piece.$isp;
	$i++;
}
$secs = rand(60, 120);
$text = Array(
		"You're $ip.",
		"You're also known as $ihn.",
		"Your isp is $isp.",
		"LocationScript is currently tracking you.",
		"Tracking should be completed in approximatly $secs seconds.",
		"This information has been logged.",
		"Thank you, come again!"
	);
?>

As we can all understand, the result of this script is text stored in $text.
key 0 : "You're "+your ip+"."
key 1 : "You're also known as "+your internet host name
key 2 : "Your isp is "+your isp+"."
key 3 : "LocationScript is currently tracking you."
key 4 : "Tracking should be completed in "+random int between 60 and 120+" seconds."
key 5 : "This information has been logged."
key 6 : "Thank you, come again!"

Of course, only 0-2 is actually true, we wouldn't want our poor user to end up being tracked by LocationScript and that information logged, do we?

Now we have text and an image, and it's time to add them together...

The first thing we would want to do is create an image object in PHP (it's not actually an image, it's a resource, but in this case the resource is an image, so we can safely assume it's an image object.)
As we've saved the background image as image/png, we'll need the function imagecreatefrompng().
PHP:
$image = imagecreatefrompng("background.png");
Now for drawing strings on an image, PHP has a function imagestring().
So to draw all strings on the image:
PHP:
imagestring($image,3 ,168 ,17 , $text[0], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,32 , $text[1], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,47 , $text[2], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,62 , $text[3], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,77 , $text[4], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,92 , $text[5], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,107 , $text[6], imagecolorallocate($image, 0,0,0));

And the result of all this is... an empty page...
(This is the point where you should not give up.)
Of course we get an empty page. We spend a lot of time into creating the image, but what did we do with it? Nothing. We 'might' want to output the result of all our labour to the user, and this is the code to do so:
PHP:
return $image;
Yeah, I know that's easy, you could have thought of that too, couldn't you? :p

Ok, let's run our example again...
And what do we get this time? IE8 is too smart, and makes an image of it... (I don't know about previous versions...)
But there's always at least one annoying browser if you made a code! This time, an example of them is FF. Any idea what you get if you open that in FireFox?
Exactly, a bunch of random gibberish, that vaguely represents... text?
Let's think about that for a second. Why would FF show text, and not an image? Of course, the standard MIME type of the output of a PHP script is text/html. IE8 is too smart and sees that it's in fact image/png, but FF beleives the headers and shows the file as text/html. We can safely assume all browsers rely on the MIME type, so we should change something about our code...
And once more, PHP has a function that solves our problem: header().
This function HAS to appear BEFORE ANY OUTPUT. If you fail to put it there, you'll get errors...
PHP:
header("Content-type: image/png");

This time, the output of our script is correct!

This is the full code:
PHP:
<?php
$ip = $_SERVER["REMOTE_ADDR"];
$ihn = gethostbyaddr($ip);
$isp_temp = explode(".", $ihn);
$isp_temp = array_reverse($isp_temp);
$isp = "";
$continue = true;
$i = 0;
foreach($isp_temp as $piece) {
	if($i > 4)
		$continue = false;
	if(!$continue)
		break;
	if(strlen($piece) > 3) {
		$isp = $piece.".".$isp;
		$continue = false;
		break;
	}
	if($i > 0)
		$isp = ".".$isp;
	$isp = $piece.$isp;
	$i++;
}
$secs = rand(60, 120);
$text = Array(
		"You're $ip.",
		"You're also known as $ihn.",
		"Your isp is $isp.",
		"LocationScript is currently tracking you.",
		"Tracking should be completed in approximatly $secs seconds.",
		"This information has been logged.",
		"Thank you, come again!"
	);
header("Content-type: image/png");
$image = imagecreatefrompng("background.png");
imagestring($image,3 ,168 ,17 , $text[0], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,32 , $text[1], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,47 , $text[2], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,62 , $text[3], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,77 , $text[4], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,92 , $text[5], imagecolorallocate($image, 0,0,0));
imagestring($image,3 ,168 ,107 , $text[6], imagecolorallocate($image, 0,0,0));
return imagepng($image);  
?>
Note: any character too much, and I mean any one character can make your image change into a red X. Don't put a space, tab, enter or any other character before or after the <?php and ?> tags!

== Tips & Tricks ==

If you call your PHP file "index.php", you can put it (and any other file required for the image) in a directory that's named like an image. For example the directory '/ipimg.png/'. You can then link to 'yoursite.com/ipimg.png', which looks better then 'yoursite.com/ipimg.php'. And it's certainly useful if you need more then one file to make your image. (For example 'index.php' and 'background.png': it's cleaner to put it in one directory.)

PHP has a lot more utils to work with images then the ones I've already mentionned. For the full list, and more information, go to http://www.php.net/manual/en/intro.image.php. (Thanks to verbsite)

No more tips & tricks at this point.

== FAQ ==

None at this point.


This is the end of this tutorial about dynamic images with PHP. I hope you learned something from it, but now I'm going to bed.

- Marshian
 
Last edited by a moderator:

Sohail

Active Member
Messages
3,055
Reaction score
0
Points
36
Nice tutorial! I'll give this a 9/10 for making everything simple and easy to understand.
 

LHVWB

New Member
Messages
1,308
Reaction score
0
Points
0
I have worked with dynamic images when I was creating some family tree software but this is a quite good tutorial, nice and easy to understand. ;)

Rep++ :)

For the more advanced programmer you can do a whole lot more with images such as change fonts, draw shapes and etc. Below is the official php manual on the image capabilities of php.

http://www.php.net/manual/en/intro.image.php
 
Last edited:

marshian

New Member
Messages
526
Reaction score
9
Points
0
I have worked with dynamic images when I was creating some family tree software but this is a quite good tutorial, nice and easy to understand. ;)

Rep++ :)

For the more advanced programmer you can do a whole lot more with images such as change fonts, draw shapes and etc. Below is the official php manual on the image capabilities of php.

http://www.php.net/manual/en/intro.image.php

Yeah, I forgot to put the link to the PHP's image functions...
Thanks for telling me, I'll add it ^^
 

knmtftw

New Member
Messages
2
Reaction score
0
Points
0
This image looks a lot like danasoft's one^^. Nice tutorial btw!
 

tcmstr134

New Member
Messages
59
Reaction score
0
Points
0
Very nice! I will try it out later when I have an image to put as a background.
 

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
you might also want to talk about fonts and use a destroy image after to remove it from memory...

I also made a tut a while ago, you can check it out in my sig
 
Last edited:

marshian

New Member
Messages
526
Reaction score
9
Points
0
you might also want to talk about fonts and use a destroy image after to remove it from memory...

I also made a tut a while ago, you can check it out in my sig

I might do that, and while I'm doing that, I could also talk about making different layers, setting filters, etc... but this isn't ment to be a tutorial on all possible ways to manipulate an image with php, it's only an introduction to it, so it must remain simple.

And destroying the image isn't really required, as you'ld have to put that command on the last line of the code, and the script is completed then, so php will free the used memory anyway...
 

S t e i n

New Member
Messages
6
Reaction score
0
Points
0
Oh my god
thank you sir for the tutorial. it helped me a lot thanks!
 

hamsn

New Member
Messages
290
Reaction score
0
Points
0
good tutorial
and also the location tracker
its also good if you post the ip tracker code too
in tutorials
anyways the main programming tutorial was excellent!
 

marshian

New Member
Messages
526
Reaction score
9
Points
0
good tutorial
and also the location tracker
its also good if you post the ip tracker code too
in tutorials
anyways the main programming tutorial was excellent!

The LocationScript-thing is actually just a joke ;-)
 

marshian

New Member
Messages
526
Reaction score
9
Points
0
You could use a script similar to the one in the link below to actually have the image track the viewers country, you could even put a little flag in there as well. ;)

http://www.dynamicdrive.com/forums/showpost.php?p=62837&postcount=18

It's a nice idea, but NOT THAT SCRIPT plox :eek:
It uses a 'small' list...
http://www.ci-pro.com/misc/phptest/loc/ip.csv
That thing is around 6 meg! It stores a huge list of ip's and their countries...
Maybe if I find something less... huge...
Edit:
I'm going to change something about my image code, this is an example of what the tutorial outputs:
ipimgtg0.png
 
Last edited:

scorch94

Member
Messages
228
Reaction score
0
Points
16
Hmmm... looks like you've edited your font :)
Is it that hard to do? :s

I'm good with PHP, but I've never actually worked with images in PHP. So this one came up like a really good image introduction and made me start learning it :)
 

marshian

New Member
Messages
526
Reaction score
9
Points
0
It's not hard at all, I've got the file "data-latin.ttf" in the same directory, so I can use this command:
PHP:
imagettftext($image, 10, 0, 168, 27, 0, "data-latin.ttf", $text[0]);
which does almost the same as imagestring(), but it uses a truetype font instead of the normal one.
 

mattura

Member
Messages
570
Reaction score
2
Points
18
If it didn't work for you - try the following as a last line (make sure you send the header first though):
PHP:
return imagepng($image);
 
Last edited:

marshian

New Member
Messages
526
Reaction score
9
Points
0
If it didn't work for you - try the following as a last line (make sure you send the header first though):
PHP:
return imagepng($image);

OMG I can't beleive i'm that stupid! o_O
I forgot that part! =.=
IT HAS TO BE
PHP:
return imagepng($image);
instead of
PHP:
return $image;

Edit: I can't change the contents of the first post any more, but it has to be that!
 
Last edited:

marshian

New Member
Messages
526
Reaction score
9
Points
0
Is it possible to use this kind of script to add a copyright notice which automatically updates the year in the footer image of my site? http://www.circuitz4u.com/

Of course it's possible to use the php image capabilities to edit that image for you, but I'ld recommend using an external font to do it, instead of imagestring(), as it wouldn't look too professional.
If you need help, you know where to find me =p
 
Top