Serge's World

Blogging about software development, astronomy, genealogy and more.

Proportionately Resizing A Bitmap in C#

Resizing a bitmap and keeping the sides proportions intact - in other words keeping the same aspect ratio, we need to specify a maximum width and maximum height.

The first thing we do is get the longest and shortest dimensions and divide the one by the other. We then have the ratio of the two sides which we will use further on in the calculations.

Then, finding the new width and height, we set the new width to the maximum width, and the new height to the maximum height divided by the ratio of the sides. If however, the height was the largest side, we then set the new height to the maximum height, and the width to maximum width divided by the ratio of the sides.

Once we have done this, we can then create a new Bitmap from the old Bitmap, using the new width and height we have calculated and then return the Bitmap as the last thing we do.

public static Bitmap ProportionallyResizeBitmap(Bitmap sourceBitmap, int maxWidth, int maxHeight)
{
	// original dimensions

	int width = sourceBitmap.Width;
	int height = sourceBitmap.Height;

	// Find the longest and shortest dimentions

	int longestDimension = (width > height) ? width : height;
	int shortestDimension = (width < height) ? width : height;

	double factor = ((double)longestDimension) / (double)shortestDimension;

	// Set width as max

	double newWidth = maxWidth;
	double newHeight = maxWidth / factor;

	//If height is actually greater, then we reset it to use height instead of width

	if (width < height)
	{
		newWidth = maxHeight / factor;
		newHeight = maxHeight;
	}

	// Create new Bitmap at new dimensions based on original bitmap

	Bitmap resizedBitmap = new Bitmap((int)newWidth, (int)newHeight);
	using (Graphics g = Graphics.FromImage((System.Drawing.Image)resizedBitmap))
		g.DrawImage(sourceBitmap, 0, 0, (int)newWidth, (int)newHeight);
	return resizedBitmap;
}

Originally posted on my old blog, Smoky Cogs, on 15 Nov 2009

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)