160

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);
Cœur
  • 34,719
  • 24
  • 185
  • 251
frosty
  • 5,274
  • 18
  • 83
  • 122
  • how are we posting the file in another .aspx page? – shivi Jun 23 '15 at 01:42
  • 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 Jun 20 '17 at 06:00

6 Answers6

306

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);
}
Robert MacLean
  • 38,615
  • 24
  • 98
  • 151
Wolfwyrd
  • 15,402
  • 5
  • 44
  • 67
  • 1
    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 Dec 17 '09 at 04:13
  • Remember to close the BinaryReader. – Chris Jun 01 '10 at 17:00
  • Work like a charm. Thank you for this simple solution (with the comments of jeff, Spongeboy and Chris)! – David Jun 09 '10 at 14:59
  • 32
    Binary reader doesn't have to be closed, because there is a using that is automaticaly closing the reader on disposal – BeardinaSuit Oct 28 '11 at 13:14
  • 1
    Any idea on why this wouldn't work for a .docx file? http://stackoverflow.com/questions/19232932/how-do-i-get-a-byte-array-from-httpinputstream-for-a-docx-file – wilsjd Oct 07 '13 at 19:42
  • Worked on my end. Thanks! – Rejwanul Reja Jun 01 '20 at 07:02
27
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);
Andre Figueiredo
  • 11,944
  • 7
  • 45
  • 70
15

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;
tinamou
  • 2,272
  • 3
  • 24
  • 28
3

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

ImageElement image = ImageElement.FromBinary(buffer);
devio
  • 36,179
  • 7
  • 78
  • 140
2

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

lpapp
  • 48,739
  • 39
  • 106
  • 133
xpfans
  • 81
  • 3
2

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();
Jodda
  • 25
  • 4