Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize JPEG image to fixed width, while keeping aspect ratio as it is

How would you resize a JPEG image, to a fixed width whilst keeping aspect ratio? In a simple way, whilst preserving quality.

like image 252
cllpse Avatar asked Nov 21 '11 15:11

cllpse


People also ask

How do you keep aspect ratio when resizing paint?

From the Home Tab, select the Resize and Skew Icon (note the original pixel size shown near the bottom). 3. Make sure there is a check mark in the box next to "Maintain aspect ratio"; then set the width and click OK.

Why you should maintain the aspect ratio while resizing an image?

When scaling your image, it's crucial to maintain the ratio of width to height, known as aspect ratio, so it doesn't end up stretched or warped. If you need a specific width and height, you may need a mixture of resizing and cropping to get the desired result.


3 Answers

This will scale in the vertical axis only:

    public static Image ResizeImageFixedWidth(Image imgToResize, int width)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = ((float)width / (float)sourceWidth);

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return (Image)b;
    }
like image 136
rboarman Avatar answered Sep 23 '22 01:09

rboarman


If you are reducing the width by 25 percent to a fixed value, you must reduce the height by 25 percent.

If you are increasing the width by 25 percent to a fixed value, you must increasing the height by 25 percent.

It's really straight forward.

like image 25
Steve Wellens Avatar answered Sep 21 '22 01:09

Steve Wellens


Assuming there is a (double width) variable:

Image imgOriginal = Bitmap.FromFile(path);
double height = (imgOriginal.Height * width) / imgOriginal.Width;
Image imgnew = new Bitmap((int)width, (int)height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(imgnew);
g.DrawImage(imgOriginal, new Point[]{new Point(0,0), new Point(width, 0), new Point(0, height)}, new Rectangle(0,0,imgOriginal.Width, imgOriginal.Height), GraphicsUnit.Pixel);

In the end you´ll have a new image with widthxheight, then, you´ll need to flush the graphics e save the imgnew.

like image 21
Adilson de Almeida Jr Avatar answered Sep 22 '22 01:09

Adilson de Almeida Jr