wpf - 将 drawing.bitmap 转换为 windows.controls.image

标签 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 = ReadData.GetPhotoFile();

生成错误:
无法将类型“System.Drawing.Bitmap”隐式转换为“System.Windows.Controls.Image”

最好的方法是什么?

最佳答案

不要从该文件创建 System.Drawing.BitmapBitmap 是 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赋给Image控件的Source属性:

imgphoto.Source = ReadData.GetPhotoFile();

关于wpf - 将 drawing.bitmap 转换为 windows.controls.image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579023/

相关文章:

c# - ComboBox SelectedItem 绑定(bind)

c# - 将 BitmapImage 转换为位图,反之亦然

android - 带有触摸事件的移动图像

java - libgdx 如何在图像上添加点击监听器

c++ - 数字识别,神经网络无法正常工作

c# - Silverlight:为图像添加透明度

c# - WPF MVVM 从同一层级导航 betweel View

c# - WPF - 防止用户操作在应用程序繁忙时排队

c# - 将事件发送到特定线程

php - php 获取混合颜色的百分比