[英]Convert System.Drawing.Bitmap to System.Windows.Media.BitmapImage for WPF
I am receiving a bitmap as a string encoded in Base64. 我收到的位图是用Base64编码的字符串。 I am successfully turning this into a System.Drawing.Bitmap and displaying it on a test winforms in a picture box. 我成功地将其转换为System.Drawing.Bitmap并将其显示在图片框中的测试Winforms上。 Image shows without issues. 该图显示没有问题。
However when i try and convert it to an BitmapImage i get a 但是,当我尝试将其转换为BitmapImage时,我得到了
Metadata = 'image.Metadata' threw an exception of type 'System.NotSupportedException' 元数据='image.Metadata'引发了类型'System.NotSupportedException'的异常
Below is the code im using to do the initial conversion and the conversion to a BitmapImage. 下面是代码im用于执行初始转换和转换为BitmapImage。 The BitmapImage is required to pass to another method which requires an System.Windows.Media.ImageSource. 需要BitmapImage传递给另一个需要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 编辑:我还应该提到即时通讯试图使用.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. 与BitmapImage
, BitmapFrame
支持Metadata
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.