我收到的是以 Base64 编码的字符串形式的位图。我成功地将其转换为 System.Drawing.Bitmap 并将其显示在图片框中的测试 winform 上。图片显示没有问题。
但是,当我尝试将其转换为 BitmapImage 时,我得到了
Metadata = 'image.Metadata' threw an exception of type 'System.NotSupportedException'
下面是我用来进行初始转换和转换为 BitmapImage 的代码。 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;
}
}
编辑:我还应该提到我正在尝试使用 .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
属性。
关于c# - 将 System.Drawing.Bitmap 转换为 WPF 的 System.Windows.Media.BitmapImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29767636/