Resizing an Image in C#

Because the resolution of that image the user uploaded is too damn high.
Mar 26 2008 by James Craig

One of the things that comes up constantly for some reason is image manipulation and specifically resizing of an image. It's actually really simple to do. However by default resizing an image in .Net is done using a fast method that tends to have a poor quality. We can, however, set the quality of the function based on our needs. Anyway here's the code to do it:

 /// <summary>
/// Resizes an image to a certain height
/// </summary>
/// <param name="Image">Image to resize</param>
/// <param name="Width">New width for the final image</param>
/// <param name="Height">New height for the final image</param>
/// <param name="Quality">Quality of the resizing</param>
/// <returns>A bitmap object of the resized image</returns>
public static Bitmap ResizeImage(Bitmap Image, int Width, int Height, Quality Quality)
{
Bitmap NewBitmap = new Bitmap(Width, Height);
using (Graphics NewGraphics = Graphics.FromImage(NewBitmap))
{
if (Quality == Quality.High)
{
NewGraphics.CompositingQuality = CompositingQuality.HighQuality;
NewGraphics.SmoothingMode = SmoothingMode.HighQuality;
NewGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
}
else
{
NewGraphics.CompositingQuality = CompositingQuality.HighSpeed;
NewGraphics.SmoothingMode = SmoothingMode.HighSpeed;
NewGraphics.InterpolationMode = InterpolationMode.NearestNeighbor;
}
NewGraphics.DrawImage(Image, new System.Drawing.Rectangle(0, 0, Width, Height));
}
return NewBitmap;
}

The Quality item is a basic enum:

 public enum Quality
{
High,
Low
}

As you can see, it's rather simple to accomplish, but is definitely one of those items that should be in every web developers tool box. All the code does, is creates a new bitmap, sets the quality settings for the resize, and then lets .Net resize the image for us. Anyway, try out the code, leave comments, and happy coding.