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

Hi everyone

I'm trying to create a perl script which encodes images to base64. This shall be used to transfer images via xml to another system.

I created the following script to read the capture.png file:

use MIME::Base64; open (my $image, 'Z:\capture.png') or die "$!"; $raw_string = do{ local $/ = undef; <$image>; }; $encoded = encode_base64( $raw_string );

For the beginning, I just re-write into a new file photo.png

my $decoded= MIME::Base64::decode_base64($encoded); open my $fho, '>', 'Z:\photo.png' or die $!; binmode $fho; print $fho $decoded;

The photo.png is created with exactly the same size as the input photo, however the newly created file can't be opened.

I also comared the base64 value with the value created by an online encoding webpage (using the same input photo) and this is different.

I would be very happy if somebody could help me out with this!

Thanks a lot in advance. Best regards zurich

Replies are listed 'Best First'.
Re: image encode base64 - help needed
by Corion (Patriarch) on Feb 11, 2016 at 14:32 UTC

    Have you tried also using binmode when reading the file?

Re: image encode base64 - help needed
by graff (Chancellor) on Feb 12, 2016 at 00:38 UTC
    If those two snippets in the OP are in the same script, you can add a few more lines to use MD5 checksums on $raw_string and $decoded, to confirm whether the encode/decode is behaving as it should:
    use strict; use warnings; use MIME::Base64; use Digest::MD5 'md5_hex'; open (my $image, 'Z:\capture.png') or die "$!"; binmode $image; my $raw_string = do{ local $/ = undef; <$image>; }; my $encoded = encode_base64( $raw_string ); my $decoded = MIME::Base64::decode_base64($encoded); my $rawmd5 = md5_hex( $raw_string ); my $decmd5 = md5_hex( $decoded ); warn sprintf( "raw != decoded (%s vs %s)\n", $rawmd5, $decmd5 ) if ( $rawmd5 ne $decmd5 ); open my $fho, '>', 'Z:\photo.png' or die $!; binmode $fho; print $fho $decoded;
    (I added binmode on the input file handle, just in case; but if that's the problem with the OP code, then I wouldn't expect your input and output files to be exactly the same size.)