Reputation: 10055
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
Upvotes: 2
Views: 3200
Reputation: 128061
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.
Upvotes: 3