C# 单线程将8位Bitmap保存为bmp格式图片,怎样做速度最快,占用磁盘空间最小,EncoderValue.CompressionRLE没有效果,并且在重新加载图片后能得到压缩前的图片
时间: 2024-01-16 18:02:53 浏览: 201
c# bmp格式图片压缩
5星 · 资源好评率100%
如果要在重新加载图片后得到压缩前的图片,就需要使用无损压缩方式,比如EncoderValue.CompressionNone。这种压缩方式不会降低图片质量,但会增加文件大小。
以下是一个示例代码,可以将8位Bitmap保存为bmp格式图片,速度较快,同时占用磁盘空间较小,且使用无损压缩方式:
```
public static void SaveBitmap(Bitmap bitmap, string fileName)
{
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
int stride = bmpData.Stride;
int height = bmpData.Height;
byte[] data = new byte[stride * height];
Marshal.Copy(bmpData.Scan0, data, 0, data.Length);
bitmap.UnlockBits(bmpData);
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BitmapInfoHeader bmiHeader = new BitmapInfoHeader();
bmiHeader.biSize = 40;
bmiHeader.biWidth = bitmap.Width;
bmiHeader.biHeight = bitmap.Height;
bmiHeader.biPlanes = 1;
bmiHeader.biBitCount = 8;
bmiHeader.biCompression = 0;
bmiHeader.biSizeImage = data.Length;
bmiHeader.biXPelsPerMeter = 0;
bmiHeader.biYPelsPerMeter = 0;
bmiHeader.biClrUsed = 256;
bmiHeader.biClrImportant = 256;
byte[] header = new byte[bmiHeader.biSize];
BitConverter.GetBytes(bmiHeader.biSize).CopyTo(header, 0);
BitConverter.GetBytes(bmiHeader.biWidth).CopyTo(header, 4);
BitConverter.GetBytes(bmiHeader.biHeight).CopyTo(header, 8);
BitConverter.GetBytes(bmiHeader.biPlanes).CopyTo(header, 12);
BitConverter.GetBytes(bmiHeader.biBitCount).CopyTo(header, 14);
BitConverter.GetBytes(bmiHeader.biCompression).CopyTo(header, 16);
BitConverter.GetBytes(bmiHeader.biSizeImage).CopyTo(header, 20);
BitConverter.GetBytes(bmiHeader.biXPelsPerMeter).CopyTo(header, 24);
BitConverter.GetBytes(bmiHeader.biYPelsPerMeter).CopyTo(header, 28);
BitConverter.GetBytes(bmiHeader.biClrUsed).CopyTo(header, 32);
BitConverter.GetBytes(bmiHeader.biClrImportant).CopyTo(header, 36);
fs.Write(header, 0, header.Length);
fs.Write(data, 0, data.Length);
ImageCodecInfo bmpCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID == ImageFormat.Bmp.Guid);
if (bmpCodecInfo != null)
{
fs.Flush();
fs.Position = header.Length;
bmp.Save(fs, bmpCodecInfo, encoderParams);
}
}
}
```
注意:由于使用了无损压缩方式,文件大小可能会比原始图片大。
阅读全文