Monday, January 2, 2012

How to download image from a web site programatically using HttpWebRequest

I was working on adding new features to Car Pass application. The new feature will show some details about the car accident and one of the details is showing map image associated with car accident event. To get that, I have developed an image service that downloads the map images(Google Static Map see here) in the background. This is done using HttpWebRequest object to send request to image URL with parameter. Following code shows you how you can download an image from a Url programatically using HttpWebRequest.

Create .aspx page and put the following code in code-behind.
protected void Page_Load(object sender, EventArgs e)
{
    //Here should be your image url.
    String url = "http://maps.googleapis.com/maps/api/staticmap?center=huamark,bangkapi,th&zoom=15&size=500x500&scale=1&format=jpg&maptype=roadmap&language=en&markers=icon:http://www.iblogseeker.com/favicon.ico|13.758185,100.628732&sensor=false";

    HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
    HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse;
    if (resp.StatusCode == HttpStatusCode.OK)
    {
        if (resp.ContentType.Contains("image/"))
        {
            int pos = resp.ContentType.IndexOf("/");
            string fileName = string.Format("{0}.{1}", "Map", resp.ContentType.Substring(pos + 1));
            byte[] imageContent = ProcessImageStream(resp);

            MemoryStream ms = new MemoryStream(imageContent);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            string path = string.Format(@"G:\{0}", fileName);
            img.Save(path);

            //for image manipulation with third party component such as Telerik Reporting, Bitmap is better.
            //e.g. when you rotate image and put in Telerik Report as image.
            System.Drawing.Bitmap bmap= new Bitmap(ms);
            bmap.RotateFlip(RotateFlipType.Rotate90FlipXY);
            bmap.Save(string.Format(@"G:\B{0}", fileName));
        }
    }
}

Here is utility function called from Page_Load.
private static byte[] ProcessImageStream(HttpWebResponse resp)
{
    byte[] streamContent;
    MemoryStream memStream = new MemoryStream();
    const int BUFFER_SIZE = 4096;
    int iRead = 0;
    Int64 iSize = 0;
    memStream.SetLength(BUFFER_SIZE);
    try
    {
        using (memStream)
        {
            while (true)
            {
                iRead = 0;
                byte[] respBuffer = new byte[BUFFER_SIZE];
                iRead = resp.GetResponseStream().Read(respBuffer, 0, BUFFER_SIZE);
                if (iRead == 0)
                {
                    break;
                }
                iSize += iRead;
                memStream.SetLength(iSize);
                memStream.Write(respBuffer, 0, iRead);
            }
            streamContent = memStream.ToArray();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return streamContent;
}

When you run the application, it download image and save two images in drive G:.

No comments:

Post a Comment