'Xamarin Image data is invalid on a stream copy

In the first case the code works fine. In the second case I get:

ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource

So, case A (works fine):

Stream stream = await DependencyService.Get<IPicturePicker>().GetGalleryStreamAsync();
image.Source = ImageSource.FromStream(() => stream);

Case B (error):

MemoryStream memoryStream = new MemoryStream();
Stream stream = await DependencyService.Get<IPicturePicker>().GetGalleryStreamAsync();
stream.CopyTo(memoryStream);
image.Source = ImageSource.FromStream(() => memoryStream);

Please help!



Solution 1:[1]

Try this on the last line

 Imgsrc= ImageSource.FromStream(() => new MemoryStream(memorystream));

Solution 2:[2]

I believe your problem stems from the line stream.CopyTo(memoryStream);

The effect of this statement is to put the 'position' of the stream reader pointer at the end of the image stream.

If you follow this CopyTo statement with a 'stream.Position = 0;' then I believe all will be fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SteveD430