gpt4 book ai didi

c# - 将 32 位位图转换为 8 位(彩色和灰度)

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:25 29 4
gpt4 key购买 nike

我有一个 System.Drawing.Bitmap,其 PixelFormatFormat32bppRgb。我想把这张图片转换成8bit的位图。

以下是将 32 位图像转换为 8 位灰度图像的代码:

        public static Bitmap ToGrayscale(Bitmap bmp)
{
int rgb;
System.Drawing.Color c;

for (int y = 0; y < bmp.Height; y++)
for (int x = 0; x < bmp.Width; x++)
{
c = bmp.GetPixel(x, y);
rgb = (int)((c.R + c.G + c.B) / 3);
bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(rgb, rgb, rgb));
}
return bmp;
}

但是,我最终得到的 Bitmap 仍然具有 Format32bppRgb 的 PixelFormat 属性。

此外,

  • 如何将 32 位彩色图像转换为 8 位彩色图像?

感谢任何输入!

相关。
- Convert RGB image to RGB 16-bit and 8-bit
- C# - How to convert an Image into an 8-bit color Image?
- C# Convert Bitmap to indexed colour format
- Color Image Quantization in .NET
- quantization (Reduction of colors of image)
- The best way to reduce quantity of colors in bitmap palette

最佳答案

您必须创建(并返回)Bitmap 的新实例。

PixelFormat 在 Bitmap 的构造函数中指定,不能更改。

编辑(2022 年 3 月 30 日):修复了从 x * data.Stride + y 到 y * data.Stride + x 的字节数组访问表达式并将调色板更改为灰度。

编辑:示例代码基于 this answer on MSDN :

    public static Bitmap ToGrayscale(Bitmap bmp) {
var result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed);

var resultPalette = result.Palette;

for (int i = 0; i < 256; i++)
{
resultPalette.Entries[i] = Color.FromArgb(255, i, i, i);
}

result.Palette = resultPalette;

BitmapData data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

// Copy the bytes from the image into a byte array
byte[] bytes = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

for (int y = 0; y < bmp.Height; y++) {
for (int x = 0; x < bmp.Width; x++) {
var c = bmp.GetPixel(x, y);
var rgb = (byte)((c.R + c.G + c.B) / 3);

bytes[y * data.Stride + x] = rgb;
}
}

// Copy the bytes from the byte array into the image
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);

result.UnlockBits(data);

return result;
}

关于c# - 将 32 位位图转换为 8 位(彩色和灰度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891219/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com