Random forum avatars

Posted by Quinny Thu, 04 Feb 2010 23:26:37 GMT
Random forum avatars

Today I felt like changing my avatar on one of the forums I frequently visit. I then thought it would be fun if I could have a random avatar, chosen from a directory on my server.

After about half an hour of experimenting and Googling I came up with something that works reasonably well. The only thing I need to look at is the increased JPEG compression that is very visible in the images, after they've been through the PHP script.

Continue reading for my code.

I've taken some code from PHP.net (see #1 and #2). The rest was simple:

Code:
<? function LoadJpeg($imgname) { /* Attempt to open */ $im = @imagecreatefromjpeg($imgname); /* See if it failed */ if(!$im) { /* Create a black image */ $im = imagecreatetruecolor(150, 30); $bgc = imagecolorallocate($im, 255, 255, 255); $tc = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 150, 30, $bgc); /* Output an error message */ imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc); } return $im; } //define the path as relative $path = "./"; //using the opendir function $dir_handle = @opendir($path) or die("Unable to open $path"); //define an empty array $avatars = array(); //running the while loop and fill the array with filenames (*.jpg) while ($file = readdir($dir_handle)) { if(preg_match('~[^/]*\.jpg$~iD', $file)) { $avatars[] = $file; } } //Randomly select an element from the avatars array $rand_keys=array_rand($avatars,1); //Close the file handler closedir($dir_handle); //Print the content type header header( "Content-type: image/jpeg" ); //Load the image $my_img = LoadJpeg($avatars[$rand_keys]); //Show the image imagejpeg($my_img); //Free the memory used for the image imagedestroy($img); ?>

Save this code in a file, inside the directory with avatars, with the filename ending in '.php'. Now, PHPBB won't accept any address for an external avatar that ends in '.php', luckily, PHP accepts GET variables, even if the script doesn't use them. I just added '?type=.jpg' to the end of my url, now PHPBB will accept it as a valid image.

Have fun with your randomized avatar!

no comments |



Leave a comment

Leave a comment