简体   繁体   中英

Convert System.Drawing.Bitmap to System.Windows.Media.BitmapImage for WPF

I am receiving a bitmap as a string encoded in Base64. I am successfully turning this into a System.Drawing.Bitmap and displaying it on a test winforms in a picture box. Image shows without issues.

However when i try and convert it to an BitmapImage i get a

Metadata = 'image.Metadata' threw an exception of type 'System.NotSupportedException'

Below is the code im using to do the initial conversion and the conversion to a BitmapImage. The BitmapImage is required to pass to another method which requires an System.Windows.Media.ImageSource.

using (MemoryStream BitmapMS = new MemoryStream(Convert.FromBase64String(base64str)))
{                    
    Bitmap bitmap = new Bitmap(BitmapMS);                    
    TestForm test = new TestForm();
    test.pictureBox1.Image = bitmap;
    test.ShowDialog();

    using (MemoryStream BitmapImageMS = new MemoryStream())
    {
        bitmap.Save(BitmapImageMS, ImageFormat.Jpeg);
        BitmapImageMS.Position = 0;
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.StreamSource = BitmapImageMS;
        image.EndInit();
        return image;
    }
}

Edit: I should also mention im trying to use .Net 3.5

You should decode the bitmap like this:

public static BitmapSource BitmapFromBase64(string base64String)
{
    var bytes = Convert.FromBase64String(base64String);

    using (var stream = new MemoryStream(bytes))
    {
        return BitmapFrame.Create(stream,
            BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}

In contrast to BitmapImage , BitmapFrame supports the Metadata property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM