views:

2334

answers:

3

I'm having a wee bit of a problem scaling my images to a proper 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 your images proportionally.

+2  A: 

I'd recommend not writing this code yourself; there are myriads of pixel-level details that take a serious while to get right. Use ImageMagick, it's the best graphics library out there.

Alex
+12  A: 
ratio = MIN( maxWidth / width, maxHeight/ height );
width = ratio * width;
height = ratio * height;

Make sure all divides are floating-point.

Dark Shikari
+2  A: 

Dark Shikari has it. Your solution as stated in the question fails because you aren't first establishing which dimenson's size-to-maxsize ratio is greater and then reducing both dimensions by that greater ratio.

Your current solution's use of a serial, conditional analysis of one potential dimensional violation and then the other won't work.

Note also that if you want to upscale images, your current solution won't fly, and Dark Shikari's again will.

Josh Millard