2017-08-29 91 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

相关问题