Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty Saving Image To MemoryStream

Tags:

I'm having some difficulty saving a stream of bytes from an image (in this case, a jpg) to a System.IO.MemoryStream object. The goal is to save the System.Drawing.Image to a MemoryStream, and then use the MemoryStream to write the image to an array of bytes (I ultimately need to insert it into a database). However, inspecting the variable data after the MemoryStream is closed shows that all of the bytes are zero... I'm pretty stumped and not sure where I'm doing wrong...

using (Image image = Image.FromFile(filename)) {     byte[] data;      using (MemoryStream m = new MemoryStream())     {         image.Save(m, image.RawFormat);         data = new byte[m.Length];         m.Write(data, 0, data.Length);     }      // Inspecting data here shows the array to be filled with zeros... } 

Any insights will be much appreciated!

like image 481
Andrew Avatar asked Oct 02 '11 23:10

Andrew


People also ask

How do you save on MemoryStream?

Save MemoryStream to a String Steps follows.. StreamWriter sw = new StreamWriter(memoryStream); sw. WriteLine("Your string to Memoery"); This string is currently saved in the StreamWriters buffer.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

Do I need to close MemoryStream?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .

How do I reuse MemoryStream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.


1 Answers

To load data from a stream into an array, you read, not write (and you would need to rewind). But, more simply in this case, ToArray():

using (MemoryStream m = new MemoryStream()) {     image.Save(m, image.RawFormat);     data = m.ToArray(); } 
like image 182
Marc Gravell Avatar answered Oct 04 '22 12:10

Marc Gravell