编辑8bpp索引位图

我正在尝试编辑8bpp的像素。 由于此PixelFormat已编制索引,我知道它使用颜色表来映射像素值。 即使我可以通过将位图转换为24bpp来编辑位图,但8bpp编辑速度要快得多(13ms vs 3ms)。 但是,在访问8bpp位图时更改每个值会导致一些随机的rgb颜色,即使PixelFormat仍为8bpp。

我目前正在开发c#,算法如下:

(C#)

1-将原始位图加载到8bpp

2-创建具有8bpp的空温度位图,其大小与原始尺寸相同

两个位图的3-LockBits,使用P / Invoke调用c ++方法,我传递每个BitmapData对象的Scan0。 (我使用了c ++方法,因为它在迭代Bitmap的像素时提供了更好的性能)

(C ++)

4-根据一些参数创建一个int [256]调色板,并通过将原始像素值传递到调色板来编辑临时位图字节。

(C#)

5- UnlockBits。

我的问题是如何在没有奇怪的rgb颜色的情况下编辑像素值,甚至更好地编辑8bpp位图的颜色表?

根本没有必要进入C ++领域或使用P / Invoke; C#完全支持指针和不安全的代码; 我甚至可能会猜测这会导致你的问题。

颜色可能来自默认的调色板。 您会发现更改调色板应该不会很慢。 这是我创建灰度调色板的方法:

image = new Bitmap( _size.Width, _size.Height, PixelFormat.Format8bppIndexed); ColorPalette pal = image.Palette; for(int i=0;i<=255;i++) { // create greyscale color table pal.Entries[i] = Color.FromArgb(i, i, i); } image.Palette = pal; // you need to re-set this property to force the new ColorPalette 

想象一下,您的索引8ppp灰度存储在线性数组dataB中(速度)

试试这段代码:

 //Create 8bpp bitmap and look bitmap data bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed); bmp.SetResolution(horizontalResolution, verticalResolution); bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); //Create grayscale color table ColorPalette palette = bmp.Palette; for (int i = 0; i < 256; i++) palette.Entries[i] = Color.FromArgb(i, i, i); bmp.Palette = palette; //write data to bitmap int dataCount = 0; int stride = bmpData.Stride < 0 ? -bmpData.Stride : bmpData.Stride; unsafe { byte* row = (byte*)bmpData.Scan0; for (int f = 0; f < height; f++) { for (int w = 0; w < width; w++) { row[w] = (byte)Math.Min(255, Math.Max(0, dataB[dataCount])); dataCount++; } row += stride; } } //Unlock bitmap data bmp.UnlockBits(bmpData); 

您是否尝试过加载System.Drawing.Image ? 该类使您可以访问调色板。 然后,您可以在设置调色板后将System.Drawing.Image包装为System.Drawing.Image

我不确定System.Drawing.BitMap.SetPixel()如何使用索引的彩色图像。 它可能会尝试将其映射到调色板中最接近的颜色。

我没有足够的声誉来评论Paul Ruane的post,但不得不说他将文件加载到System.Drawing.Image更改了调色板并将生成的Image发送到System.Drawing.Bitmap以保存实际工作。

>如果我直接通过Image保存,则更改将被丢弃。

>如果我通过Bitmap保存,则保留更改。