编辑8bpp索引位图

时间:2010-04-07 14:21:24

标签: c# gdi+ bitmap indexed

我正在尝试编辑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位图的颜色表?

3 个答案:

答案 0 :(得分:10)

根本没有必要进入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

答案 1 :(得分:2)

想象一下,你的索引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);

答案 2 :(得分:1)

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

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

相关问题