如何将流转换为BitmapImage?

时间:2017-08-29 06:03:35

标签: c# uwp bitmapimage

我正在尝试使用以下代码将MemoryStream转换为Image。

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

但它在SetSourceAsync方法中引发异常,异常是

  

System.Exception未被用户代码处理         的HResult = -2003292336         消息=无法找到组件。 (HRESULT的例外情况:         0x88982F50)         来源= mscorlib程序         堆栈跟踪:         在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务         任务)         在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificat         离子(任务任务)         在System.Runtime.CompilerServices.TaskAwaiter.GetResult()         at ImageEditor_UWP.MainPage.d__1.MoveNext()InnerException:

如何将流转换为图像?

2 个答案:

答案 0 :(得分:0)

要成像:

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;
}

答案 1 :(得分:-1)

试试这个

var img = Bitmap.FromStream(stream);