Display Image using Perl

How can I display image using LWP:: Simple module in Perl…
This is my code that I am trying to use…

my $html0 = get(“http://chart.finance.yahoo.com/t?s=MSFT&lang=en-US&region=US&width=300&height=180”);

and image is in the get method… and then I am printing this $html0… but instead of image i am getting some weird characters… so can anybody tell me what wrong I am doing…

You need to do two things.

First change STDOUT to binary mode since you image stream contains binary data.

Second put out a Content-Type to say what is coming. In this case image/png.

use LWP::Simple;

my $html0 = get("http://chart.finance.yahoo.com/t?s=MSFT&lang=en-US&region=US&width=300&height=180");

binmode STDOUT;
print "Content-type: image/png\
\
".$html0;

If not showing the result to a browser then,
print "Content-type: image/png

".$html0;

can be skipped. Isn’t it?

If not showing the result to a browser

What else might you be going to do with it?

The variable $html0 will contain the datastream that is the image. The Content-type is for the browsers information so it knows that is coming. binmode is for perl’s file i/o so that it knows to handle $html0 as binary data.

I was trying to download images from my local machine to a folder.
that’s why I skipped content type :slight_smile:

#!/usr/bin/perl

use warnings;
use strict;
use CGI;

my $form = new CGI;
print $form->header; #Print HTML header

my $web_home = "$ENV{DOCUMENT_ROOT}/ajax";

#Getting parametres from form
my $session_id = $form->param("session_id"); 
my $filename = $form->param("filename");

#Create temp dir if doesn't exist yet
umask 0000;  
if ( !-e "$web_home/tmp/$session_id" ) {
    mkdir "$web_home/tmp/$session_id", 0777 
         or die "Problems creating temporary dir '$web_home/tmp/$session_id':  $!\
";
}

#the upload() method to grab the file handle
my $UPLOAD_FH = $form->upload("filename");

my $newfilename = $session_id;

open my $NEWFILE_FH, "+>", "$web_home/tmp/$session_id/$newfilename.txt" 
    or die "Problems creating file '$newfilename': $!";
 
while ( <$UPLOAD_FH> ) {
	print $NEWFILE_FH;
}

close $NEWFILE_FH or die "I cannot close filehandle: $!";

exit;
open (FILE,">$file_in") or die "can't open: $!"; syswrite(FILE,$_,1024) while (read($file, $_, 1024)); close (FILE);