Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proportional image resize

I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally.

I'm using this at the moment:

var maxHeight   = 300; var maxWidth    = 300;  var ratio:Number    =   height / width;  if (height > maxHeight) {     height = maxHeight;     width = Math.round(height / ratio); }   else if(width > maxWidth) {     width = maxWidth;     height = Math.round(width * ratio); } 

But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally.

like image 777
Hot Pixel Avatar asked Sep 22 '08 15:09

Hot Pixel


People also ask

How do I reduce the size of an image using proportions CSS?

A common use is to set max-width: 100%; height: auto; so large images don't exceed their containers width. Another way is the use of object-fit property, this will fit image, without changing the proportionally. Example 2: html.


1 Answers

ratio = MIN( maxWidth / width, maxHeight/ height ); width = ratio * width; height = ratio * height; 

Make sure all divides are floating-point.

like image 160
Dark Shikari Avatar answered Sep 28 '22 16:09

Dark Shikari