Dynamically loading image from the web [C#]
A common scenario for a web-based developer is the following: your client-side application within the browser (either Javascript or Flash application) needs to reach across the web and pull an image from another domain. But the sandbox security model within the browser will almost always stop your client-side application from doing the cross-domain request. So what do you do?
The easiest (and best) solution is to create a server-side page on your own server or website which takes a URL and loads the image (or other file) for you and returns it in the response. Most hosting scenarios will allow these kinds of requests across the Internet. A bonus is that you can do some caching or other processing on the server before returning to the client - for example, adding a watermark or standardizing the image size.
I am building an application which does exactly this, getting thumbnails of websites from a remote site. I load the image by passing the URL to an ASPX page:
http://server/LoadImage.aspx?url={URL}
where {URL} is the (encoded) web address of the image.
Below is the C# code I use to implement.
using System;
using System.Data;
using System.Net;
using System.Text;
using System.IO;
public partial class LoadImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((Request.QueryString[”url”] != null) && (Request.QueryString[”url”] != “”))
{
string url = Request.QueryString[”url”].ToString();
byte[] _data;
_data = this.LoadThumbshotFromWeb(url);
Response.ContentType = “image/jpeg”;
Response.BinaryWrite(_data);
}
}
// load image
protected byte[] LoadThumbshotFromWeb(string url)
{
// create a request for the URL
string _url = url;
WebRequest wr = WebRequest.Create(_url);
// if required by the server, set the credentials.
wr.Credentials = CredentialCache.DefaultCredentials;
byte[] result;
byte[] buffer = new byte[4096];
// get the response and buffer
using (WebResponse response = wr.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
int count = 0;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
} while (count != 0);
result = memoryStream.ToArray();
}
}
}
return result;
}
}
