perl 的 graphicsmagick 包非常廣泛,但檔案看起來很輕(或讓我感到困惑)如果我有影像并且我想確保大小在 800x200 以內(例如
運行腳本時,我得到輸出:
Height = 404
Width = 1548
factor1 = 0.516795865633075
factor2 = 0.495049504950495
1548 x 0.516795865633075 = 800
404 x 0.516795865633075 = 208.785529715762
1548 x 0.495049504950495 = 766.336633663366
404 x 0.495049504950495 = 200
Height = 200
Width = 766
和保存的輸出檔案out.jpg:

uj5u.com熱心網友回復:
該問題的解決方案的演算法非常簡單。
需要在寬度和高度的比例之間找到影像的最小比例。確定比例后,將其應用于影像。
use strict;
use warnings;
use Graphics::Magick;
my $fname = shift || die "Provide filename";
my($image,$img);
my($scale,$scaleH,$scaleW);
my $holder = {
width => 800,
height => 200
};
$image = Graphics::Magick->new;
$image->ReadImage($fname);
$img->{height} = $image->Get('height');
$img->{width} = $image->Get('width');
$scaleH = $holder->{height} / $img->{height};
$scaleW = $holder->{width} / $img->{width};
$scale = $scaleH < $scaleW ? $scaleH : $scaleW;
$image->Scale( height => $img->{height}*$scale, width => $img->{width}*$scale );
$image->write('image_new.jpg');
exit 0;
為了進行測驗,從互聯網上隨機獲取了一個檔案
結果驗證
$ file image.png
image.png: PNG image data, 2250 x 585, 8-bit/color RGB, non-interlaced
$ file image_new.jpg
image_new.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 769x200, components 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/344569.html
