繁体   English   中英

编辑8bpp索引位图

[英]Editing 8bpp indexed Bitmaps

我正在尝试编辑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.Bitmap一旦调色板设置。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM