3

I am trying to convert MemoryStream to Image by using the following code.

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

but it throws an exception in the SetSourceAsync method and the exception is

System.Exception was unhandled by user code HResult=-2003292336 Message=The component cannot be found. (Exception from HRESULT: 0x88982F50) Source=mscorlib StackTrace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificat ion(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at ImageEditor_UWP.MainPage.d__1.MoveNext() InnerException:

How can I convert a stream to an image?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Santhiya
  • 191
  • 2
  • 14

2 Answers2

0

To image:

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;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • 2
    BitmapImage bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream); image.Source = bitmap; this is also working for me. – Santhiya Aug 29 '17 at 09:00
-1

try this

var img = Bitmap.FromStream(stream);
Krish
  • 376
  • 3
  • 14