Friday, September 16, 2011

Save image from URL

Soon as I needed to save image from different URLs again, I recalled how many times i have previously done this, So this time pasting it on the blog so it will help not only me but some viewers too


'MyImage is System.Drawing.Image type variable
  MyImage = GetImage(ImageURL)
  If Not IsNothing(MyImage) Then
       ImagePath = RetreivedImagesPath + ValidFileName(PartNo) + ".jpg"
       MyImage.Save(ImagePath)
  Else
       ImagePath = "File Not Found"
  End If


Definition of GetImage() Function in VB


'Function to return an image taking URL as input
 Function GetImage(ByVal URL As String) As System.Drawing.Image
        Dim Request As HttpWebRequest
        Dim Response As HttpWebResponse
        Try
            Request = WebRequest.Create(URL)
            Response = CType(Request.GetResponse, System.Net.WebResponse)
            If Request.HaveResponse Then
                If Response.StatusCode = Net.HttpStatusCode.OK Then
                    GetImage = System.Drawing.Image.FromStream(Response.GetResponseStream)
                End If
            End If
            Thread.Sleep(5000)
        Catch ex As Exception
            GetImage = Nothing
        End Try
    End Function

Function for Valid File Name



Below is a VB function to return a valid file name,


  Protected Function ValidFileName(ByVal FileName As String) As String
        Dim rgPattern as String = "[\\\/:\*\?""'<>|]"
        Dim objRegEx As New Regex(rgPattern)
        Return objRegEx.Replace(FileName, "-")
  End Function