Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Related Posts
Laziness .NET -- the Professional Edition
Some new MSDN links of note
Visual Basic Resource Kit
Visual Basic Resource Kit Download Avail...
URLScan and the VB Resource Kit

Reading An Image from the web...

Posted on November 17th

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( _
        "http://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])


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Greate work. thanks for shearing

I got an error of: "System.Net.Sockets.SocketException: An invalid argument was supplied"

May i know how can i solve it?