我需要在WPF控件上显示实时图像。我正在寻找使用WPF执行此操作的最快方法。如何从像素字节数组(现场视频显示)创建BitmapImage
我使用它的dll API从相机捕获图像(AVT)。
该图像是由dll写的,并且相机用一个IntPtr将一个回调上升到一个名为tFrame(如下所述)的图像结构。像素数据存储在ImageBuffer属性中,并且是一个InPtr到一个字节数组。
我知道如何从像素字节数组创建一个位图,但不是BitmapImage。所以可以创建一个Bitmap,然后从中创建一个BitmapImagem。 Here there is a way to create a BitmapImage from a Bitmap on the memory。但我想直接从数据源(tFrame)创建BitmapImage。我怎样才能做到这一点?
我知道BitmapImage有一个CopyPixels方法,但它有一个SetPixels。
public struct tFrame
{
public IntPtr AncillaryBuffer;
public uint AncillaryBufferSize;
public uint AncillarySize;
public tBayerPattern BayerPattern;
public uint BitDepth;
public tFrameCtx Context;
public tImageFormat Format;
public uint FrameCount;
public uint Height;
public IntPtr ImageBuffer;
public uint ImageBufferSize;
public uint ImageSize;
public uint RegionX;
public uint RegionY;
public tErr Status;
public uint TimestampHi;
public uint TimestampLo;
public uint Width;
}
这是我如何从像素字节数组创建位图。这是在WinForm版本的软件中使用的。
private void CreateBitmap(tFrame frame)
{
//This sample is for a 8bpp captured image
PixelFormat pxFormat = PixelFormat.Format8bppIndexed;
//STRIDE
//[https://stackoverflow.com/questions/1983781/why-does-bitmapsource-create-throw-an-argumentexception/1983886#1983886][3]
//float bitsPerPixel = System.Drawing.Image.GetPixelFormatSize(format);
int bitsPerPixel = ((int)pxFormat >> 8) & 0xFF;
//Number of bits used to store the image data per line (only the valid data)
int validBitsPerLine = ((int)frame.Width) * bitsPerPixel;
//4 bytes for every int32 (32 bits)
int stride = ((validBitsPerLine + 31)/32) * 4;
Bitmap bmp = new Bitmap((int)frame.Width, (int)frame.Height, stride, pxFormat, frame.ImageBuffer);
}
编辑1:
感谢dr.mo,现在我能够用约3%的CPU使用率,以显示60倍1024×1024的图像! 我在做什么是:
//@ UI Thread
public WriteableBitmap wbm = new WriteableBitmap(1024, 1024, (double)96, (double)96, System.Windows.Media.PixelFormats.Gray8, null);
this.wbBackBuffer = this.wbm.BackBuffer;
//This can be called by a timer in the UI thread or at the grab Thread for every image, the CPU usage is almost the same.
void UpdateDisplayImage()
{
wbm.Lock();
wbm.AddDirtyRect(new Int32Rect(0, 0, wbm.PixelWidth, wbm.PixelHeight));
wbm.Unlock();
}
//@ Grab Thread
//Update the backbuffer with new camera image data.
UpdateBackBuffer(...);
/// <summary>
/// [http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx]
/// </summary>
public void UpdateBackBuffer(IntPtr pData, int w, int h, int ch)
{
//Can not acess wbm from outside UI thread
//CopyMemory(wbm.BackBuffer, pData, (uint)(w * h * ch));
//I dont know if it is safe to write to it buffer like this:
CopyMemory(this.wbBackBuffer, pData, (uint)(w * h * ch));
}
msdn.microsoft.com/en-gb/library/system.windows.interop.imaging.createbitmapsourcefrommemorysection.aspx – DarkSquirrel42 2013-04-25 16:55:43
看到这一点:http://stackoverflow.com/a/15290190/1507182 – Obama 2013-04-25 16:57:47
@ DarkSquirrel42。对不起,链接已损坏。 – Pedro77 2013-04-25 17:18:20