Your skill will accomplishwhat the force of many cannot PerlMonks

### Fix this HTML-ish image sizer

by sulfericacid (Deacon)
 on Jun 18, 2007 at 17:49 UTC Need Help??
sulfericacid has asked for the wisdom of the Perl Monks concerning the following question:

This was posted as an untested solution to a SOPW a week or so past and it was stated by a monk that there was indeed an error in the calculations. Can someone provide a working solution keeping my methods thus far intact? I know it can be done via Image::Image or another module but those aren't available in my workspace and I'd like to see how close I got to the final solution.

The question was: the user needed a way to determine the h/w of an image and output an html-resized version of it so that both h/w are less than a max value.. AND the image has to stay the same aspect ratio.

#!/usr/bin/perl use warnings; use strict; my \$height = "1000"; my \$width = "1234"; my \$maxh = "600"; my \$maxw = "800"; if (\$height > \$maxh || \$width > \$maxw) { my \$hratio = \$height / \$maxh; my \$wratio = \$width / \$maxw; my \$newh = \$height / \$hratio; my \$neww = \$width / \$hratio; print "Height is now \$newh, Width is now \$neww"; } RESPONSE FROM ALMUT: It's not quite as trivial as it might seem at first (most of us who ha +ve tried probably got it wrong the first time :) Just as an example, take a width of 1000 and a height of 100. Your al +gorithm would compute 6000x600 (W x H), although the expected result +would be 800x80 (i.e. max width doesn't exceed 800 and aspect ratio s +tays at 10:1)

"Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

sulfericacid

Replies are listed 'Best First'.
Re: Fix this HTML-ish image sizer
by FunkyMonk (Canon) on Jun 18, 2007 at 18:02 UTC
You need to divide by whichever ratio is the greatest:

rescale( 1000, 1234 ); rescale( 100, 1000 ); sub rescale { my ( \$height, \$width ) = @_; my \$maxh = "600"; my \$maxw = "800"; if (\$height > \$maxh || \$width > \$maxw) { my \$hratio = \$height / \$maxh; my \$wratio = \$width / \$maxw; my \$ratio = \$hratio > \$wratio ? \$hratio : \$wratio; my \$newh = \$height / \$ratio; my \$neww = \$width / \$ratio; printf "H=%d W=%d ratios: old=%0.2f new =%0.2f\n", \$newh, \$neww, \$height / \$width, \$newh / \$neww; } }

Create A New User
Node Status?
node history
Node Type: perlquestion [id://621836]
Approved by Errto
help
Chatterbox?
and snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-06-24 22:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (562 votes). Check out past polls.