System.Drawing.Bitmap尝试设置图像源

时间:2013-12-17 19:18:17

标签: c# wpf image binding bitmap

我试图设置图像控件的源,我每隔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;
}

0 个答案:

没有答案