Just ran into a problem where I needed to resize images to fill (without distortion) a box of a defined height and width with high quality using C#. As I’m working with the Images as Streams to and from the database, my function takes and returns MemoryStream objects. It should be trivial to adjust the function to use Image objects as inputs and outputs instead.
The code I’ve written is below.
using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; ... private MemoryStream ResizeImageStream(MemoryStream stream, int boundingBoxWidth, int boundingBoxHeight) { // One of the dimensions of the resultant image WILL be 'full size'. // i.e. The image will either have a width of boundingBoxWidth or a height of boundingBoxHeight. // This will happen whether the image needs to be shrunk or enlarged. Image imageToBeResized = Image.FromStream(stream); #region Derive the undistorted dimensions of the resized image. int imageResizeToHeight = (imageToBeResized.Height * boundingBoxWidth) / imageToBeResized.Width; int imageResizeToWidth = boundingBoxWidth; if (imageResizeToHeight >= boundingBoxHeight) { imageResizeToWidth = (imageResizeToWidth * boundingBoxHeight) / imageResizeToHeight; imageResizeToHeight = boundingBoxHeight; } #endregion #region Resize the image with high quality. Bitmap bitmap = new Bitmap(imageResizeToWidth, imageResizeToHeight); Graphics graphics = Graphics.FromImage(bitmap); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; // Resize the image using the Graphics object. // As the Graphics object is tied to the Bitmap above, the resulting image will be in the Bitmap object. graphics.DrawImage(imageToBeResized, new Rectangle(0, 0, imageResizeToWidth, imageResizeToHeight)); // Re-instantiate the stream in order to clean it out. stream = new MemoryStream(); // Save the Bitmap into the MemoryStream as a PNG. bitmap.Save(stream, ImageFormat.Png); #endregion return stream; }

