While developing web application for digital publications using Java and Javascript, I was forced to resize images on server and
client sides by width or height and the main concern was to keep the aspect ratio of the images. So here is a simple solution, better say method,
how you can calculate the ratio. You can pass either only width, or height, or both of them.

Java example

/*
	@originalWidth 	- is required
	@originalWidth 	- is required
	@newWidth	- width to resize to, pass 0 if you want to resize only by height
	@newHeight	- height to resize to, pass 0 if you want to resize only by width
*/
private double getAspectRatio(int originalWidth, int originalHeight, int newWidth, int newHeight) {
	double ratioX = (double) newWidth / originalWidth;
	double ratioY = (double) newHeight / originalHeight;
	return Math.max(ratioX, ratioY);
}

Javascript example

/*
	@originalWidth 	- is required
	@originalWidth 	- is required
	@newWidth	- width to resize to, pass 0 if you want to resize only by height
	@newHeight	- height to resize to, pass 0 if you want to resize only by width
*/
var getAspectRatio = function(originalWidth, originalHeight, newWidth, newHeight) {
	var ratioX = newWidth / originalWidth;
	var ratioY = newHeight / originalHeight;
	return Math.max(ratioX, ratioY);
};

Dima Svirid

Software architect. Ajax/Javascript, HTML5, Android, iPhone/iPad, JAVA, PHP, Cold Fusion, SQL, Air, Flash, Open source software, Frameworks

More Posts

Follow Me:

Tagged with:
 

Leave a Reply