Wednesday, July 20, 2011

Download image url to file

Recently, in one of my personal projects, I wanted to provide an option to save (or download) a png image url to the disk. First, as most of us do, I Googled it and found lot of solutions. But I was not able to use any snippet readily without any modifications. May be no one has encountered this scenario (as you could easily use browse “save as” functionality for this). [Updated on July 21st - I found a very elegant solution here which I have also updated at the end of this post). In interest of others who might someday need this functionality, I am providing the code snippet that I used to achieve this.

public void saveAsFile(string link)
{
          /*Get the name of the image from the link by finding the last '/' */           
          string name = link.Split('/')[link.Split('/').Length - 1];

          /*save the file with the same name in the current base directory */
          string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);
           
          System.Net.WebRequest request = System.Net.WebRequest.Create(link);            
          System.Net.WebResponse response = request.GetResponse();
          System.IO.Stream stream = response.GetResponseStream();
           
          //convert the response stream into an image object.
          System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

//save the image to a file.
          image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);           
 }

Note that I have used ImageFormat.Png as my need is to save only PNG files. You need to change this format based  on what type of image (gif,bmp,etc) you want to save.

Happy coding!!

Updated on July 21st - Looks like I am not good in Googling. I found a very elegant solutions here. I have updated the code based on this:



       public void saveAsFile(string link)
       {
         /*Get the name of the image from the link by finding the last '/' */
          string name = link.Split('/')[link.Split('/').Length - 1];

          /*save the file with the same name in the current base directory */
          string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);

           System.Net.WebClient client = new System.Net.WebClient();
           client.DownloadFile(link, filePath);
        }

No comments:

Post a Comment