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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.