【问题标题】:Image resize results in massively larger file size than original C#图像调整大小导致文件大小比原始 C# 大得多
【发布时间】:2017-08-18 11:22:26
【问题描述】:

我一直在使用这种方法将上传的.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();
}

【问题讨论】:

  • 您使用的是 jpg 文件吗?你说的是磁盘大小吗?它用于 jpg 主要由编码质量设置决定。您应该添加一个显式编码器来控制它!
  • 我已经编辑了我的问题,以反映我主要上传 jpg。有的话请加个答案谢谢!
  • 位图类不检测文件扩展名的格式。您可能会将其保存为带有 jpeg 文件扩展名的 png 格式。您需要将第二个参数提供给 save 方法。
  • @john 天哪,我什至不知道有第二个参数的选项!添加 ImageFormat.JPEG 立即解决了这个问题!你能添加一个答案吗?
  • @Dave 如果 TaW 没有决定将您的问题错误地标记为重复,我将能够做到。可悲的是他做到了,所以我不能。

标签: c# image-resizing filesize pixelformat


【解决方案1】:

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

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

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

【讨论】:

  • PNG 供参考。再次感谢。天才。
猜你喜欢
  • 2012-10-26
  • 2016-05-04
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 2020-01-27
相关资源
最近更新 更多