Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: graphicsmagick perl shrink image to size

by bliako (Monsignor)
on Nov 01, 2021 at 18:12 UTC ( [id://11138308]=note: print w/replies, xml ) Need Help??


in reply to graphicsmagick perl shrink image to size

I managed to install this package via my linux package manager along with the library.

Here is something to get you started from first principles:

#!/usr/bin/perl # by bliako # for https://perlmonks.org/?node_id=11138293 # on 01/11/2021 use strict; use warnings; use Graphics::Magick; my($image, $status); $image = Graphics::Magick->new; $status = $image->Read('a.jpg'); my $W = $image->Get('width'); my $H = $image->Get('height'); my $maxW = 800; my $maxH = 200; my ($newW, $newH, $factor) = trans($W, $H, $maxW, $maxH); my $AR = $W / $H; my $newAR = $newW / $newH; print "($W x $H) => ($newW x $newH)\n"; print "original aspect ratio: $AR, new aspect ratio:$newAR\n"; $image->Resize(width => $newW, height => $newH); $image->write("resized.jpg"); #testme(); # given original dimensions and new max dimensions # it returns (newW, newH, resize_factor) sub trans { my ($W, $H, $maxW, $maxH) = @_; my ($arW, $arH); my $factor = ($arW=($W/$maxW)) < ($arH=($H/$maxH)) ? $arH : $arW; my $newW = int($W/$factor); my $newH = int($H/$factor); return ($newW, $newH, $factor); } # this does a brute-force testing on sizes 10-1000 # for 800x200 max dim sub testme { my $maxW = 800; my $maxH = 200; for my $W (map { $_*10 } 1..100){ for my $H (map { $_*10 } 1..100){ my ($newW, $newH, $factor) = trans($W, $H, $maxW, $maxH); my $AR = $W / $H; my $newAR = $newW / $newH; die "failed test: aspect ratios not the same ($AR -> $newAR) for + ($W x $H) => ($newW x $newH)" if ($AR-$newAR) > 10E-1; die "failed test: new width exceeds maximum for ($W x $H) => ($n +ewW x $newH)" if $newW > $maxW; die "failed test: new height ($newH) exceeds maximum for ($W x $ +H) => ($newW x $newH)" if $newH > $maxH; } } }

Output:

(2560 x 1536) => (333 x 200) original aspect ratio: 1.66666666666667, new aspect ratio:1.665

bw, bliako

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138308]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-26 06:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found