0

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.

MarsOne
  • 2,155
  • 5
  • 29
  • 53
  • 1
    pick any duplicate from http://stackoverflow.com/search?q=resize+image+c%23 – chiccodoro Aug 20 '14 at 14:13
  • possible duplicate of [Resize an Image C#](http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp) – chiccodoro Aug 20 '14 at 14:16
  • http://stackoverflow.com/questions/1932546/resizeing-image, http://stackoverflow.com/questions/11137979/image-resizing-using-c-sharp, http://stackoverflow.com/questions/24748270/resizing-image-in-c-sharp, or http://stackoverflow.com/questions/1613117/resizing-an-image-in-cm-c-sharp, do just as well – chiccodoro Aug 20 '14 at 14:17
  • I hope you don't mean resize before downloading.. no can do for that. – TaW Aug 20 '14 at 14:48

1 Answers1

3

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.

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76