C# 为什么缩小宽度和高度后,我的BMP图像比原始图像大?
在我的项目中,我必须调整图像的大小,然后将其保存到文件夹中。然而,我遇到了一个问题,一些图像将大于原始的文件大小 调整大小方法:C# 为什么缩小宽度和高度后,我的BMP图像比原始图像大?,c#,image,C#,Image,在我的项目中,我必须调整图像的大小,然后将其保存到文件夹中。然而,我遇到了一个问题,一些图像将大于原始的文件大小 调整大小方法: public Image reduce(Image sourceImage, string size) { double percent = Convert.ToDouble(size) / 100; int width = (int)(sourceImage.Width * percent); int
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根据您提供的代码,我已经创建了一个您可能想要使用的扩展方法:
用法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; } }
请注意,现在自动确定新图像的x=0和y=0。我还将字符串百分比替换为双百分比 正如评论中提到的其他人一样,您必须使用与源图像相同或更低的var nImage = new Bitmap(@"PathToImage").Reduce(50); //Percentage here nImage.Save(@"PathToNewImage", ImageFormat.Jpeg); //Change Compression as you need
。另外,在Save方法上设置right/best图像扩展可以减小文件大小PixelFormat
希望这有帮助颜色深度正在增加您的文件大小 可能有更好的方法,但您可以将生成的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)); }
你绝对确定要将其保存为BMP吗?@Euphoric,是的!您可以查看上面的图像url!它是XXXX.bmp图像可能原始图像是16 bpp,输出是24 bpp?@i486 ooooo h,原始图像的位深度是24,大小是32!!!!!!!但是,如何修复它???我必须检查原始图像的深度,然后再增加它,因为原始图像可能是32位深度。(如果图像是32位,我无法将其转换为24位)你不能只使用图像。PixelFormat看这里,它应该准确地告诉你为什么它不是destX和destY的零?你是对的,第一种按比例提取图像的方法。更新的答案既然我已经修改了我的答案,就不应该再修改了