图像调整大小导致文件大小比原始C#大

时间:2017-03-25 14:52:09

标签: c# image-resizing filesize pixelformat

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

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

例如:源图像​​是.JPG 1900w,试图调整为1200w ...
  - 源文件为563KB,
  - 已调整大小的文件为926KB或更大,甚至为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();
}

1 个答案:

答案 0 :(得分:3)

您需要指定要将其另存为jpeg格式:

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

否则它将默认保存为BMP / PNG(我无法记住哪个)。