views:

25

answers:

1

Could anyone tell me how I could retrieve an image or a thumbnail of a website through my ASP.NET application? I have seen this functionality in a few sites such as Alexa etc.

+1  A: 

Try SnapCasa's free and easy to use service. Just form your image tag like this:

<img src="http://SnapCasa.com/Get.aspx?code=[code]&amp;size=[size]&amp;url=[url]" />

Requires sign-up, but it's free for 500,000 requests a month. [code] is an api key that they provide after sign-up. [size] is one of three sizes available. [url] is the website address to the site for which you want to display a thumbnail.

If you want to work with the image from your code, here are a couple of helper methods:

static public byte[] GetBytesFromUrl(string url)
{
    byte[] b;
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
    WebResponse myResp = myReq.GetResponse();

    Stream stream = myResp.GetResponseStream();
    //int i;
    using (BinaryReader br = new BinaryReader(stream))
    {
        //i = (int)(stream.Length);
        b = br.ReadBytes(500000);
        br.Close();
    }
    myResp.Close();
    return b;
}

static public void WriteBytesToFile(string fileName, byte[] content)
{
    FileStream fs = new FileStream(fileName, FileMode.Create);
    BinaryWriter w = new BinaryWriter(fs);
    try
    {
        w.Write(content);
    }
    finally
    {
        fs.Close();
        w.Close();
    }
}

Then, in your code, just use:

//get byte array for image
var imageBytes = GetBytesFromUrl("http://SnapCasa.com/Get.aspx?code=[code]&amp;size=[size]&amp;url=[url]");
//save file to disk
WriteBytesToFile("c:\someImageFile.jpg", imageBytes);
Byron Sommardahl