将8位彩色bmp图像转换为8位灰度bmp

cro*_*wso 4 c# bitmap

这是我的位图对象

Bitmap b = new Bitmap(columns, rows, PixelFormat.Format8bppIndexed);
BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat);
Run Code Online (Sandbox Code Playgroud)

如何将其转换为8位灰度位图?

Han*_*ant 5

是的,无需更改像素,只需调色板就可以了.ColorPalette是一个片状类型,这个示例代码运行良好:

        var bmp = Image.FromFile("c:/temp/8bpp.bmp");
        if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format8bppIndexed) throw new InvalidOperationException();
        var newPalette = bmp.Palette;
        for (int index = 0; index < bmp.Palette.Entries.Length; ++index) {
            var entry = bmp.Palette.Entries[index];
            var gray = (int)(0.30 * entry.R + 0.59 * entry.G + 0.11 * entry.B);
            newPalette.Entries[index] = Color.FromArgb(gray, gray, gray);
        }
        bmp.Palette = newPalette;    // Yes, assignment to self is intended
        if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
        pictureBox1.Image = bmp;
Run Code Online (Sandbox Code Playgroud)

我实际上并不建议你使用这个代码,索引的像素格式是一个pita来处理.您将在此答案中找到快速且更通用的颜色到灰度转换.