Resize Bitmap Image with Aspect Ratio

Just Copy this function into your code and use it to resize the bitmap image with corresponding aspect Ratio.

private Bitmap ResizeImage(Bitmap image, int width, int height)
{
Bitmap OriginalBmp = image;

int OriginalWidth = OriginalBmp.Width;
int OriginalHeight = OriginalBmp.Height;
int OriginalX = 0;
int OriginalY = 0;
int NewX = 0;
int NewY = 0;

float Percent = 0;
float WidthPercent = 0;
float HeightPercent = 0;

WidthPercent = ((float)width / (float)OriginalWidth);
HeightPercent = ((float)height / (float)OriginalHeight);
if (HeightPercent < WidthPercent)
{
Percent = HeightPercent;
NewX = System.Convert.ToInt32((width – (OriginalWidth * Percent)) / 2);
}
else
{
Percent = WidthPercent;
NewY = System.Convert.ToInt32((height – (OriginalHeight * Percent)) / 2);
}

int DestWidth = (int)(OriginalWidth * Percent);
int DestHeight = (int)(OriginalHeight * Percent);

Bitmap NewImage = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
NewImage.SetResolution(OriginalBmp.HorizontalResolution, OriginalBmp.VerticalResolution);

Graphics Gr = Graphics.FromImage(NewImage);
Gr.Clear(Color.White);
Gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

Gr.DrawImage(OriginalBmp, new Rectangle(NewX, NewY, DestWidth, DestHeight), new Rectangle(OriginalX, OriginalY, OriginalWidth, OriginalHeight), GraphicsUnit.Pixel);
Gr.Dispose();
OriginalBmp.Dispose();
MemoryStream Ms = new MemoryStream();
return NewImage;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: