Image Resize without losing Aspect Ratio | C#.NET

AA,
In this post you will find out how to resize an image in C#.NET without losing its aspect ratio and quality.

How the image resize program works:

It iterates all the images in defined folder and converts them into all the resolutions defined in the code which are:
Height x Width
550 x 500
350 x 500
225 x 200
170 x 148

Here is the main image resize function:


public static Image FixedSize(Image imgPhoto, int Height, int Width, bool needToFill)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (!needToFill)
{
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
}
else
{
nPercent = nPercentW;
}
}
else
{
if (nPercentH > nPercentW)
{
nPercent = nPercentH;
destX = (int)Math.Round((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = (int)Math.Round((Height -
(sourceHeight * nPercent)) / 2);
}
}

if (nPercent > 1)
nPercent = 1;

int destWidth = (int)Math.Round(sourceWidth * nPercent);
int destHeight = (int)Math.Round(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(
destWidth <= Width ? destWidth : Width,
destHeight < Height ? destHeight : Height,
PixelFormat.Format32bppRgb);

Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);
grPhoto.Clear(System.Drawing.Color.White);
grPhoto.InterpolationMode = InterpolationMode.Default;
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.SmoothingMode = SmoothingMode.HighQuality;

grPhoto.DrawImage(imgPhoto,
new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),
new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
System.Drawing.GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}

How filled attribute works:

It does crop the image but it keeps the aspect ratio as is. To match the given new resolution. Try the code yourself.

Here you can find the complete project code.

One Reply to “Image Resize without losing Aspect Ratio | C#.NET”

Leave a Reply

Your email address will not be published. Required fields are marked *

Connect with Facebook