简体   繁体   中英

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

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 , eg PixelFormat.Format16bppRgb555

Eg: 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();
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM