http://qs1969.pair.com?node_id=11132636

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

Whilst refactoring some code, I'm trying to solve a long time minor bug.

The code takes an image which is $file{'image', 'file'}. It creates a blank background image of 600x450 pixels then places the original image on top. If the aspect ratio of the original image is too tall it gets cropped, if it is too wide then the width is maintained so the background forms a band top and bottom. The background is set to white but it nearly always comes out as black and occasionally dark green.

my $white; # Create background my $image = new GD::Image(600, 450); $white = $image->colorAllocate(255, 255, 255); # Resize uploaded image to 600 wide my $picture = GD::Image->new($file{'image', 'file'}); my ($srcw, $srch) = $picture->getBounds(); my $newh = ($srch * 600 / $srcw) - 1; my $resize = GD::Image->new(599, $newh - 1); $resize->copyResized($picture, 0, 0, 0, 0, 600, $newh, $srcw, $srch); # Copy onto background image offset to crop or center $image->copy($resize, 0, 0, 0, ($newh - 450) / 2, 600, 450); $white = $image->colorAllocate(255, 255, 255); open my $fh, '>' ,"$root/images/property/unit/$filename.png"; binmode $fh; print $fh $image->png; close $fh;

A second call to colorAllocate() has been added to check that copy() wasn't resetting the colour pallette. This makes no difference. When $white is checked it is always a positive number. 16777215 for colorAllocate(255, 255, 255) and different positive numbers for different colours.

Any ideas what else I can check?
The documentation for GD->colorAllocate is not very helpful.

Or, perhaps there is a better way to solve the problem...
To create images that are always 600px x 450px regardless of the original but without distorting them.