159
votes

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);
6
how are we posting the file in another .aspx page? - shivi
Doesn't this line file.InputStream.Read(buffer, 0, file.ContentLength); fill the buffer with bytes from the input stream? Why should we use BinaryReader.ReadBytes(...) as mentioned by @Wolfwyrd in the answer below? Won't ImageElement.FromBinary(buffer); fix the problem? - Srinidhi Shankar

6 Answers

303
votes

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

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
26
votes
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

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

It won't work if your file InputStream.Position is set to the end of the stream. My additional lines:

Stream stream = file.InputStream;
stream.Position = 0;
3
votes

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

ImageElement image = ImageElement.FromBinary(buffer);
2
votes

before stream.copyto, you must reset stream.position to 0; then it works fine.

2
votes

For images if your using Web Pages v2 use the WebImage Class

var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();