Manipulating and Saving Images Locally from a Remote Server
It has come up a few times. Say you want to be able to allow someone to edit content using a rich text editor and allow them to upload images. Well, often you will find that they are linking images from other servers and the images are not formatted or sized appropriately for your application.
Here is a working example of a simple call to get an image from a remote server using a WebRequest, Manipulating the image and saving it to your server. Be warned that legal issues may arise if you do not have rights to use the image on your site.
For this example, I am using a picture of my dog found at my main site.
To keep this example simple, I am not manipulating or resizing the image. This would be easy to extend to use with a rich text editor. Enjoy!
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://www.robbihun.com/images/albums/fs_128664251554700000eau.jpg";
System.Drawing.Image img = null;
try
{
img = GetImageByURL(url);
if (img != null)
{
//resize the image
//save it to the filesystem.
string filename = "Beau" + url.Substring(url.LastIndexOf("."));
img.Save(Server.MapPath("~\\images\\" + filename));
}
}
catch
{
lblErrorMessage.Text = "There was an error retrieving your file.";
}
}
private static System.Drawing.Image GetImageByURL(string url)
{
WebResponse response = null;
Stream serverStream = null;
System.Drawing.Image result = null;
try
{
WebRequest request = WebRequest.Create(url);
if (request != null)
{
response = request.GetResponse();
if (response != null)
{
serverStream = response.GetResponseStream();
return System.Drawing.Image.FromStream(serverStream);
}
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (response != null) response.Close();
if (serverStream != null) serverStream.Close();
}
return result;
}
Comments (0)