0

If I did this in my MAUI project:

var uploadImage = new UploadImage();
var img = await uploadImage.OpenMediaPickerAsync();

var imagefile = await uploadImage.Upload(img);
var imageBytes = uploadImage.StringToByteBase64(imagefile.byteBase64);
var stream = uploadImage.ByteArrayToStream(imageBytes);

img_profilePic.Source = ImageSource.FromStream(() => stream); //working

I am displaying an image from my ios simulator. At one point in time I have the stream of the IO at my displosal.

If I now add

MemoryStream newStream = new MemoryStream();
stream.CopyTo(newStream);

these two lines of code to my code above, the image I was displaying at that point dissapears. SO somehow, when I copy my stream, I for some reason also delete the already existing stream...?

What is going on here...

Florian
  • 1,019
  • 6
  • 22
inno
  • 376
  • 2
  • 15

2 Answers2

0

SO somehow, when I copy my stream, I for some reason also delete the already existing stream...?

It's far more likely that you're trying to use the same stream as multiple sources without rewinding it. Streams have a position that increases as you use it.

In short, use this when you want to reuse your stream:

stream.Position = 0;

Assuming, of course, that whatever stream you're using is rewindable in the first place. If not, then copy it to a memory stream first and reuse that as many times as you wish, rewinding between uses.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

The point of streams is to be able to process very large amounts of data (sequentially) without having to load all that data into memory (at once anyway), which is what happens if instead of streams you work with collections. So, what stream do is track the current position so they can keep loading more data to memory when the position moves forward and unload already processed data. So, using the same stream for two things it's not going to work because the second usage won't get the data that the first usage has already consumed.

That said, it's possible to reset the position of a stream with the seek operation (as long as the type of stream you are using allows it).

Check out this answer https://stackoverflow.com/a/1746108/352826

Francesc Castells
  • 2,692
  • 21
  • 25
  • thank you. I understood. I have a follow up question: If I now do this: img_profilePic.Source = ImageSource.FromStream(() => stream); and go though my code with breakpoints. I can see that even though I set the stream to a source, it is still at position 0. Why isnt it after putting it to the source at the final position? – inno Dec 22 '22 at 15:56
  • 1
    I don't know the inner workings of ImageSource.FromStream, but my guess is that the stream is not used when FromStream is executed. This will just create the ImageSource with a reference to the Func which will be invoked later on. So, when debugging, it's not going to consume the stream, unless you keep debugging and the image needs to be rendered. – Francesc Castells Dec 22 '22 at 16:06