Image From URL

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

Visual Basic Code Snippet - Download Image from URL

This .Net Visual Basic code snippet download image from URL. To use this function
simply provide the URL of the image you like to download. This function read the
image contents using URL and returns downloaded image as an image object. This
function download image using web response stream.

01
''' <summary>
02
''' Function to download Image from website
03
''' </summary>
04
''' <param name="_URL">URL address to download image</param>
05
''' <returns>Image</returns>
06
Public Function DownloadImage(ByVal _URL As String) As Image
07
Dim _tmpImage As Image = Nothing
08

09
Try
10
' Open a connection
11
Dim _HttpWebRequest As System.Net.HttpWebRequest =
CType(System.Net.HttpWebRequest.Create(_URL), System.Net.HttpWebRequest)
12

13
_HttpWebRequest.AllowWriteStreamBuffering = True
14

15
' You can also specify additional header values like the user agent or the
referer: (Optional)
16
_HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT
5.1)"
17
_HttpWebRequest.Referer = "http://www.google.com/"
18

19
' set timeout for 20 seconds (Optional)
20
_HttpWebRequest.Timeout = 20000
21

22
' Request response:
23
Dim _WebResponse As System.Net.WebResponse = _HttpWebRequest.GetResponse()
24

25
' Open data stream:
26
Dim _WebStream As System.IO.Stream = _WebResponse.GetResponseStream()
27

28
' convert webstream to image
29
_tmpImage = Image.FromStream(_WebStream)
30

31
' Cleanup
32
_WebResponse.Close()
33
_WebResponse.Close()
34
Catch _Exception As Exception
35
' Error
36
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString())
37
Return Nothing
38
End Try
39

40
Return _tmpImage
41
End Function

Here is a simple example showing how to use above function (DownloadImage) to


download image and show it in a PictureBox and how to save it on a local disk.

01
' Download web image
02
Dim _Image As Image = Nothing
03
_Image = DownloadImage("http://www.youdomain.com/sample-image.jpg")
04

05
' check for valid image
06
If _Image IsNot Nothing Then
07
' show image in picturebox
08
pictureBox1.Image = _Image
09

10
' lets save image to disk
11
_Image.Save("C:\\sample-image.jpg")
12
End If

You might also like