Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scaling an image, but keep its proportions

I want to scale images, but I don't want the image to look skewed.

The image has to be 115x115 (length x width).

The image can't be over 115 pixels high (length), but if needed, the width can be less than 115 but not more.

Is this tricky?

like image 523
mrblah Avatar asked Dec 30 '09 12:12

mrblah


People also ask

How do you scale without distorting?

Select the "Constrain Proportions" option to scale the image without distorting it and change the value in the "Height" or "Width" box. The second value changes automatically to prevent the image from distorting.


1 Answers

You need to preserve aspect ratio:

float scale = 0.0;

    if (newWidth > maxWidth || newHeight > maxHeight)
    {
        if (maxWidth/newWidth < maxHeight/newHeight)
        {
            scale = maxWidth/newWidth;
        }
        else
        {
            scale = maxHeight/newHeight;
        }
        newWidth = newWidth*scale;
        newHeight = newHeight*scale;

    }

In the code, Initially newWidth/newHeight are width/Height of image.

like image 137
Brij Avatar answered Sep 28 '22 14:09

Brij