Timothy R. Butler
Timothy R. Butler

Reputation: 1139

Preserving Aspect Ratio in Image::Magick's Thumbnail function

I'm trying to use the Perl Image::Magick library to use ImageMagick's thumbnail function. Everything I read suggests that ImageMagick preserves aspect ratio when it is given both a width and height, almost functioning more like max-width and max-height in CSS parlance. However, in practice, it seems to be jamming the image into the dimensions I give, disregarding aspect ratio. Am I missing a flag I need to turn on? My impression is that preserving aspect ratio is default behavior.

    my $image = Image::Magick->new;
    $image->BlobToImage($imageData);
    $image->SetAttribute(quality => 80);
    $image->SetAttribute(compression => 'JPEG');
    $image->Thumbnail(width => $thumbnailWidth, height => $thumbnailHeight);

Upvotes: 2

Views: 345

Answers (1)

zdim
zdim

Reputation: 66883

There are options for comprehensive size manipulation under geometry parameter

scale%         Height and width both scaled by specified percentage.
...
width          Width given, height automagically selected to preserve aspect ratio.
...
widthxheight   Maximum values of height and width given, aspect ratio preserved.
widthxheight^  Minimum values of width and height given, aspect ratio preserved.
widthxheight!  Width and height emphatically given, original aspect ratio ignored.
...

This is from the Image Geometry section of the page on ImageMagick's command-line use. The fact that Perl module's documentation doesn't give this level of API detail usually implies that its binding implements most (all?) of these, and is covered by the generic documentation.

A command-line example, scaling an image down to 20%

perl -MImage::Magick -we'$f = shift // die "Pass image filename\n"; 
    $img = Image::Magick->new; 
    $img->Read($f);
    $img->Thumbnail(geometry => "20%"); 
    $img->Write(filename => "scaled_$f")'

Judged by the example in the question it looks like you'd want the parameter value

widthxheight  Maximum values of height and width given, aspect ratio preserved.

The more generic Resize and Scale methods also have geometry parameter.

Upvotes: 2

Related Questions