How to Resize Photos in ASP.NET

If you’re developing a website that allows users to upload any sort of photos or images, you have to expect that they aren’t going to bother doing any sort of basic image manipulation, such as resizing an 8 megapixel image down to something that’s appropriate for the web. Fortunately, there are a number of good cropping and image resizing tools that are available for most server-side programming languages.

ASP.NET does a particularly good job of offering the ability to resize photos. The System.Drawing library that comes with .NET allows you to resize photos extremely well with just a few lines of code, and place it in the format that you’d like.

Here’s how to resize photos in the .NET Framework:

(1) Reference the appropriate libraries.

The example code below will be in C#, but it will work basically the same way for Visual Basic or J#. You’ll need to reference the System.IO library to read and write the files, as well as the System.Drawing library and the System.Drawing.Imaging library. To do this, simply add the following lines to the top of your code-behind page.

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

(2) Load the OriginalImage

The following three lines of code will take an existing image that you can set programmatically, say if you want to connect it to a photo gallery module in a database, and create a bitmap/image object that you can use to resize the image:

string UploadPath = Server.MapPath(“/images/”);
string FileName = “OriginalImage.PNG”;
Bitmap OriginalBM = new Bitmap(UploadPath + FileName);

(3) Determine The New Size

Typically you’ll want to keep the aspect ratio the same, but you can set them statically if you’d like.  Here’s some code that will create two variables for the height and the width. We set the width statically based on what we’d like to use, then the height is based on the aspect ratio of the original image so that the image is not stretched.Finally, we’ll create a “Size” object that will be used for the resizing

float AspectRatio = (float)OriginalBM.Size.Width / (float)OriginalBM.Size.Height;
int NewWidth = 800;
int newHeight = NewWidth / AspectRatio;
Size newSize = new Size(NewWidth, newHeight);

(4) Resize and Save the Photo

Once you have a new “Size” object created, we can create a new Bitmap/image object with the new size that we specify and save it in the format of image that we’d like. In this case, I’m saving it as a Jpeg file, but you can also save it as a PNG, GIF, or Bitmap file if you’d like.

Bitmap ResizedBM = new Bitmap(OriginalBM, newSize);
string newfilepath = UploadPath + “resized_” + FileName.Replace(@”\”, @””);
ResizedBM.Save(newfilepath, ImageFormat.Jpeg);

Speak Your Mind