/// <summary> /// Scale the bitmap, keeping aspect ratio, but the canvas will always have the specified size. /// </summary> /// <param name="sourceImage">Image to scale</param> /// <param name="maintainAspectRatio">true to maintain the aspect ratio</param> /// <param name="canvasUseNewSize">Makes the image maintain aspect ratio, but the canvas get's the specified size</param> /// <param name="backgroundColor">The color to fill with, or Color.Empty to take the default depending on the pixel format</param> /// <param name="newWidth">new width</param> /// <param name="newHeight">new height</param> /// <param name="matrix">Matrix</param> /// <param name="interpolationMode">InterpolationMode</param> /// <returns>a new bitmap with the specified size, the source-Image scaled to fit with aspect ratio locked</returns> public static Bitmap Resize(this Image sourceImage, bool maintainAspectRatio, bool canvasUseNewSize, Color backgroundColor, int newWidth, int newHeight, Matrix matrix, InterpolationMode interpolationMode = InterpolationMode.HighQualityBicubic) { var destX = 0; var destY = 0; var nPercentW = newWidth / (float)sourceImage.Width; var nPercentH = newHeight / (float)sourceImage.Height; if (maintainAspectRatio) { if ((int)nPercentW == 1 || (int)nPercentH != 0 && nPercentH < nPercentW) { nPercentW = nPercentH; if (canvasUseNewSize) { destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2)); } } else { nPercentH = nPercentW; if (canvasUseNewSize) { destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2)); } } } var destWidth = (int)(sourceImage.Width * nPercentW); var destHeight = (int)(sourceImage.Height * nPercentH); if (newWidth == 0) { newWidth = destWidth; } if (newHeight == 0) { newHeight = destHeight; } Bitmap newBitmap; if (maintainAspectRatio && canvasUseNewSize) { newBitmap = BitmapFactory.CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); matrix?.Scale((float)newWidth / sourceImage.Width, (float)newHeight / sourceImage.Height, MatrixOrder.Append); } else { newBitmap = BitmapFactory.CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); matrix?.Scale((float)destWidth / sourceImage.Width, (float)destHeight / sourceImage.Height, MatrixOrder.Append); } using (var graphics = Graphics.FromImage(newBitmap)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = interpolationMode; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(sourceImage, new NativeRect(destX, destY, destWidth, destHeight), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode); } } return(newBitmap); }