C# 将System.Drawing.Bitmap转换为WPF的System.Windows.Media.BitmapImage
我正在接收一个位图,它是用Base64编码的字符串。我正在成功地将其转换为System.Drawing.Bitmap,并将其显示在测试winforms的图片框中。图像显示没有问题 但是,当我尝试将其转换为位图图像时,我得到一个 Metadata='image.Metadata'引发了类型为的异常 “System.NotSupportedException” 下面是我用来进行初始转换和位图图像转换的代码。需要将BitmapImage传递给另一个需要System.Windows.Media.ImageSource的方法C# 将System.Drawing.Bitmap转换为WPF的System.Windows.Media.BitmapImage,c#,wpf,bitmap,bitmapimage,imagesource,C#,Wpf,Bitmap,Bitmapimage,Imagesource,我正在接收一个位图,它是用Base64编码的字符串。我正在成功地将其转换为System.Drawing.Bitmap,并将其显示在测试winforms的图片框中。图像显示没有问题 但是,当我尝试将其转换为位图图像时,我得到一个 Metadata='image.Metadata'引发了类型为的异常 “System.NotSupportedException” 下面是我用来进行初始转换和位图图像转换的代码。需要将BitmapImage传递给另一个需要System.Windows.Media.Imag
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;
}
}
编辑:我还应该提到我正在尝试使用.Net 3.5。你应该像这样解码位图:
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);
}
}
与
BitmapImage
不同,BitmapFrame
支持Metadata
属性。您的第一个选项是我已经在做的,这失败了,但是您使用BitmapFrame的第二个选项工作得非常好。谢谢