How do i read a base64 image in WPF?

后端 未结 3 943
刺人心
刺人心 2020-12-08 20:49

I know how to do it in WinForms

byte[] binaryData = Convert.FromBase64String(bgImage64);
image = Image.FromStream(new MemoryStream(binaryData));
3条回答
  •  不知归路
    2020-12-08 21:19

    In a situation I came across, I created a converter to handle the conversion of a Base64 string to WPF Image. So you can bind it to your base64 string property and let the converter handle the rest.

       public class ByteToImageConverter : IValueConverter
            {
                public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
                {
                    if(string.IsNullOrEmpty(value.ToString())return;
                    var imgBytes = Convert.FromBase64String(value.ToString());
                    if (imgBytes == null)
                        return null;
                    using (var stream = new MemoryStream(imgBytes))
                    {
                        return BitmapFrame.Create(stream,
                            BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    }
                }
    
                public object ConvertBack(object value, Type targetType, object parameter,
                    System.Globalization.CultureInfo culture)
                {
                    throw new NotImplementedException();
                }
            }
    

提交回复
热议问题