grao5 has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am trying to do a very simple thing of reading an image file (jpeg) into an HTML page from a perl cgi script. But for some reason when I click the html file I get a blank image. Why? I am running on Windows 98 OS. If someone could try this out practically and then give me details as to what is wrong in my program, I would really appreciate.

I have the following 3 files in my source directory from where I am running.

(1) myprogram.html

(2) myprogram.cgi

(3) picture.jpg

Here are the contents of my html file "myprogram.html"

<HTML> <head> <title> Test page </title> </head> <BODY> <IMG SRC = "myprogram.cgi"> </BODY> </HTML>

Following are the contents of my perl cgi program "myprogram.cgi"

#!C:\Progra~1\Perl\bin\perl use CGI; $co=new CGI; BINMODE IMAGEHANDLE1; open(IMAGEHANDLE1,"<picture.jpg") or die "filenot found"; $size1=(stat("picture.jpg"))[7]; read IMAGEHANDLE1,$data1,$size1; close IMAGEHANDLE1 ; print $co->header(-type=>'image/jpeg'), $data1;

thanks

grao5 (grao5@hotmail.com)

Replies are listed 'Best First'.
Re: Problem reading image from perl cgi script
by fruiture (Curate) on Oct 16, 2002 at 18:26 UTC

    There are several "caveats" about the code:

    • no strict
    • no warnings
    • no use of $! in error messages...
    • the function 'BINMODE' is not defined.
    • you should(must on windows) use binmode() for input and output-handle. Ouput handle is STDOUT

    This is how i'd write it, which doesn't mean it's right, but as recommendation:

    #!C:\Progra~1\Perl\bin\perl use CGI; my $co = CGI->new(); open IMG, 'picture.jpg' or die $!; binmode IMG; binmode STDOUT; $/ = \ 256; #or bigger as you like it print $co->header('image/jpeg'); print while <IMG>; close IMG;

    update: there's no strict and warnings in my code either, so don't use it without inserting them!

    --
    http://fruiture.de
Re: Problem reading image from perl cgi script
by dws (Chancellor) on Oct 16, 2002 at 18:30 UTC
    Try replacing "BINMODE" with "binmode", and do it after you've opened the file.

    Also, for what you're doing, CGI.pm is overkill.   print "Content-type: image/jpeg\n\n", $data1; is sufficient.

    Also, unless you have access to server error logs, you might consider a fallback strategy for error handling. Instead of die(), why not emit a blank (or black, or red, or orange) image? You can borrow code from On-demand single-pixel GIFs to make that work.