2017-08-29 200 views
1

我想通過使用下面的代碼將MemoryStream轉換爲圖像。如何將流轉換爲BitmapImage?

Stream stream = new MemoryStream(bytes); 
    BitmapImage bitmapImage = new BitmapImage(); 
    await bitmapImage.SetSourceAsync(stream.AsRandomAccessStream()); 

但將在SetSourceAsync方法一個異常,異常是

System.Exception的是由用戶代碼 的HResult = -2003292336 消息未處理=該組件無法找到。在 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任務 任務) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificat 離子(任務的任務) :(從HRESULT異常: 0x88982F50) 源= mscorlib程序 堆棧跟蹤System.Runtime.CompilerServices.TaskAwaiter.GetResult() 在ImageEditor_UWP.MainPage.d__1.MoveNext()的InnerException:

我怎麼能轉換成一個流的圖像?

+0

使用try/catch塊 – Akshay

+0

你能分享你的源代碼?我複製了你的代碼,並且運行良好https://github.com/haison8x/sample-uwp-bitmapimage –

回答

2

圖像:

public async static System.Threading.Tasks.Task<BitmapImage> ImageFromBytes(byte[] bytes) 
{ 
    var image = new BitmapImage(); 

    try 
    { 
     var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); 
     await stream.WriteAsync(bytes.AsBuffer()); 
     stream.Seek(0); 
     await image.SetSourceAsync(stream); 
    } 
    catch (Exception ex) 
    { 
     System.Diagnostics.Debug.WriteLine(ex.Message); 
    } 

    return image; 
} 
+0

感謝您的代碼。 – Santhiya

+1

BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream); image.Source = bitmap;這也適用於我。 – Santhiya

-1

試試這個

var img = Bitmap.FromStream(stream); 
+0

目前在UWP窗口中不存在「Bitmap」類10 – Tcraft

+0

這並不能解答問題。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/17172764) –

+0

這是WinForms,而問題是關於UWP。 – Clemens

相關問題