Skip to content

Instantly share code, notes, and snippets.

@odises
Last active January 3, 2016 19:49
Show Gist options
  • Save odises/8511218 to your computer and use it in GitHub Desktop.
Save odises/8511218 to your computer and use it in GitHub Desktop.
Resizing Image Canvas - Fit original Image to an square
private Bitmap ExpandCanvas(System.Drawing.Image inputImage)
{
var img = inputImage;
// Calculate the square side
var max = Math.Max(img.Width, img.Height);
int side;
var isVertical = false;
// Check if the image is vertical or horizontal
// and then calculate the side white space
if (img.Height > img.Width)
{
isVertical = true;
side = (img.Height - img.Width) / 2;
}
else
{
side = (img.Width - img.Height) / 2;
}
Size szDimensions = new Size(max, max);
// Create blank canvas
Bitmap resizedImg = new Bitmap(szDimensions.Width, szDimensions.Height);
resizedImg.SetResolution(img.HorizontalResolution, img.VerticalResolution);
// Fill canvas with White color
Graphics gfx = Graphics.FromImage(resizedImg);
gfx.FillRectangle(Brushes.White, 0, 0, max, max);
//Check if the image is vertical
if (isVertical)
{
// Paste source image on white canvas and shift image from right to the center
gfx.DrawImageUnscaled(img, side, 0);
}
else
{
// Paste source image on white canvas and shift image from top to the center
gfx.DrawImageUnscaled(img, 0, side);
}
// Dispose gfx
gfx.Dispose();
return resizedImg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment