Monday, August 8, 2011

How to Copy an Image from A URL to Your Own Server and Change Its Size

First: Download the image with Url.
Second: Resize the image and save it into disk.

1) For the first requirement, you can use WebClient class. Refer to the following code
private void Page_Load(object sender, System.EventArgs e)
{
WebClient wc = new WebClient();

byte[] data = wc.DownloadData("http://www.google.cn/intl/en-us/images/logo_cn.gif");

MemoryStream ms = new MemoryStream(data);

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

GetThumbnailImage(img);//Resize Image
}


2) For the second requirement refer to the code below:
private void GetThumbnailImage(System.Drawing.Image img)
{
float iScale = img.Height > img.Width ? (float)img.Height / 100 : (float)img.Width / 100;

img = img.GetThumbnailImage((int)(img.Width / iScale), (int)(img.Height / iScale), null, IntPtr.Zero);

MemoryStream memStream = new MemoryStream();

img.Save(Server.MapPath("att.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg);

memStream.Flush();
}


SPONSORS:

No comments:

Post a Comment