gpt4 book ai didi

C# 位图为 Format8bppIndexed 设置像素值

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:47 24 4
gpt4 key购买 nike

我有一个位图。我想更改所有像素的像素值。这是我的代码:

// I use this :
// - int width = 300
// - int height = 400
// - Byte[] matrix = new Byte[width * height]

Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
byte pixValue = matrix[y * width + x];
Color c = Color.FromArgb(pixValue, pixValue, pixValue);
bmp.SetPixel(x, y, c);
}
}

之前,我将这段代码与 Bitmap Format24bppRgb 一起使用,效果很好。现在我将它与 Format8bppIndexed 一起使用,但出现错误:

SetPixel is not supported for images with indexed pixel formats.

我该如何解决?

最佳答案

您不能使用 SetPixel,您应该在嵌套的 loop 中执行类似的操作:

int width = 300;
int height = 400;
Byte[] matrix = new Byte[width * height];
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color colorBefore = bmp.GetPixel(x, y);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
byte[] bytes = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
bytes[y * data.Stride + x] = 7;
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
bmp.UnlockBits(data);
}
}
bmp.Save("D:\\imageBimap1.jpg", ImageFormat.Jpeg);

关于C# 位图为 Format8bppIndexed 设置像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553517/

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