Visual Basic Code Snippet - Download Image from URL
(VB) Visual Basic code snippet download image from URL. This function download image using web response stream.
Bookmark:
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.
''' <summary> ''' Function to download Image from website ''' </summary> ''' <param name="_URL">URL address to download image</param> ''' <returns>Image</returns> Public Function DownloadImage(ByVal _URL As String) As Image Dim _tmpImage As Image = Nothing Try ' Open a connection Dim _HttpWebRequest As System.Net.HttpWebRequest = CType(System.Net.HttpWebRequest.Create(_URL), System.Net.HttpWebRequest) _HttpWebRequest.AllowWriteStreamBuffering = True ' You can also specify additional header values like the user agent or the referer: (Optional) _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)" _HttpWebRequest.Referer = "http://www.google.com/" ' set timeout for 20 seconds (Optional) _HttpWebRequest.Timeout = 20000 ' Request response: Dim _WebResponse As System.Net.WebResponse = _HttpWebRequest.GetResponse() ' Open data stream: Dim _WebStream As System.IO.Stream = _WebResponse.GetResponseStream() ' convert webstream to image _tmpImage = Image.FromStream(_WebStream) ' Cleanup _WebResponse.Close() _WebResponse.Close() Catch _Exception As Exception ' Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()) Return Nothing End Try Return _tmpImage 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.
' Download web image Dim _Image As Image = Nothing _Image = DownloadImage("http://www.youdomain.com/sample-image.jpg") ' check for valid image If _Image IsNot Nothing Then ' show image in picturebox pictureBox1.Image = _Image ' lets save image to disk _Image.Save("C:\\sample-image.jpg") End If
VB Keywords Used:
- HttpWebRequest
- WebResponse
- Image
- Stream
- StreamReader
- ExecuteReader
- Exception
Code Snippet Information:
- Applies To: .Net, VB, Visual Basic, CLI, HTML, HttpWebRequest, WebResponse, StreamReader, Data Mining, Download Image from URL
- Programming Language : Visual Basic (VB)
External Resources:
adarsh :: August 20-2010 :: 05:27 PM
Hi., i have been looking for this program for long time. I tried to copy paste that into console application but its showing an error on "Image" at public Image DownloadImage(String _url) and the error is "the type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?). I tried to google the error but no luck. Can you please help me with this issue. Thank you