Image resize results in massively larger file size than original C#
Asked Answered
L

1

1

I've been using this method to resize uploaded .JPG images to a max width, but it's resulting in images being larger in kb than the source. What am I doing wrong? Is there something else I need to do when saving the new image?

I've tried all sorts of combinations of PixelFormat, e.g. PixelFormat.Format16bppRgb555

E.g: source image is a .JPG 1900w, trying to resize to 1200w...
- Source file is 563KB,
- resized file is 926KB or larger, even 1.9MB

public static void ResizeToMaxWidth(string fileName, int maxWidth)
{
    Image image = Image.FromFile(fileName);

    if (image.Width > maxWidth)
    {
        double ratio = ((double)image.Width / (double)image.Height);
        int newHeight = (int)Math.Round(Double.Parse((maxWidth / ratio).ToString()));

        Bitmap resizedImage = new Bitmap(maxWidth, newHeight);

        Graphics graphics = Graphics.FromImage(resizedImage);
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High

        Rectangle rectDestination = new Rectangle(0, 0, maxWidth, newHeight);
        graphics.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);            
        graphics.Dispose();

        image.Dispose();
        resizedImage.Save(fileName);
        resizedImage.Dispose();
    }
    image.Dispose();
}
Linter answered 25/3, 2017 at 14:52 Comment(5)
Are you using jpg files? Are you talking about disk size? It is for jpg mostly decided by the encoding quality setting. You should add an explict encoder to cotrol that!Nauseous
I've edited my question to reflect that I'm mostly uploading jpgs. Please add an answer if you have one thanks!Linter
The bitmap class does not detect format from file extension. You're likely saving it in a png format with a jpeg file extension. You need to supply the second parameter to the save method.Anoint
@john Holy balls, I didn't even know there WAS an option for a second parameter! Adding ImageFormat.JPEG immediately fixed the issue! Can you add an answer?Linter
@Linter If TaW hadn't decided to incorrectly mark your question as a duplicate, I would be able to. Sadly he did, so I can't.Anoint
A
4

You need to specify that you want to save it as the jpeg format:

    resizedImage.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

Otherwise it will default to saving as BMP / PNG (I can't remember which).

Anoint answered 26/3, 2017 at 12:18 Comment(1)
PNG for reference. Thanks again. Genius.Linter

© 2022 - 2024 — McMap. All rights reserved.