gpt4 book ai didi

c# - 抓取位图图像(Winforms)并转换为 WPF 图像失败

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:13 24 4
gpt4 key购买 nike

我从外部摄像头抓取图像。 winforms 应用程序到目前为止工作。现在我需要将它传输到 WPF。因此,我像这样将位图图像转换为 WPF:

    GrabHandler frameCallbackDelegate;
void frameCallBack(IntPtr lpUserData, ref VCECLB_FrameInfoEx frameInfo)
{
if (frameInfo.dma_status != 0) return;

// fill image
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

BitmapData bmdata = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);

UInt32 outputBitDepth;
IntPtr stride = new IntPtr(bmdata.Stride);

VCECLB_Error err = NativeFunctions.VCECLB_UnpackRawPixelsEx(ref pRawPixelInfo, frameInfo.lpRawBuffer, bmdata.Scan0, ref stride, VCECLB_Output_Format.VCECLB_EX_FMT_TopDown | VCECLB_Output_Format.VCECLB_EX_FMT_3Channel, out outputBitDepth);

image.UnlockBits(bmdata);



Dispatcher.Invoke(new Action(() =>
{
// Convert bitmap to WPF-Image
var bmp = new Bitmap(image);
var hBitmap = bmp.GetHbitmap();

ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());

image_LowLight.Source = wpfBitmap;

DeleteObject(hBitmap);
image.Dispose();
}));
GC.Collect();


}


private void StartGrab(object sender, RoutedEventArgs e)
{
start_button.IsEnabled = true;
stop_button.IsEnabled = false;

frameCallbackDelegate = new GrabHandler(frameCallBack);
m_ImageAquisition.StartGrab(frameCallbackDelegate);
}

当我第一次从 StartGrab 进入 frameCallBack 时,image.Widthimage.Height 有一个有效值(不是 0)并且看起来是正确的。当第二次输入 frameCallBack 时,所有图像数据(宽度和高度)均为 0,因此 rect 会出错。

我使用 Dispatcher.Invoke 获取有效位图图像的方式有问题吗?

谢谢!

最佳答案

避免在稍后由 Dispatcher 执行的 Action() 中使用 volatile 数据。

像这样重构你的代码:

   GrabHandler frameCallbackDelegate;
void frameCallBack(IntPtr lpUserData, ref VCECLB_FrameInfoEx frameInfo)
{
if (frameInfo.dma_status != 0) return;

// fill image
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

BitmapData bmdata = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);

UInt32 outputBitDepth;
IntPtr stride = new IntPtr(bmdata.Stride);

VCECLB_Error err = NativeFunctions.VCECLB_UnpackRawPixelsEx(ref pRawPixelInfo, frameInfo.lpRawBuffer, bmdata.Scan0, ref stride, VCECLB_Output_Format.VCECLB_EX_FMT_TopDown | VCECLB_Output_Format.VCECLB_EX_FMT_3Channel, out outputBitDepth);

image.UnlockBits(bmdata);

// Convert bitmap to WPF-Image
var bmp = new Bitmap(image);
var hBitmap = bmp.GetHbitmap();

ImageSource wpfBitmap =
System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());

DeleteObject(hBitmap);
image.Dispose();

Dispatcher.Invoke(new Action(() =>
{
image_LowLight.Source = wpfBitmap;
}));
GC.Collect();
}

关于c# - 抓取位图图像(Winforms)并转换为 WPF 图像失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28021089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com