在 Image::Magick 的缩略图功能中保留纵横比

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

我正在尝试使用 Perl Image::Magick 库来使用 ImageMagick 的缩略图功能。我读到的所有内容都表明 ImageMagick 在给定宽度和高度时保持纵横比,几乎更像 CSS 说法中的 max-width 和 max-height。然而,在实践中,它似乎将图像塞进了我给出的尺寸,而忽略了纵横比。我是否缺少需要打开的标志?我的印象是保留宽高比是默认行为。

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

geometry 参数

下有综合大小操作的选项
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.
...

这来自 Image Geometry section of the page on ImageMagick's command-line use. The fact that Perl module's documentation 没有给出这一级别的 API 详细信息通常意味着它的绑定实现了其中的大部分(全部?),并且包含在通用文档中。

命令行示例,将图像缩小到 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")'

根据问题中的示例判断,您似乎需要参数值

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

更通用的 ResizeScale 方法也有 geometry 参数。