图像调整大小导致文件大小比原始C#大得多 [英] Image resize results in massively larger file size than original C#

查看:130
本文介绍了图像调整大小导致文件大小比原始C#大得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用此方法将上传的.JPG图片调整为最大宽度,但是导致图片的kb大小大于源的大小.我究竟做错了什么?保存新图像时,我还需要做其他事情吗?

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?

我尝试了PixelFormat的各种组合,例如PixelFormat.Format16bppRgb555

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

例如:源图像​​是.JPG 1900w,试图将尺寸调整为1200w ...
-源文件为563KB,
-调整大小的文件为926KB或更大,甚至1.9MB

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

推荐答案

您需要指定要保存为jpeg格式:

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

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

否则,它将默认保存为BMP/PNG(我不记得是哪一个).

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

这篇关于图像调整大小导致文件大小比原始C#大得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆