Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


.NET - Resize Image to Square
Method to resize an image so that it fits into a square:

/// <summary>
/// Resizes an image on disk to a square
/// </summary>
/// <param name="filePath"></param>
/// <param name="newWidthAndHeight">Resizes file to a square of this width and height</param>
public static void ResizeImageToSquare(string filePath, int newWidthAndHeight)
{
using (System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(filePath))
{
decimal w = bmp.Width;
decimal h = bmp.Height;
if (w > newWidthAndHeight && w>=h)
{
var scaling = (decimal)newWidthAndHeight / w;
w = newWidthAndHeight;
h *= scaling;
}
else if (h > newWidthAndHeight)
{
var scaling = (decimal)newWidthAndHeight / h;
h = newWidthAndHeight;
w *= scaling;
}

using (System.Drawing.Bitmap resized = new System.Drawing.Bitmap(newWidthAndHeight, newWidthAndHeight))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(resized))
{
g.Clear(System.Drawing.Color.White);
int x = w < (decimal)newWidthAndHeight ? (newWidthAndHeight - (int)w) / 2 : 0;
int y = h < (decimal)newWidthAndHeight ? (newWidthAndHeight - (int)h) / 2 : 0;
g.DrawImage(bmp, x, y, (int)w, (int)h);
bmp.Dispose();
resized.Save(filePath);
}
}
}
} // resize

Created By: amos 12/11/2014 5:06:05 PM
Updated: 1/2/2015 2:24:12 PM