7

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!

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Xetius
  • 44,755
  • 24
  • 88
  • 123
  • Is the only problem that the files are different sizes? How slight is slight? Is the image that is being sent to the user the same as the image on your server? – John Christensen May 29 '09 at 15:06
  • a 20k image was off by maybe 30 bytes. Dave Hinton solved the problem. I was not running in binmode. – Xetius May 29 '09 at 15:18

2 Answers2

14

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
dave4420
  • 46,404
  • 6
  • 118
  • 152
13

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
  • 47,505
  • 4
  • 67
  • 87