Load bitmapImage from base64String

后端 未结 2 769
無奈伤痛
無奈伤痛 2021-01-14 05:31

How can I load a bitmapImage from base64String in windows 8?

I tried this but I am not successful. It used to work on windows

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 05:41

    Here conversion methods for both System.Drawing.Bitmap and System.Windows.Media.BitmapSource.

    Enjoy

    Remark: Not tested on Win8 but there is not reason why it should not work.

        string ToBase64(Bitmap bitmap)
        {
            if (bitmap == null)
                throw new ArgumentNullException("bitmap");
    
            using (var stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);
    
                return Convert.ToBase64String(stream.ToArray());
            }
        }
    
        string ToBase64(BitmapSource bitmapSource)
        {
            using (var stream = new MemoryStream())
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(stream);
                return Convert.ToBase64String(stream.ToArray());
            }
        }
    
        Bitmap FromBase64(string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
    
            using (var stream = new MemoryStream(Convert.FromBase64String(value)))
            {
                return (Bitmap)Image.FromStream(stream);
            }
        }
    
        BitmapSource BitmapSourceFromBase64(string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
    
            using (var stream = new MemoryStream(Convert.FromBase64String(value)))
            {
                var decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                BitmapSource result = decoder.Frames[0];
                result.Freeze();
                return result;
            }
        }
    

提交回复
热议问题