Here's a piece of code that I quickly knocked down that changed it based on width. I am sure you can understand how to add background color to the bitmap. This is not complete code, but just an idea of how to do things.
public static void ResizeLogo(string originalFilename, string resizeFilename) { Image imgOriginal = Image.FromFile(originalFilename); //pass in whatever value you want for the width (180) Image imgActual = ScaleBySize(imgOriginal, 180); imgActual.Save(resizeFilename); imgActual.Dispose(); } public static Image ScaleBySize(Image imgPhoto, int size) { int logoSize = size; float sourceWidth = imgPhoto.Width; float sourceHeight = imgPhoto.Height; float destHeight = 0; float destWidth = 0; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; // Resize Image to have the height = logoSize/2 or width = logoSize. // Height is greater than width, set Height = logoSize and resize width accordingly if (sourceWidth > (2 * sourceHeight)) { destWidth = logoSize; destHeight = (float)(sourceHeight * logoSize / sourceWidth); } else { int h = logoSize / 2; destHeight = h; destWidth = (float)(sourceWidth * h / sourceHeight); } // Width is greater than height, set Width = logoSize and resize height accordingly Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight, PixelFormat.Format32bppPArgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, (int)destWidth, (int)destHeight), new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; }
David
source share