How to stream image file on web page


Apr 17, 2008
Programming Experience

I'm looking for a way to display a 'png' file from a local drive to a web page.

I have this streaming method, reading image file is not an issue, but it just won't display it.

Any advice? Thanks.

Public Function ConvertToByteArray(ByVal value As Bitmap) As Byte()
        Dim bitmapBytes As Byte()

        Using stream As New System.IO.MemoryStream

            value.Save(stream, System.Drawing.Imaging.ImageFormat.Png)
            bitmapBytes = stream.ToArray

        End Using

        Return bitmapBytes

    End Function
    Private Sub displayMap()

        Dim oBmp As Bitmap
        oBmp = New Bitmap(m_strAppPath & "\" & m_LotNo & "_" & m_SlotNo & "_" & m_Surface & IMAGE_TYPE)

        Dim bitmapBytes As Byte() = ConvertToByteArray(oBmp)

        Response.ContentType = "image/png"

        Response.OutputStream.Write(bitmapBytes, 0, bitmapBytes.Length)

    End Sub
For the record, you can get a Byte array from a file by calling File.ReadAllBytes. There's no need to go through Bitmap and MemoryStream objects. You don't actually need to create a Byte array anyway. If you open a FileStream, you can call CopyTo to copy its contents directly to another Stream.
You can also build your file path in a more readable and less error-prone way:
Dim filePath = IO.Path.Combine(m_strAppPath, $"{m_LotNo}_{m_SlotNo}_{m_Surface}{IMAGE_TYPE}")

One reason I'm using the memory stream is because this page will be rendered in another application, and from what I know, it could only support binary stream. So I have to make to conversion.
it could only support binary stream. So I have to make to conversion.
What do you think a FileStream is? They are both basically the same thing from the outside - they both inherit Stream - but one is backed by memory and the other is backed by a file. What you need is a source of Bytes to write to Response.OutputStream. You're currently using a Byte array but how you get that is irrelevant to how you use it. File.ReadAllBytes will produce the same Byte array in a far less convoluted and more efficient fashion, i.e. it's one method call and you're not storing the same data twice. FileStream.CopyTo will do the writing for you without your having to create a Byte array yourself. It will be more efficient because it will write the data in chunks and thus use less memory than reading the entire data into an array and then writing it all in one go.