title: Deserialize very large image file
body: <p>I am receiving my imageset from a WebAPI as a list of ImageData objects each containing a bytearray.</p>
  
  <pre><code>    public class ImageData
      {
          public byte[] data;
      }
  </code></pre>
  
  <p>When I have many small size images, I can receive the API response and deserialize it using JObject without any issues. Below works perfectly.</p>
  
  <pre><code>using (var sr = new StreamReader(stream))
  using (var jr = new JsonTextReader(sr))
  {
  
   while (jr.Read())
   {
       if (jr.TokenType == JsonToken.StartObject)
       {
          imageData = JObject.Load(jr).ToObject&lt;ImageData&gt;();
       }
   }
  
  }
  </code></pre>
  
  <p>However, sometimes I have a single very large image file ( more than 200MB). In this case, regular deserializing method does not work. I keep getting OutOfMemory exceptions. </p>
  
  <p>I tried reading the response in buffers and getting the bytearray but the end size of all read bytes is always bigger than the actual image size. If the original image size is around 220MB, what I end up with is around 295MB, I believe due to encoding. So the image can never be properly written.
  Below is how I do buffered reading.</p>
  
  <pre><code>byte[] buffer = new byte[1024];
  List&lt;byte[]&gt; imageBytes = new List&lt;byte[]&gt;();
  
  while (true)
  {
      int read = stream.Read(buffer, 0, buffer.Length);
      if (read &lt;= 0)
          break;  
      imageBytes.Add(buffer);
  }
  
  var output = new byte[imageBytes.Sum(arr =&gt; arr.Length)];
  int writeIdx = 0;
  foreach (var byteArr in imageBytes)
  {
      byteArr.CopyTo(output, writeIdx);
      writeIdx += byteArr.Length;
  }
  
  imageData = new ImageData() { data = output };
  </code></pre>
  
  <p>What am I missing here? How can I accomplish getting the image data from this huge payload without memory exceptions or extra bytes?</p>
  
  <p>---- Update ---</p>
  
  <p>I tried with below, but still larger number of bytes than the original.</p>
  
  <pre><code>while (true)
  {
      read = await stream.ReadAsync(buffer, 0, 1024);
      ++count;
      if (read &lt;= 0)
  
      bytesRead += read;
      ms.Write(buffer, 0, read);
  }
  
  imageData = new ImageData() { data = ms.ToArray() };
  </code></pre>
  
  <p>Tried using a FileStream, temp.dcm size is again about 290MB, while original image is about 210MB:</p>
  
  <pre><code>string file = @"C:\Test\\temp.dcm";
  using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write,
              FileShare.None, 4096, useAsync: true))
  {
      await response.Content.CopyToAsync(fs);
  }
  </code></pre>