Thursday, May 15, 2008

How to Get Image from Internet / How To Load Online Image into Image Class

Level: Intermediate

Knowledge Required:
  • WebClient Class
  • MemoryStream Class
  • Image Class

Description:
We have used Image class to create images. One of its Shared member is
Image.FromFile(filename)
Which we can use as,
Dim i As Image
i = Image.FromFile("C:\MyTest.Jpg")
This will create a New instance of Image Class with MyTest.Jpg Loaded. We can then use this image in different controls like PictureBox.

But this method does NOT support URI. For example we have an image at:

http://www.google.com/intl/en_ALL/images/logo.gif

We cannot use as,

Dim i As Image
i = Image.FromFile("http://www.google.com/intl/en_ALL/images/logo.gif")


This will through an exception. So to Load images (programitically) that are stored online we will use the following code,



Private Function GetOnlineImage(ByVal URL As String) As Image
Dim i As Image
Dim w As New Net.WebClient
Dim b() As Byte
Dim m As System.IO.MemoryStream

' download the Image Data in a Byte array
b = w.DownloadData(URL)

' create a memory stream from that Byte array
m = New System.IO.MemoryStream(b)
' now create an Image from Memory Stream
i = Image.FromStream(m)

' release the WebClient
w.Dispose()

' return image
Return i
End Function

' Usage
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Image
i = Me.GetOnlineImage("http://www.google.com/intl/en_ALL/images/logo.gif")
Me.PictureBox1.Image = i
End Sub


No comments: