binmode $img_fh; local $/; undef $/; my $img = GD::Image->new($img_fh) or die "Failed to read image file: $!\n"; # ... my $fh; my $fullpath = "$path/$filename" . ($png_img ? '.png' : '.jpg'); open $fh, '>', $fullpath or die "Failed to write image file: $!\n"; binmode $fh; print $fh ($png_img ? $img->png : $img->jpeg); close $fh;