Scaling Images preserving Aspect Ratio. Universal method for Java and Javascript.
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
SEARCH ARTICLES & TUTORIALS
MOST POPULAR TUTORIALS
Generating PDF Documents with Adobe Air Javascript SDK and jQuery
I am not a Flex guy and I don't think I will ever be. While searching [...]
Search Engine Optimization - Do It Yourself!
This is Part 1 of "Search Engine Optimization – Do It Yourself!" ser[...]
jQuery Object Oriented Plugins
Many people have asked me, if jQuery is object oriented and how they c[...]
Spring-MVC Tutorial (Part 1)
Overview This document is a step-by-step guide on how to de[...]
Animated scroll to anchor method with jQuery
It's a one line but can add a really nice effect to your website. f[...]
RECENT POSTS
Is trying to be everywhere online actually helping grow your business?
Social media experts have probably told you that keeping your clients [...]
How to calibrate Samsung Galaxy battery
There is no guarantee that this method will work for you. However it d[...]
Real Estate Social Network new Toronto Startup
Wanted to write for a long time about a new startup for Real Estate ag[...]
Eclipse Keyboard Shortcuts for Developers
Eclipse Navigation Shortcuts Every Java Programmer Should Know Ctrl [...]
Duplicated Content
This is Part 4 of "Search Engine Optimization – Do It Yourself!" ser[...]




