Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# System.Drawing.Bitmap正在尝试设置图像源_C#_Wpf_Image_Binding_Bitmap - Fatal编程技术网

C# System.Drawing.Bitmap正在尝试设置图像源

C# System.Drawing.Bitmap正在尝试设置图像源,c#,wpf,image,binding,bitmap,C#,Wpf,Image,Binding,Bitmap,我正在尝试设置图像控件的源,我每2秒从事件中获取位图。我首先尝试的是在没有绑定的情况下设置源代码 public void FiletransferImage(string _id, Bitmap _Image) { try { imgDesktop.Source = ToBitmapSource(_Image); } catch (Exception ex) { MessageBox

我正在尝试设置图像控件的源,我每2秒从事件中获取位图。我首先尝试的是在没有绑定的情况下设置源代码

public void FiletransferImage(string _id, Bitmap _Image)
    {
        try {

                imgDesktop.Source = ToBitmapSource(_Image);
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }


    public static BitmapSource ToBitmapSource(System.Drawing.Bitmap source)
    {
        BitmapSource bitSrc = null;

        var Bitmap_ = source.GetHbitmap();

        try {

            bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                Bitmap_,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        catch (Exception ex) {
            bitSrc = null;
        }
        finally {

        }

        return bitSrc;
    }
但是图像控件不显示图像。我也试着把图像绑定起来

Image Name="imgDesktop" Source={Binding ImgSource}">


public ImageSource YourImage {get;set;}
有人知道我做错了什么吗

编辑:我找到了一个解决方案,我将字节数组转换为位图图像,这对我很有效:

public void GetImage(byte[] buffer)
        {
BitmapImage img = new BitmapImage();
        img.BeginInit();
        img.StreamSource = new MemoryStream(buffer);
        img.EndInit();
        this.imgDesktop.Source = img;
}

首先,你是。但更重要的是,调用FiletransferImage后,您的代码在做什么?是否有可能使UI线程处于休眠状态?其他可能是图像控件本身的大小不正确,或者其实际宽度/实际高度为0-还请注意,WPF不使用绝对像素值,而是使用基于96 DPI的逻辑像素尺寸。然后,还有一种可能性是位图实际上是一个空位图…是的,我检查了位图并通过了调试器,但一切似乎都正常,唯一的问题是什么也没有发生。事件每2秒触发一个新映像。好的,让我们找出不同的潜在原因。首先在VS中创建一些用于测试的图像资源,完成后可以将它们丢弃,并让FiletransferImage将它们提供给图像控件。不要为此使用位图对象。如果这样做有效,您的问题在于提供的位图对象及其转换。如果它不起作用,那么您的UI中就有可疑的东西。如果您已经尝试过,请在这里继续,以便我们能够正确地找到问题的原因。。。