C# 如何在Magick.NET中创建8 bpp BMP?

C# 如何在Magick.NET中创建8 bpp BMP?,c#,magick.net,C#,Magick.net,使用Magick.NET-Q8-AnyCPU。我想将现有TIFF图像转换为灰度8 bpp BMP图像。我试过这个: byte[] input = <existing TIFF image>; using (var image = new MagickImage(input)) { image.Grayscale(); image.ColorType = ColorType.Palette; image.Depth = 8; image.Quantize

使用Magick.NET-Q8-AnyCPU。我想将现有TIFF图像转换为灰度8 bpp BMP图像。我试过这个:

byte[] input = <existing TIFF image>;
using (var image = new MagickImage(input))
{
    image.Grayscale();
    image.ColorType = ColorType.Palette;
    image.Depth = 8;
    image.Quantize(new QuantizeSettings() { Colors = 256,  DitherMethod = DitherMethod.No });

    byte[] result = image.ToByteArray(MagickFormat.Bmp);

    return result;
}
byte[]输入=;
使用(var image=new MagickImage(输入))
{
image.Grayscale();
image.ColorType=ColorType.palete;
图像深度=8;
Quantize(新的QuantizeSettings(){Colors=256,DitherMethod=DitherMethod.No});
字节[]结果=image.ToByteArray(MagickFormat.Bmp);
返回结果;
}
在FastStone Viewer中,图像报告为8位,但在文件属性>详细信息中,图像报告为位深度:32。我需要这里是8点。我可以在Paint.NET中转换此图像,当我选择“位深度:8位”时,新图像将在文件属性中正确显示8位深度


因此,Paint.NET会创建正确的8位位图。如何使用Magick.NET?这似乎是不可能的。
image.Depth=8
image.BitDepth(8)
都不起作用。 根目录可能位于:

// ImageMagick.MagickImage.NativeMethods.X{ver.}
[DllImport("Magick.Native-Q8-x{ver.}.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MagickImage_SetBitDepth(IntPtr Instance, UIntPtr channels, UIntPtr value);

看起来它无法创建8位
.bmp
,尽管
.png
没有问题

var original = @"D:\tmp\0.tif";
var copy = @"D:\tmp\0.bmp";

using (var image = new MagickImage(original))
{
    image.Grayscale();
    image.ColorType = ColorType.Palette;
    image.Quantize(new QuantizeSettings() { Colors = 256, DitherMethod = DitherMethod.No });
    byte[] result = image.ToByteArray(MagickFormat.Png8);
    File.WriteAllBytes(copy, result);
}
Console.WriteLine("Press 'Enter'..."); // one have 8 bits .png here
Console.ReadLine();
using (var image = new MagickImage(copy))
{
    byte[] result = image.ToByteArray(MagickFormat.Bmp3);
    File.WriteAllBytes(copy, result);
} // but ends up with 32 bits .bmp again here
我还注意到

image.Quantize(new QuantizeSettings() { Colors = 16, DitherMethod = DitherMethod.No });

产生4位结果。逐渐增加会得到32位,但不会是8位。

Windows资源管理器将所有压缩的BMP文件显示为32位,与实际位深度相反

我不知道它是不是一个bug,但我更接近于称它为bug

因为,;使用代码创建8bpp BMP文件后,当我使用二进制编辑器打开该文件时,在位图头结构中,我看到每像素位字段值(块28-29)为
8
。另外,下一个字节
01
(偏移量30)意味着压缩的数据是一种简单的无损数据压缩算法

因此,我可以说,您使用Magick.NET生成的图像没有问题,它当然是一个8bpp的BMP图像文件,但经过压缩

与Magick.NET的默认设置不同,Paint.NET似乎会生成未压缩的BMP文件,这就是为什么由于Windows资源管理器的怪异性,您会看到不同的位深度

要解决此问题,可以禁用压缩,以便“属性”对话框中显示的位深度值将是您期望的值

image.Settings.Compression=CompressionMethod.NoCompression;
字节[]结果=image.ToByteArray(MagickFormat.Bmp);
image.Quantize(new QuantizeSettings() { Colors = 16, DitherMethod = DitherMethod.No });