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;
In reply to How to display an image on a webpage with minimal code by Melly
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |