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);
        }

2 comments:

Skill Zero said...

I was more than happy to uncover this great site. I need to to thank you for your time due to this fantastic read!! I definitely enjoyed every bit of it and I have you bookmarked to see new information on your blog.

https://durgapujawish.com/makar-sankranti-2018-images-wallpapers-makar-sankranti-greetings-in-hindi/

Skill Zero said...

I was more than happy to uncover this great site. I need to to thank you for your time due to this fantastic read!! I definitely enjoyed every bit of it and I have you bookmarked to see new information on your blog.

http://bit.ly/2m7eKyl

Post a Comment