This post originated from an RSS feed registered with .NET Buzz
by Duncan Mackenzie.
Original Post: Reading An Image from the web...
Feed Title: Code/Tea/Etc...
Feed URL: /msdnerror.htm?aspxerrorpath=/duncanma/rss.aspx
Feed Description: Duncan is the Visual Basic Content Strategist at MSDN, the editor of the Visual Basic Developer Center (http://msdn.microsoft.com/vbasic), and the author of the "Coding 4 Fun" column on MSDN (http://msdn.microsoft.com/vbasic/using/columns/code4fun/default.aspx). While typically Visual Basic focused, his blogs sometimes wanders off of the technical path and into various musing of his troubled mind.
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...