I am working with a system that needs to consume product images uploaded by employees and resize them / add white padding to the sides to create square images to be consumed by our e-commerce site. I'm attempting to keep things somewhat light on the memory usage because this will live in a windows service on an azure vm. I know there are better solutions, but that's what I'm given as a platform. I also don't want to use 3rd party libraries.
The following code is what I have so far. Please, pick it apart and let me know if i'm making any mistakes.
public static Image ImageToFixedSize(Image originalImage, int width, int height)
{
Graphics graphicController = null;
try
{
if (originalImage != null)
{
int sourceWidth = originalImage.Width;
int sourceHeight = originalImage.Height;
int destX = 0;
int destY = 0;
float percent = 0;
float percentW = 0;
float percentH = 0;
percentW = width / (float)sourceWidth;
percentH = height / (float)sourceHeight;
if (percentH < percentW)
{
percent = percentH;
destX = Convert.ToInt16((width - (sourceWidth * percent)) / 2);
}
else
{
percent = percentW;
destY = Convert.ToInt16((height - (sourceHeight * percent)) / 2);
}
int destWidth = (int)(sourceWidth * percent);
int destHeight = (int)(sourceHeight * percent);
Bitmap tempPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);
tempPhoto.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
graphicController = Graphics.FromImage(tempPhoto);
graphicController.FillRectangle(Brushes.White, 0, 0, width, height);
// The chances of hitting this ONE SPECIFIC COLOR are very slim
graphicController.SmoothingMode = SmoothingMode.HighQuality;
graphicController.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphicController.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicController.CompositingQuality = CompositingQuality.HighQuality;
graphicController.DrawImage(
originalImage,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(1, 1, sourceWidth - 1, sourceHeight - 1),
GraphicsUnit.Pixel);
return tempPhoto;
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
graphicController.Dispose();
}
}