Set Url of the Image you want to save on your system.
DestinationPath is the path where you want to save the image.
in this case it is Products folder on the root of the application folder.
strImage = url.Substring(url.LastIndexOf('/') + 1);
above line of code will give us the name of the image.
GetBytesFromUrl(url); method will return the Byte array of the image
for the corrsponding url of the image.
Once we got the Byte image data in the form of Byte array then
we can save the image using WriteBytesToFile method.
string url = "http://3.bp.blogspot.com/_Kp--fzJWFmc/
SNH1SzkEZoI/AAAAAAAAADU/W0bjZKqem6s/S220/lakhan.jpg";
strImage = url.Substring(url.LastIndexOf('/') + 1);
string DestinationPath = Server.MapPath("~/Products");
byte[] bytes = GetBytesFromUrl(url);
WriteBytesToFile(DestinationPath + "/" + strImage, bytes);
First we make the request for the given image url and server
will send us a response for that request in the form of stream of data.
With the help of BinaryReader system will read the content of image
and add that into byte array.
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;
}
Here we'll write the Byte array data with the help of
BinaryWriter on the given destinaion path.
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();
}
}