Random Avatar

You have probably seen avatars and banners like this before in forums and such.
Avatars that changes when you reload the page. And when you look at the avatars extention, you see that it is a .png or whatever.
This can be done using PHP and .htaccess.
PHP is used to create a new image from a random image and .htaccess is used to change the file extention to make it look like a regular .png file.

This is exactly what we're going to do now.
So find a few avatars you want to use, like these:

Random avatar Random avatar Random avatar Random avatar Random avatar

(Try to make sure they are 8-bit png, not 24-bit)

Create a new php file called "avatar.php" and enter this code:

<?php header("Content-type: image/png"); $avatars[] = "avatars/1.png"; $avatars[] = "avatars/2.png"; $avatars[] = "avatars/3.png"; $avatars[] = "avatars/4.png"; $avatars[] = "avatars/5.png"; $avatar = $avatars[mt_rand(0, count($avatars)-1)]; $newavatar = imagecreatefrompng($avatar); imagepng($newavatar); imagedestroy($newavatar); ?>

Ok, here's what the code does:

header("Content-type: image/png");
- Makes the php file act like a png image file.

Then we add all the avatars we want into an array called $avatars.
Makes sure you use the correct path to the images.

$avatar = $avatars[mt_rand(0, count($avatars)-1)];
- This code selects a random avatar from the $avatars array and store it in a new variable called $avatar. mt_rand() is a function that returns a random number between 0 and the amount of avatars in the $avatars array in this case. count() returns how many avatars there is in the $avatars array.

$newavatar = imagecreatefrompng($avatar);
- Uses the imagecreatefrompng() function from the GD library to create a new image from a file. The avatar stored in the $avatar array in this case.

imagepng($newavatar);
- Outputs the image to the browser.

imagedestroy($newavatar);
- Deletes the image from the memory.

Now, if you run this script you will just see alot of weid characters, but thats where .htaccess comes in.
Create a new file called ".htaccess" and enter the following code:

RewriteEngine On RewriteRule avatar.png avatar.php

This code will make avatar.png act like avatar.php.
So if you open avatar.png (wich doesnt even exist) you will get the output from avatar.php. - A random image!

And that's about it.
If you have any troubble, make sure your server have the GD library installed and that you have permission to use .htaccess.

Anyways, here's my result:

Random avatar

(try to refresh)



Want to get in touch? Got some feedback for me? or a couple of requests? Follow me at twitter:
@ThomasPedersen

Need a reliable webhost? Take my word for it and go with Hostgator Green Web Hosting by HostGator



Warning: fread(): Length parameter must be greater than 0 in /customers/f/2/7/n1studios.net/httpd.www/minicounter.php on line 17