c#位图位图位图位图
-
11-10-2019 - |
题
我在网上某个地方发现了一些代码。
unsafe static Bitmap SaveFrame(IntPtr pFrame, int width, int height)
{
try
{
int x, y;
int linesize = width * 3;
byte* scan0 = (byte*)Marshal.ReadIntPtr(pFrame);
IntPtr bufferPtr = Marshal.AllocHGlobal(linesize * height);
byte* buffer = (byte*)bufferPtr;
for (y = 0; y < height; y++)
{
for (x = 0; x < linesize; x = x + 3)
{
*buffer++ = (byte)*(scan0 + y * linesize + x + 2);
*buffer++ = (byte)*(scan0 + y * linesize + x + 1);
*buffer++ = (byte)*(scan0 + y * linesize + x);
}
}
Bitmap b = new Bitmap(width, height, linesize, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bufferPtr);
return b;
}
catch (Exception ex) { throw new Exception(ex.Message); }
}
以上代码为我提供了有效的位图,但是我正在使用WPF,并希望它在位图中
在不进行此过程的情况下,即时通讯尝试代码
byte[] ptr = ....
Marshal.Copy(pFrame, ptr , 0, ptr .Length);
BitmapImage aBitmapImage = new BitmapImage();
aBitmapImage.BeginInit();
aBitmapImage.StreamSource = new MemoryStream(ptr); //FLastImageMemStream;//
aBitmapImage.EndInit();
它不起作用...
我也尝试了
System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96,
System.Windows.Media.PixelFormats.Rgb24, null, bufferPtr,linesize * height,
width * 3 ));
这也没有给我一个图像(将其分配给图像的源属性之后)
谁能给我任何提示?谢谢艾伦
解决方案
将数据直接加载到位映射不起作用,因为它以图像文件格式期望数据,就像您在.bmp或.png文件中看到的那样。您改用原始像素数据。
您的第二种方法看起来应该起作用,但有一些不必要的步骤。您发现的代码是将像素数据从BGR24重写为RGB24,但是您应该能够直接将其直接加载为BGR24:
System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96,
System.Windows.Media.PixelFormats.Bgr24, null, pFrame, linesize * height,
width * 3 ));
无论如何,您是否有有关为什么不给您图像的详细信息?创建位图时,您是否有任何例外?它给出了错误的颜色还是错误的尺寸?您确定所有源数据都存在吗?创建它之后,您在BitMapsource的属性上看到了什么?
不隶属于 StackOverflow