Download Image from Web to File Using VB.Net

Hi to all,

I want to be able to download an image from the web and save it locally to a file in a winforms application. How would I do that using VB.Net?

Thanks
ALawrence007Asked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Haven't looked...but this is probably similar to emoreau's approach:
Imports System.IO
Imports System.Net
Public Class Form1
 
    Private WithEvents bgw As New System.ComponentModel.BackgroundWorker
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim puppyURL As String = "http://www.shooterdog.com/puppy.jpg"
        bgw.RunWorkerAsync(puppyURL)
    End Sub
 
    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Dim url As String = e.Argument
        Dim img As Image = GetWebImage(url)
        e.Result = img
    End Sub
 
    Private Function GetWebImage(ByVal URL As String) As Image
        Try
            Dim wReq As WebRequest = WebRequest.Create(URL)
            If Not IsNothing(wReq) Then
                Dim wRes As WebResponse = wReq.GetResponse
                If Not IsNothing(wRes) Then
                    Dim wStrm As Stream = wRes.GetResponseStream
                    If Not IsNothing(wStrm) Then
                        Return Image.FromStream(wStrm)
                    End If
                End If
            End If
        Catch ex As Exception
        End Try
        Return Nothing
    End Function
 
    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
        Dim img As Image = e.Result
        If Not IsNothing(img) Then
            PictureBox1.Image = img
 
            ' if you want to save it:
            img.Save(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
        Else
            MessageBox.Show("Failed to get image...")
        End If
    End Sub
 
End Class

Open in new window

0
 
technofileCommented:
What information do you have?
0
 
ALawrence007Author Commented:
Thanks Guys!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.