在减小宽度和高度后,为什么我的BMP图像比原始图像大?

时间:2016-09-26 09:20:18

标签: c# image

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

调整大小的方法:

    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,fileSize: 6076KB

  •   
  • 第二次保存图片:1824 * 1026,fileSize: 7311KB < =应该小于6076KB

  •   

图像:

更新

原始图像的位深度为24,调整大小为32.这里有问题吗?

2 个答案:

答案 0 :(得分: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.此外,我用双倍的字符串替换了字符串百分比。

与上述评论中的其他人一样,您必须使用相同甚至更低的PixelFormat作为SourceImage。此外,在Save-Method上设置正确/最佳图像扩展名会减少FileSize

希望这有帮助

答案 1 :(得分:1)

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

可能有更好的方法,但您可以将生成的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));
}