Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display image via PERL

Status
Not open for further replies.

1DMF

Programmer
Joined
Jan 18, 2005
Messages
8,795
Location
GB
I have toyed with this script for ages and couldn't work out how to get the image to display, then it came to me and thought I'd share as it took me ages searching to get the answer.

If you want to have a page with an image and the source is equal to the cgi script i.e.
Code:
<img src="url_to_cgi/image.cgi?ID=1" />
in the perl you would do the following...
Code:
#!/usr/bin/perl

######################
# Set Error Trapping #
######################

use CGI::Carp qw(fatalsToBrowser warningsToBrowser); 
use warnings;
use strict;

##################
# Use CGI Module #
##################
use CGI;

# Set new CGI
my $cgi = new CGI;

my $id = $cgi->param('ID');

# Set file
my $file = "path_to_file/$id.jpg";

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

# Open Image File
open(FILE, "<$file") || die "Error opening image file, seek support!";

[b]# Prepare STDOUT for binary data
binmode(STDOUT);[/b]

# Print File
print <FILE>;
close(FILE);
exit();
I have highlighted the important part, it is important to remember that you must prepare the STDOUT for binary data before printing the image content.

This example works for JPEG files, but you can easily change it for your required file type, and remember to change the MIME header content type .i.e.
Code:
# GIF
print "Content-type: image/gif\n\n";
# PNG
print "Content-type: image/png\n\n";

Hope it helps someone :-)

Regards, 1DMF

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Since you're using CGI anyways, might as well have it rolling the headers for you
Code:
print $q->header(-type=>'image/gif');
and sub image/gif for the appropriate MIME headers eg image/jpeg

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
yeah I guess, but I still prefer to type
print "Content-type: image/gif\n\n";
than
print $q->header(-type=>'image/gif');
just habbit and preference I supose and why is it $q and not $cgi ?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
$q->... is straight from the docs, my apologies, should read $cgi->... in this context.

Headers can cause problems when hand rolled, typos etc, so where possible I like to use CGI for that.

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top