简体   繁体   中英

How can I resize an Image from remote URL before saving it

This is my code to save images. The code works fine and i have no issues with it.

Guid id = Guid.NewGuid();      

string strRealname = Path.GetFileName(ImageUrl);
string exts = Path.GetExtension(ImageUrl);

WebClient webClient = new WebClient();
webClient.DownloadFile(ImageUrl, Server.MapPath("~/Images/") + id + exts);

I want to be able to save the image according to my SET dimensions. For example: an image I download is 600x300. I want to keep the original dimensions(2:1) and save it as 400x200. How can I do this?

EDIT: Maybe i Should have stressed this point. I dont want to save the orginal image from the URl. Some of the images would be more than 1000px in width or height. I want to downscale this before saving. this will be done for 1000's of Images and I dont want my server to run out of of disk space.

There are many ways to do this, but the simplest may be to use GDI+ and the Graphics class.

Instead of downloading a file, download a stream and create a Bitmap object from that using Bitmap.FromStream .

Then create a new Bitmap with the dimensions you want and use Graphics.FromImage to create a Graphics object that will draw to that image.

Finally use the Graphics.DrawImage to draw the downloaded image to the new one. Pass in the dimensions of the resized image to the method and you will get a Bitmap object containing the resized image that is ready to be written to disk.

NOTE: I am unable to setup a complete example at the moment, but this should be enough for you to sort it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM