rgb32 byte[] to bitmap(100分 请帮忙)
我需要把rgb32 的 byte[]数组 转换到 bitmap 对象中
写了下面函数,但是发现转换回来的图像是灰色的,图像里面的文字能看出来。
估计是颜色方面出了问题。但是看不出错误来。
麻烦大家帮忙看看。
非常感谢。
// Create RGB32 bitmap from Byte array
Bitmap BitsToBitmapRGB32(Byte[] bytes, int width, int height)
{
//swap ARGB to BGRA
Byte tmp;
for (int x = 4; x < bytes.GetLength(0); x += 4)
{
//swap A B
tmp = bytes[(x + 3)];
bytes[x + 3] = bytes[x];
bytes[x] = tmp;
//swap R G
tmp = bytes[(x + 2)];
bytes[x + 2] = bytes[x+1];
bytes[x+1] = tmp;
}
if (bytes.GetLength(0) < width * height * 4)
{
return null;
}
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
int i;
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
if (data.Stride == width * 4)
{
Marshal.Copy(bytes, 0, data.Scan0, width * height * 4);
}
else
{
for (i = 0; i < bmp.Height; i++)
{
IntPtr p = new IntPtr(data.Scan0.ToInt32() + data.Stride * i);
Marshal.Copy(bytes, i * bmp.Width * 4, p, bmp.Width * 4);
}
}
bmp.UnlockBits(data);
return bmp;
}