【问题标题】:Why my BMP image is bigger than the original after reducing its width and height?为什么我的 BMP 图像在减小宽度和高度后比原始图像大?
【发布时间】:2016-09-26 09:20:17
【问题描述】:

在我的项目中,我必须调整图像大小,然后将其保存到文件夹中。但是,我遇到了一个问题,即某些图像会大于原始文件的大小。

调整大小方法:

    public Image reduce(Image sourceImage, string size)
    {
        double percent = Convert.ToDouble(size) / 100;
        int width = (int)(sourceImage.Width * percent);
        int height = (int)(sourceImage.Height *percent );
        var resized = new Bitmap(original, width, height);
        return resized;
    }

使用:

//the code to get the image is omitted (in my testing, bmp format is fixed, however, other image formats are required)
//to test the size of original image
oImage.Save(Path.Combine(oImagepath), System.Drawing.Imaging.ImageFormat.Bmp);

Image nImage = resizeClass.reduce(oImage,"95");
nImage.Save(Path.Combine(nImagepath), System.Drawing.Imaging.ImageFormat.Bmp);

结果:

  • 第一次保存图片:1920*1080,文件大小:6076KB

  • 第二次保存图片:1824*1026,文件大小:7311KB

图片:

更新

原图的Bit depth是24,resize后是32,问题出在这里吗?

【问题讨论】:

  • 您确定将其保存为 BMP 格式吗?
  • @Euphoric,是的!您可以查看上面的图片网址!是 XXXX.bmp 图片
  • 也许原始图像是 16 bpp,输出是 24 bpp?
  • @i486 OOOOOOOH,原来的位深度是24,调整大小是32!!!!!!!!!但是,如何解决呢???

标签: c# image


【解决方案1】:

根据您提供的代码,我制作了一个您可能想要使用的 ExtensionMethod:

public static class ImageExtensions {

    public static System.Drawing.Image Reduce(this System.Drawing.Image sourceImage, double size) {
      var percent = size / 100;
      var width = (int)(sourceImage.Width * percent);
      var height = (int)(sourceImage.Height * percent);         
      Bitmap targetBmp;
      using (var newBmp = new Bitmap(sourceImage, width, height))
        targetBmp = newBmp.Clone(new Rectangle(0, 0, width, height), sourceImage.PixelFormat);
      return targetBmp;
    }

  }

用法

 var nImage = new Bitmap(@"PathToImage").Reduce(50); //Percentage here
 nImage.Save(@"PathToNewImage", ImageFormat.Jpeg); //Change Compression as you need

请注意,这现在是自动确定的,新图像的 x = 0 和 y = 0。我还用双倍替换了字符串百分比。

正如 cmets 中的其他人所提到的,您必须使用与 SourceImage 相同甚至更低的PixelFormat。此外,在 Save-Method 上设置正确/最佳的图像扩展名会减少 FileSize

希望对你有帮助

【讨论】:

  • 为什么destX和destY不为零?
  • 你说得对,第一种方法是按比例提取图像。更新答案
  • 因为我已经修改了我的答案,它应该不再
【解决方案2】:

颜色深度正在增加您的文件大小。

可能有更好的方法,但您可以将生成的 32 位位图转换为 24 位位图

Bitmap clone = new Bitmap(resized.Width, resized.Height,
    System.Drawing.Imaging.PixelFormat.Format24bppRgb);

using (Graphics gr = Graphics.FromImage(clone)) {
    gr.DrawImage(resized, new Rectangle(0, 0, clone.Width, clone.Height));
}

【讨论】:

  • 我必须在增加原始图像深度之前检查原始图像深度,因为原始图像可能是 32 位深度。 (如果是 32 位,我无法将图像转换为 24 位)
  • 你不能只使用 image.PixelFormat 看到这里,它应该给你确切的信息msdn.microsoft.com/en-us/library/…
猜你喜欢
  • 2014-08-03
  • 2011-04-09
  • 2014-02-12
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2018-05-05
  • 1970-01-01
相关资源
最近更新 更多