Screaming Into The Abyss

Random Image Via Perl
By Ben Zvan
On March 25, 2008 at 10:56
Computers

I don't know if it's useful to anyone but me, but I was trying to figure out the best way to display a random image on a webpage. What I ran into for using Server Side Includes is that the image to show is defined in my css which isn't parsed by the server for includes and apparently include directives within class= statements are ignored with my server configuration.

Well, it seemed that there should be a simple way to do this. The result was to create a configuration-less perl script that displays a random image from the folder it's in. It currently only does files that end in .jpg, so I'll leave that change as an exercise for the reader.

If you just want to use the script, here are some instructions. In the directory where your source images are stick the code in a file whatever name you like as long as it ends with .cgi or .pl, I'd suggest something like randomimage.pl. Make the file executable (chmod a+x randomimage.pl (windows users are on their own)). In your html or css use the name of your file as the name of the image, something like "http://www.yourdomain.com/randomimages/randomimage.pl" would work nicely. This will work best if all the images are the same size so the web page doesn't look different every time and you can define the image dimensions in the html or css.

#!/usr/bin/perl

opendir (THISDIR, "./") or die "no such directory: $!";
@imagelist = grep { /.*\.jpg/ } readdir THISDIR;
closedir (THISDIR);

$max = $#imagelist + 1;

$imagenumber= int(rand($max)) ;

print "Content-type: image/jpeg\n\n";

open (IMAGEFILE, "<", "./$imagelist[$imagenumber]") or die "can't open file $imagelist[$imagenumber]";
foreach (readline (IMAGEFILE)) {
    print;
    }
close (IMAGEFILE);

Anyway. No guarantees. No promises. Code provided as is and free for any legal, non-malicious use.

--Ben

Facebook | Twitter | Reddit | Stumble

blog comments powered by Disqus

 

Arts

New Pictures 8: Sarah Jones
Minneapolis Institue of Arts
04/18/2013—02/02/2014 - Free

31 Years: Gifts from Martin Weinstein
Minneapolis Institue of Arts
11/02/2013—08/31/2014 - Free

New Pictures 9: Rinko Kawauchi
Minneapolis Institue of Arts
02/20/2014—08/10/2014 - Free

Finland: Designed Environments
Minneapolis Institue of Arts
05/10/2014—08/17/2014 - Free

Music

Nick Cave and the Bad Seeds
at State Theatre
06/21/2014 \ Doors 8:00pm

Twitter

Please wait while my tweets load

If you can't wait - check out what I've tw@