Saving Image from Image URL

Overview
Create image object and save it into file by URL.

Depending on your needs it can be two solutions:

Solution 1
when you need to make some manipulations with the image object (resize, crop, etc) before saving to disk:
1. get Stream from URL using WebRequest class
2. Create Image object from stream using System.Drawing.Image.FromStream method
3. Make manipulations with image object
3. Save image to file on disk using System.Drawing.Image.Save method

using System.Net;
using System.IO;

public bool getImageByUrl(string url, string filename)
{

WebResponse response = null;
Stream remoteStream = null;
StreamReader readStream = null;
try
{
WebRequest request = WebRequest.Create(url);
if (request != null)
{
response = request.GetResponse();
if (response != null)
{
remoteStream = response.GetResponseStream();

readStream = new StreamReader(remoteStream);

System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);

if (img == null)
return false;

// YOUR CODE HERE: make manipulations with the image object


// save image to disk
img.Save( filename, System.Drawing.Imaging.ImageFormat.Jpeg );
img.Dispose();
}
}
}
finally
{
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (readStream != null) readStream.Close();
}

return true;
}

Solution 2
when you need to get image from Url and just save it to disk as-is.
1. get Stream from URL using WebRequest class
2. Create new file and stream for it
3. Get data from Webrequest’s stream in binary format and put this data into file stream.

public static bool saveImageByUrlToDisk(string url, string filename, out string imageType)
{
imageType = "";

WebResponse response = null;
Stream remoteStream = null;
StreamReader readStream = null;
try
{
WebRequest request = WebRequest.Create(url);
if (request != null)
{
response = request.GetResponse();
if (response != null)
{
remoteStream = response.GetResponseStream();


// analyze image type, image extension
string content_type = response.Headers["Content-type"];

imageType = content_type;

if (content_type == "image/jpeg" || content_type == "image/jpg")
{
imageType = "jpg";
}
else if (content_type == "image/png")
{
imageType = "png";
}
else if (content_type == "image/gif")
{
imageType = "gif";
}
else
{
imageType = "";

return false;
}


readStream = new StreamReader(remoteStream);

Stream fw = File.Open(filename, FileMode.Create);

//
byte[] buf = new byte[256];
int count = remoteStream.Read(buf, 0, 256);
while (count > 0)
{
fw.Write(buf, 0, count);

count = remoteStream.Read(buf, 0, 256);
}

fw.Close();
}
}
}
finally
{
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
}

return true;
} 
SiteLock