tags:

views:

3217

answers:

3

Hi I'm using an image component that has a FromBinary method. Wondering how do i convert my input stream into a byte array

HttpPostedFile file = context.Request.Files[0];
                    byte[] buffer = new byte[file.ContentLength];
                    file.InputStream.Read(buffer, 0, file.ContentLength);

ImageElement image = ImageElement.FromBinary(byteArray);
+7  A: 

Use a BinaryReader object to return a byte array from the stream like:

BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
Wolfwyrd
As mentioned below by jeff, b.ReadBytes(file.InputStream.Length); should be byte[] binData = b.ReadBytes(file.ContentLength);as .Length is a long whereas ReadBytes expects an int.
Spongeboy
Remember to close the BinaryReader.
Chris Dwyer
Work like a charm. Thank you for this simple solution (with the comments of jeff, Spongeboy and Chris)!
David
+1  A: 

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);
devio
+4  A: 
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);