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

I am trying to use Win32-IE-Mechanize to open a webpage that has an image in it that is generated by PHP.

I have written a script to save the image, but it winds up saving another html page that has a link to the image - here is the perl:

use Win32::IE::Mechanize; use Time::HiRes; $ie = Win32::IE::Mechanize->new( visible => 1 ) ; $ie->get( 'http://localhost/image/myimage.php' ) ; while($ie->{agent}->Document->readyState !~ /complete/i){ sleep(0.1); +} $content = $ie->content; save_image($content); sub save_image { my ($content) = @_; open my $out_fh, ">", "image.png" or die $!; binmode $out_fh; print $out_fh $content; close $out_fh; }


here is the php myimage.php that generates the image:
<?php $my_img = imagecreate( 200, 80 ); $background = imagecolorallocate( $my_img, 0, 0, 255 ); $text_colour = imagecolorallocate( $my_img, 255, 255, 0 ); $line_colour = imagecolorallocate( $my_img, 128, 255, 0 ); imagestring( $my_img, 4, 30, 25, "test image", $text_colour ); imagesetthickness ( $my_img, 5 ); imageline( $my_img, 30, 45, 165, 45, $line_colour ); header( "Content-type: image/png" ); imagepng( $my_img ); imagecolordeallocate( $line_color ); imagecolordeallocate( $text_color ); imagecolordeallocate( $background ); imagedestroy( $my_img ); ?>


and the original html page that displays the image:
<img src="myimage.php" alt="Image created by a PHP script" width="200" + height="80">

when I try to save the png image i get a png file that contains the following html
<HTML><HEAD></HEAD> <BODY leftMargin=0 scroll=no topMargin=0><EMBED height="100%" type=ima +ge/x-png width="100%" src=http://localhost/image/myimage.php fullscre +en="yes"></BODY></HTML>

so instead of saving the png image, I am getting HTML with a link the png image.

any ideas???

Replies are listed 'Best First'.
Re: Save PHP-generated image with Win32 IE Mechanize
by Corion (Patriarch) on Feb 10, 2010 at 08:00 UTC

    Most likely, you (or your browser) are sending the wrong HTTP headers when retrieving the image. Use a tool like Wireshark to inspect the network traffic and then replicate that traffic from within Perl.

    If you're not tied to Internet Explorer, I find my module WWW::Mechanize::Firefox to be more accessible, because Firefox has the Live HTTP Headers that allow easier inspection.

      Thanks Corion

      I added some request headers and checked what was happening in Wireshark - it looks like Win32 IE Mechanize is simply ignore the request headers.

      When I do the same thing with WWW Mechanize it sends the proper headers and save the actual image.
A reply falls below the community's threshold of quality. You may see it by logging in.