I need to pad an image with a white border to make it fit a certain
size. So far I've found the Border() method to do the job, but not
quite. As far as I can see, it adds the same amount of padding to
the right of the image as it does to the left, and the same amount
of padding to the top as to the bottom. This means I can never pad
an image of size 393x297 so that it becomes 400x300 exactly, as the
geometry parameter works on integers only. I realise I can add some
extra border and crop the image afterwards, but want to know if
there's a way to do what I wish in one operation. Something
equivalent to Netpbm's "pnmpad -[left|right|top|bottom]" would be
nice.

Below is my current test code:

- - -

#!/usr/bin/perl -w

use Image::Magick;
use strict;

resizeImage('foo.jpg', 'bar.jpg', 400, 300);

sub resizeImage {
my ($sourceFile, $targetFile, $w, $h) = _;

my $image = Image::Magick->new();

# Read image from source file
$image->Read($sourceFile);

# Scale image if too large
$image->Scale(geometry => "${w}x${h}>");
my ($sw, $sh) = ($image->Get('columns'), $image->Get('rows'));

# Pad image if needed
if ($sw < $w || $sh < $h) {
# Calculate horizontal and vertical padding
my ($horz, $vert) = (int(($w - $sw + 1)/2), int(($h - $sh + 1)/2));
$image->Border(geometry => "${horz}x${vert}", fill => 'white');
my ($pw, $ph) = ($image->Get('columns'), $image->Get('rows'));

# Crop image if needed
if ($pw > $w || $ph > $h) {
$image->Crop(width => $w, height => $h);
}
}

# Write image to target file
$image->Write($targetFile);
}

- - -

--
Lars Haugseth