C# RGB 24到位图,生成黑色图像
我似乎无法将我的大脑完全围绕图像,并将它们从原始RGB颜色的C# RGB 24到位图,生成黑色图像,c#,image,bitmap,C#,Image,Bitmap,我似乎无法将我的大脑完全围绕图像,并将它们从原始RGB颜色的字节[]转换为位图。我找到了一种解决方案,可以使用SetPixel将RGB 24bppbyte[]转换为BitMap,但我已经了解到使用LockBits的速度要快得多,所以我正试图弄清楚如何这样做 使用SetPixel方法,我使用以下方法获得反转图像: public static Bitmap CreateBitmap24bppRgb(byte[] bmpData, int width, int height) { var bm
字节[]
转换为位图。我找到了一种解决方案,可以使用SetPixel
将RGB 24bppbyte[]
转换为BitMap
,但我已经了解到使用LockBits
的速度要快得多,所以我正试图弄清楚如何这样做
使用SetPixel
方法,我使用以下方法获得反转图像:
public static Bitmap CreateBitmap24bppRgb(byte[] bmpData, int width, int height)
{
var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
var pos = 0;
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
bmp.SetPixel(x, y, Color.FromArgb(bmpData[pos], bmpData[pos + 1], bmpData[pos + 2]));
pos += 3;
}
}
return bmp;
}
我只是好奇这里出了什么问题?如果您正在创建一个新位图,而不是修改现有位图,那么没有理由使用锁位或封送。复制
随你的便
(或者使用不安全的
块、固定的
关键字和指针)如果要创建新位图,而不是修改现有位图,则没有理由使用锁位
或封送。复制
随你的便
(或者使用不安全的块、固定的关键字和指针)位图数据通常是颠倒存储的。您的Marshal.Copy()方法看起来像是毫无意义的post代码,实际上可以编译。第三个参数可能应该是bmpData.Scan0+(bmp.Height-y-1)*bmpData.Stride。除了Hans的评论外:在锁定期间,您如何处理数据?您必须在那里设置一些像素的通道。。!例如,查看工作锁定位代码的示例。当然还有很多。位图数据通常是颠倒存储的。您的Marshal.Copy()方法看起来像是毫无意义的post代码,实际上可以编译。第三个参数可能应该是bmpData.Scan0+(bmp.Height-y-1)*bmpData.Stride。除了Hans的评论外:在锁定期间,您如何处理数据?您必须在那里设置一些像素的通道。。!例如,查看工作锁定位代码的示例。当然还有很多。。
public static Bitmap CreateBitmap24bppRgb(byte[] data, int width, int height)
{
var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
//Create a BitmapData and Lock all pixels to be written
var bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
for (int y = 0; y < bmp.Height - 1; y++)
{
Marshal.Copy(data, y * bmp.Width, bmpData.Scan0 bmpData.Stride);
}
//Unlock the pixels
bmp.UnlockBits(bmpData);
return bmp;
}
public static Bitmap CreateBitmap24bppRgb(byte[] data, int width, int height)
{
GCHandle pin = GCHandle.Alloc(data, GCHandleType.Pinned);
var bmp = new Bitmap(width, height,
(width * 3 + 3) / 4 * 4,
PixelFormat.Format24bppRgb,
Marshal.UnsafeAddrOfPinnedArrayElement(data, 0));
bmp = (Bitmap)bmp.Clone(); // workaround the requirement that the memory address stay valid
// the clone step can also crop and/or change PixelFormat, if desired
GCHandle.Free(pin);
return bmp;
}