转换一个BGR位图RGB [英] Converting a BGR bitmap to RGB

查看:2188
本文介绍了转换一个BGR位图RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一个网凸轮得到位图从缓冲区。当我分配给某个图片框红色和蓝色是相反的。

I am getting bitmaps from a buffer from a net cam. When I assign these to a PictureBox the red and blue are reversed.

我能做些什么,以位图或图片框获得在适当的地方,红色和蓝色的?

What can I do to the bitmap or to the PictureBox to get the red and blue in their proper places?

推荐答案

以下code确实需要的转换:

The following code does the needed conversion:

public static void RGBtoBGR(Bitmap bmp)
{
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                                   ImageLockMode.ReadWrite, bmp.PixelFormat);

    int length = Math.Abs(data.Stride) * bmp.Height;

    unsafe
    {
        byte* rgbValues = (byte*)data.Scan0.ToPointer();

        for (int i = 0; i < length; i += 3)
        {
            byte dummy = rgbValues[i];
            rgbValues[i] = rgbValues[i + 2];
            rgbValues[i + 2] = dummy;
        }
    }

    bmp.UnlockBits(data);
}

LockBits 锁定位图在内存中,这样就可以直接访问和修改的内容。如果你不希望有一个不安全的情况下,你可以创建一个字节数组,并使用的 Marshal.Copy 将数据复制到其中,并返回到操作后,该位图。使用 LockBits 是最快的选项来处理位图数据(大于 GetPixel SetPixel <快得多/ code>)。

LockBits locks the bitmap in memory so that you can access and change the contents directly. If you don't want to have an unsafe context you can create a byte array and use Marshal.Copy to copy the data into it and back to the bitmap after manipulating. Using LockBits is the fastest option to manipulate bitmap data (much faster than GetPixel or SetPixel).

的循环迭代( I + = 3 )取决于的 的PixelFormat 位图。在这里,我假定这是 PixelFormat.Format24bppRgb 。对于 Format32bppArgb 这将是 I + = 4

The loop iterator (i += 3) depends on the PixelFormat of the bitmap. Here I am assuming it is PixelFormat.Format24bppRgb. For Format32bppArgb it would be i += 4.

这篇关于转换一个BGR位图RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆