![](/img/trans.png)
[英]Convert System.Windows.Media.ImageSource to System.Drawing.Bitmap
[英]Convert System.Drawing.Bitmap to System.Windows.Media.BitmapImage for WPF
我收到的位圖是用Base64編碼的字符串。 我成功地將其轉換為System.Drawing.Bitmap並將其顯示在圖片框中的測試Winforms上。 該圖顯示沒有問題。
但是,當我嘗試將其轉換為BitmapImage時,我得到了
元數據='image.Metadata'引發了類型'System.NotSupportedException'的異常
下面是代碼im用於執行初始轉換和轉換為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
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.