I need to create images that are within a 480w x 360h pixel “canvas”.
I did create some images from my remote url, no problem with help from stackoverflow.
However, I desire to maintain aspect ratio of the image but, have the end result be 480×360.. Therefore, a “canvas” or border then crop technique needs to be used (from what I have read) but, I cannot seem to get it going.
Here is what I have:
#!/usr/bin/perl
use Image::Resize;
use Image::Magick;
use strict;
my $new = 'path/to/image/image.jpg';
my $somewords = 'Some words';
my $imageurl='http://myimageurl.com/image.jpg';
my $p = new Image::Magick;
$p->Read("$imageurl");
my ($origw, $origh) = $p->Get('width', 'height');
#### correct size images get processed here with just annotation ########
if (($origw == 480) && ($origh == 360)){
system("convert $imageurl -fill '#FFFFFF' -font Candice -pointsize 12 -undercolor '#00000080' -gravity SouthEast -annotate +1+1 '$somewords' $new");
}
#### process images of incorrect original size WHERE I AM STUCK #######
if (($origw != 480) && ($origh != 360)){
system("convert $imageurl $new");
system("convert $imageurl -resize 480x360\! -fill '#FFFFFF' -font Candice -pointsize 14 -undercolor '#00000080' -gravity SouthWest -annotate +1+1 '$somewords' $new");
}
What I need is this:
A “canvas” size of 480 x 360.
Reduce the original image from the url to correct aspect ratio at either 480w or 360h and place it in the middle of the 480×360 canvas.
I read somewhere, that offered no examples, that I could resize original image while maintaining aspect ratio to correct height or width whichever allows the image to be largest then, divide the other param (h or w) by 2 and then make add border based on that, then crop to size. Confused the “he + double hockey sticks” out of me.
I am so lost on trying to figure this out. I am even unsure if my question here is clear and worthy of asking stackoverflow.
Seems like resizing while maintaining aspect ratio while creating a fixed output image is very difficult! Hours of searching have not helped me.
I praise the one who offers a verbose solution. Thanks.
Isn’t it a bit silly to use the
Image::Magickmodule, and then use the externalconvertcommand? You can do all of this within your Perl script usingImage::Magick.Anyway, if you read the fine manual, you’ll find that ImageMagick will resize to the highest dimensions within 480×360 without changing the aspect ratio by using
480x360. This works both on the command-line withconvertand withinImage::Magick. When you add the!, you’re telling it to resize to exactly 480×360, disregarding the aspect ratio.This should get you started without using external commands: