Share via


Reading An Image from the web...

Nothing amazingly difficult about this task, but it was an interesting GotDotNet question posted today so I thought I would answer it here;

Glenn Holden asks how to turn this file based function into one for images stored at http addresses...

Protected Shared Function GetImageFromFile(ByVal FileName As String) As Byte()

    Dim myFile As String = FileName

    Dim fs As FileStream = New FileStream(myFile, FileMode.Open, FileAccess.Read)

    Dim br As BinaryReader = New BinaryReader(fs)

    Dim bytesize As Long = fs.Length

    ReDim GetImageFromFile(bytesize)

    GetImageFromFile = br.ReadBytes(bytesize)

End Function

So, I produced this;

Function GetImageFromURL(ByVal url As String) As Byte()

    Dim wr As HttpWebRequest = _

       DirectCast(WebRequest.Create(url), HttpWebRequest)

    Dim wresponse As HttpWebResponse = _

       DirectCast(wr.GetResponse, HttpWebResponse)

    Dim responseStream As Stream = wresponse.GetResponseStream

    Dim br As BinaryReader = New BinaryReader(responseStream)

    Dim bytesize As Long = wresponse.ContentLength

    Return br.ReadBytes(bytesize)

End Function

with a bit of test code thrown into a button.....

Private Sub Button1_Click(ByVal sender As System.Object, _

    ByVal e As System.EventArgs) Handles Button1.Click

    Dim img As New Bitmap( _

       New IO.MemoryStream( _

        GetImageFromURL( _

        "msdn.microsoft.com/longhorn/art/codenameLonghorn.JPG") _

        ))

    Me.BackgroundImage = img

End Sub

A generalized solution that will accept file paths or URIs and automatically determine how to retrieve the stream would likely be useful, but I think this will do for Glenn...

Markup provided by Darren Neimke's cool markup sample from MSDN

(Listening To: Pets [Porno For Pyros / Big Shiny 90's])