Wpf 将drawing.bitmap转换为windows.controls.image

Wpf 将drawing.bitmap转换为windows.controls.image,wpf,image,bitmap,type-conversion,Wpf,Image,Bitmap,Type Conversion,我正在从智能卡读取数据。 该数据还包含一张图片。 获取类ReadData中图片的代码: public Bitmap GetPhotoFile() { byte[] photoFile = GetFile("photo_file"); Bitmap photo = new Bitmap(new MemoryStream(photoFile)); return photo; } xaml中的代码: imgphoto = ReadDat

我正在从智能卡读取数据。 该数据还包含一张图片。 获取类ReadData中图片的代码:

public Bitmap GetPhotoFile()
    {
        byte[] photoFile = GetFile("photo_file");
        Bitmap photo = new Bitmap(new MemoryStream(photoFile));
        return photo;
    }
xaml中的代码:

imgphoto = ReadData.GetPhotoFile();
生成错误:
无法将类型“System.Drawing.Bitmap”隐式转换为“System.Windows.Controls.Image”


最好的方法是什么?

不要从该文件创建
系统.Drawing.Bitmap
<代码>位图是WinForms,而不是WPF

而是创建一个WPF
BitmapImage

public ImageSource GetPhotoFile()
{
    var photoFile = GetFile("photo_file");
    var photo = new BitmapImage();

    using (var stream = new MemoryStream(photoFile))
    {
        photo.BeginInit();
        photo.CacheOption = BitmapCacheOption.OnLoad;
        photo.StreamSource = stream;  
        photo.EndInit();
    }

    return photo;
}
然后将返回的
ImageSource
分配给图像控件的
Source
属性:

imgphoto.Source = ReadData.GetPhotoFile();

不要从该文件创建
System.Drawing.Bitmap
<代码>位图是WinForms,而不是WPF

而是创建一个WPF
BitmapImage

public ImageSource GetPhotoFile()
{
    var photoFile = GetFile("photo_file");
    var photo = new BitmapImage();

    using (var stream = new MemoryStream(photoFile))
    {
        photo.BeginInit();
        photo.CacheOption = BitmapCacheOption.OnLoad;
        photo.StreamSource = stream;  
        photo.EndInit();
    }

    return photo;
}
然后将返回的
ImageSource
分配给图像控件的
Source
属性:

imgphoto.Source = ReadData.GetPhotoFile();