question

AbrahamJohn-8020 avatar image
0 Votes"
AbrahamJohn-8020 asked ColeXia-MSFT answered

Stream can't be accessed more than once.

I'm using Ascetic.Plugins.Cropper inside my Xamarin project.

In MainViewModel page,

  public static byte[] imgbyte; 
  public MainViewModel(ICropper cropper)
     {
         CropCommand = new Command(async () =>
         {
             Stream cropped = await cropper.Crop();
             imgbyte = GetImageStreamAsBytes(cropped);
             ResultPhotoSource = ImageSource.FromStream(() => cropped);
         });
     }
    // Converting cropped image stream to bytes for later use
     public byte[] GetImageStreamAsBytes(Stream imgstream)
     {
         var buffer = new byte[16 * 1024];
         using (MemoryStream ms = new MemoryStream())
         {
             int read;
             while ((read = imgstream.Read(buffer, 0, buffer.Length)) > 0)
             {
                 ms.Write(buffer, 0, read);
             }
             return ms.ToArray();
         }
     }

The CropCommand is binded to the Command property of a button.

So the image stream is succesfully converted into bytes but ResultPhotoSource is null.

In my crop.xaml page I've added an Image tag:

 <Image x:Name="cropped_img" Source="{Binding ResultPhotoSource }"/>

But cropped_img displays nothing.

If I remove the line imgbyte = GetImageStreamAsBytes(cropped);, then ResultPhotoSource is binded to the Source of Image tag succesfully.

Why can't I access same stream more than once?

Help would be appreciated.


dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ColeXia-MSFT avatar image
0 Votes"
ColeXia-MSFT answered

Hello,

Welcome to Microsoft Q&A!

We can't access a closed Stream , to avoid this we can create a new MemoryStream and copy the original data to it .

Modify your code as below

public MainViewModel(ICropper cropper)
        {
            CropCommand = new Command(async () =>
            {
                Stream cropped = await cropper.Crop();
                

                using (var ms = new MemoryStream())
                {

                    cropped.CopyTo(ms);
                    imgbyte = ms.ToArray();

                    MemoryStream newM = new MemoryStream(imgbyte);  //add this line

                    ResultPhotoSource = ImageSource.FromStream(() => newM);
                }

            });
        }


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.