using System.IO; using System.Drawing; using System; namespace ImageHelper { public class Resizer { public static Bitmap GetResizedImage(Stream inputStream, int maxWidth, int maxHeight) { float tempDimension; float newWidth; float newHeight; try { Image originalImg = Image.FromStream(inputStream); // work out the width/height for the thumbnail. Preserve aspect ratio and honor max width/height // Note: if the original is smaller than the thumbnail size it will be scaled up if (((originalImg.Width / maxWidth) > (originalImg.Width / maxHeight))) { tempDimension = originalImg.Width; newWidth = maxWidth; newHeight = (originalImg.Height * (maxWidth / tempDimension)); if ((newHeight > maxHeight)) { newWidth = (newWidth * (maxHeight / newHeight)); newHeight = maxHeight; } } else { tempDimension = originalImg.Height; newHeight = maxHeight; newWidth = (originalImg.Width * (maxWidth / tempDimension)); if ((newWidth > maxWidth)) { newHeight = (newHeight * (maxWidth / newWidth)); newWidth = maxWidth; } } Bitmap resizedImage = new Bitmap(Convert.ToInt32(newWidth), Convert.ToInt32(newHeight)); // Create a graphics object Graphics graphics = Graphics.FromImage(resizedImage); // just in case it's a transparent GIF force the bg to white Brush brush = new SolidBrush(System.Drawing.Color.White); graphics.FillRectangle(brush, 0, 0, resizedImage.Width, resizedImage.Height); // Re-draw the image to the specified height and width graphics.DrawImage(originalImg, 0, 0, resizedImage.Width, resizedImage.Height); return resizedImage; } catch { throw new Exception("Could not process image"); } } } }