-1

We have a code snippet that is converting Stream to byte[] and later displaying that as an image in aspx page.

Problem is when first time page loads image is being displayed, but not displaying for later requests (reload etc).

Only difference I observed is Stream position in 'input' (ConvertStreamtoByteArray) is 0 for the first time and subsequent calls is > 0. How do I fix this?

context.Response.Clear();
context.Response.ContentType = "image/pjpeg";
context.Response.BinaryWrite(ConvertStreamtoByteArray(imgStream));
context.Response.End();

private static byte[] ConvertStreamtoByteArray(Stream input)
{
    var buffer = new byte[16 * 1024];
    using (var ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

I think the source is : Creating a byte array from a stream I think the code snippet is from above link, I see everything matches except for method name.

Community
  • 1
  • 1
CoolArchTek
  • 3,729
  • 12
  • 47
  • 76

1 Answers1

0

You're (most likely) holding a reference to imgStream, so the same stream is being used every time ConvertStreamtoByteArray is called.

The problem is that streams track their Position. This starts at 0 when the stream is new, and ends up at the end when you read the entire stream.

Usually the solution in this case is to set the Position back to 0 prior to copying the content of the stream.

In your case, you should probably 1) convert imgStream to a byte array the first time it's needed 2) cache this byte array and not the stream 3) dispose and throw away imgStream and 4) pass the byte array to the Response from this point onwards.

See, this is what happens when you copypasta code from the internets. Weird stuff like this, repeatedly converting the same stream to a byte array (waste of time!), and you end up not using the framework to do your work for you. Manually copying streams is so 2000s.

  • This was not my code and I am just trying to fix a bug. But I do copy the code from internet sometimes. I must admit that! – CoolArchTek Jun 03 '15 at 18:16