tags:

views:

1174

answers:

2

I am trying to get an image from an HTTP server using Perl.

I have the full URL of the file and am attempting to use

my $data = LWP::Simple::get $params{URL};
my $filename = "image.jpg";
open (FH, ">$filename");
print FH $data;
close (FH);

Now, logically, to me at least, this should work. But the files are slightly different sizes, and I can't work out why.

Help!

+12  A: 

You need to use binmode to properly write the image data to disk.

my $data = LWP::Simple::get $params{URL};
my $filename = "image.jpg";
open (FH, ">$filename");
binmode (FH);
print FH $data;
close (FH);

Otherwise it is interpreted as text, and the newlines get munged.

Dave Hinton
I knew it had to be something simple.
Xetius
You don't need a global filehandle hanging around like that. Use File::Slurp's write_file or LWP::Simple::getstore.
Sinan Ünür
I found the big green checkmark right next to binmode amusing.
ysth
+10  A: 

Dave is right, you should/must set your file handle to binary mode. But you could do all that in one go:

LWP::Simple::getstore( $params{URL}, 'image.jpg' );
innaM