private static Bitmap ResizeImageFitLongestSide(Bitmap image, Size size, Color? spaceColor) { var colorSpace = spaceColor != null; var sourceWidth = image.Width; var sourceHeight = image.Height; var nPercentW = ((float)sourceWidth / size.Width); var nPercentH = ((float)sourceHeight / size.Height); var nPercent = Math.Min(nPercentH, nPercentW); var ufWidth = Math.Round(size.Width * nPercent); if (ufWidth < size.Width && sourceWidth > ufWidth) { ufWidth = Math.Min(size.Width, sourceWidth); } var ufHeight = Math.Round(size.Height * nPercent); if (ufHeight < size.Height && sourceHeight > ufHeight) { ufHeight = Math.Min(size.Height, sourceHeight); } var rect = new Rectangle((int)((sourceWidth - ufWidth) / 2), (int)((sourceHeight - ufHeight) / 2), (int)ufWidth, (int)ufHeight); var imageWidth = (int)Math.Min(ufWidth, size.Width); var imageHeight = (int)Math.Min(ufHeight, size.Height); if (!colorSpace) { var result = new Bitmap(imageWidth, imageHeight); using (var graphics = Graphics.FromImage(result)) { CustomizeGraphics(graphics); graphics.DrawImage(Clone(image, rect), 0, 0, imageWidth, imageHeight); } return result; } else { var result = new Bitmap(size.Width, size.Height); using (var graphics = Graphics.FromImage(result)) { graphics.Clear(spaceColor.Value); CustomizeGraphics(graphics); var imgAttributes = new ImageAttributes(); imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelC, ColorAdjustType.Bitmap); var clone = Clone(image, rect); graphics.DrawImage(clone, (int)((float)(size.Width - imageWidth) / 2), (int)((float)(size.Height - imageHeight) / 2), imageWidth, imageHeight); } return result; } }