【问题标题】:Convert drawing.bitmap to windows.controls.image将drawing.bitmap 转换为windows.controls.image
【发布时间】:2017-05-25 13:03:45
【问题描述】:

我正在从智能卡读取数据。 该数据还包含一张图片。 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”

这方面最好的方法是什么?

【问题讨论】:

    标签: wpf image bitmap type-conversion


    【解决方案1】:

    不要从该文件创建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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2014-07-20
      • 2017-01-27
      • 2013-05-10
      • 2020-09-28
      • 2013-07-26
      相关资源
      最近更新 更多