tags:

views:

353

answers:

2

How do I progromatically save an image from a URL? I am using C# and need to be able grab images from a URL and store them locally. ...and no, I am not stealing :)

+4  A: 

You just need to make a basic http request using HttpWebRequest for the URI of the image then grab the resulting byte stream then save that stream to a file.

Here is an example on how to do this...

'As a side note if the image is very large you may want to break up br.ReadBytes(500000) into a loop and grab n bytes at a time writing each batch of bytes as you retrieve them.'

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ImageDownloader
{
    class Program
    {
        static void Main(string[] args)
        {
            string imageUrl = @"http://www.somedomain.com/image.jpg";
            string saveLocation = @"C:\someImage.jpg";

            byte[] imageBytes;
            HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
            WebResponse imageResponse = imageRequest.GetResponse();

            Stream responseStream = imageResponse.GetResponseStream();

            using (BinaryReader br = new BinaryReader(responseStream ))
            {
                imageBytes = br.ReadBytes(500000);
                br.Close();
            }
            responseStream.Close();
            imageResponse.Close();

            FileStream fs = new FileStream(saveLocation, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(imageBytes);
            }
            finally
            {
                fs.Close();
                bw.Close();
            }
        }
    }
}
William Edmondson
You might as well loop until the end of the stream instead of br.ReadBytes(500000);
nos
Yeah. I agree. I have added a note to that affect. Good call.
William Edmondson
This one is especially good for me - I don't need the physical file, just the stream, so it's much better than the accepted answer, in my case.
MGOwen
+6  A: 

It would be easier to write something like this:

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);
Alex
Heh...but doesn't more lines of code mean you are smarter?
William Edmondson
Nope:) Everything should be made as simple as possible, but not one bit simpler (after Albert Einstein).
Alex
Very cool. You guys are fast! Thanks.
Lexy