This one seems to come up a lot in Seekers, so I thought I'd drop a simple script in here.
Although this script displays a random image from a specified directory, the principle should be adaptable to any image display code... basically, use a "Location:" redirect... It's worth noting that the version given here depends on the image directory being a sub-directory of the script's location. On most servers, this won't be the case, and you would probably have to manipulate the location parameter to account for this.
...And, as merlyn has pointed out, any implementation of this snippet will probably break at least one standard, or just plain not work, so I've provided two more standard-compliant (but longer) alternatives.
Non-standard-compliant version (and with probable caching):
#!/usr/bin/perl -wT use strict; # Call in img tag - e.g.: <img src="randimage.cgi" border="2"> my @files = glob("./jpegs/*.jpg"); print "Location: $files[int(rand @files)]\n\n";
Standard-compliant version (short, but with potential caching of images):
<updated>#!/usr/bin/perl -wT use strict; use URI; my @files = glob("./images/*"); my $file = URI->new_abs($files[int(rand @files)], "http://bugzilla"); print "Status: 307 Temporary redirect\n"; print "Location: $file\n\n";
Standard-compliant version (long - no caching problems):
</updated>#!/usr/bin/perl -wT use strict; # types where extension <> content-type my %types = qw(jpg jpeg tif tiff); # get an array of image-files my @images = glob("./images/*"); die "No images found\n" unless scalar @images; # choose an image and and prepare content type extension my $image = $images[int(rand @images)]; die "No extension for $image\n" unless $image =~ /\.(.+)$/; my $ctype = $1; $ctype = $types{$ctype} if exists $types{$ctype}; # read and print image open(IMG, $image)||die "Cannot open $image:$!\n"; print "Content-type: image/$ctype\n\n"; binmode (IMG); binmode (STDOUT); print while(<IMG>); close IMG;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to quickly display an image on a webpage via perl
by merlyn (Sage) on Nov 08, 2006 at 04:35 UTC | |
by Melly (Chaplain) on Nov 08, 2006 at 09:31 UTC | |
|
Re: How to display an image on a webpage with minimal code
by bart (Canon) on Nov 15, 2006 at 12:28 UTC | |
by Melly (Chaplain) on Nov 15, 2006 at 12:59 UTC | |
by bart (Canon) on Nov 16, 2006 at 19:59 UTC | |
by Melly (Chaplain) on Nov 17, 2006 at 09:36 UTC |