Save Image For given URL

Posted by Lakhangarg under ASP.NET category on | Views : 2784
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.

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);
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);

Comments or Responses

Login to post response