The graphicsmagick package for perl is very extensive but the documentation appears light (or confusing to me) If I have an image and I want to ensure the size is within 800x200 (like
When running the script I get output:
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
And the saved output file out.jpg
:
CodePudding user response:
The algorithm of a solution for the problem is quite simple.
It is required to find the smallest scale for the image between scale for width and height. Once scale identified apply it to the image.
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;
For a test was taken a random file from internet
Result verification
$ 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