Explain Codes LogoExplain Codes Logo

How to resize images proportionally / keeping the aspect ratio?

javascript
responsive-design
image-manipulation
performance
Alex KataevbyAlex Kataev·Nov 19, 2024
TLDR

Effortlessly maintain an image's aspect ratio when sizing it by applying CSS's height: auto;. It recalibrates the height relative to the width provided:

img { width: 50%; /* Feel free to tweak this */ height: auto; /* Keeps image in shape (as you look marvelous in them) */ }

To resize images programmatically using JavaScript, calculate the height values keeping the original aspect ratio in mind:

function resizeImage(img, targetWidth) { img.height = targetWidth / (img.width / img.height); /* Math, my dear Watson */ img.width = targetWidth; }

Invoke the resizeImage function with your image element along with the desired width for scaling images proportionally. Cool? Cool!

Digging Deeper into JavaScript

In certain scenarios, you might need to resize images dynamically with JavaScript, typically when dealing with user-uploaded media or performing on-demand image manipulation. Here's an advanced method that considers both the maxWidth and the maxHeight parameters, ensuring the original aspect ratio is retained:

/* Minor in Mathematics not required */ function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); // This is where the magic happens 🧙‍♂️ return { width: srcWidth * ratio, height: srcHeight * ratio }; }

Now apply the function to an image:

const aspectRatio = calculateAspectRatioFit(img.naturalWidth, img.naturalHeight, maxWidth, maxHeight); img.width = aspectRatio.width; img.height = aspectRatio.height;

Resizing Multiple Images

JavaScript Loop

If you need to resize a sequence of images, simply traverse them using jQuery's .each() method:

$('img').each(function() { const maxWidth = 300; // This ain't Sparta, adjust the max-width as needed const maxHeight = 300; // One does not simply walk into Mordor, set a maximum height const ratio = calculateAspectRatioFit(this.naturalWidth, this.naturalHeight, maxWidth, maxHeight); $(this).css('width', ratio.width); $(this).css('height', ratio.height); });

CSS to the rescue

Alternatively, apply responsive web design principles with CSS, modifying the max-width and max-height to 100% (or any other desired factor):

img { max-width: 100%; /* Boundaries are important */ max-height: 100%; /* Honey, I shrunk the image! */ display: block; /* Takes care of that extra space beneath the image */ }

Special edge-cases

Large and In Charge

Handling large images can be problematic due to associated performance issues. In these cases, use libraries specifically designed to efficiently manipulate the loading and scaling of the images to prevent performance hangovers.

Precision Localization

Sometimes, we need to be as sharp as Occam’s razor. You can round results to achieve accuracy:

// Result from calculateAspectRatioFit const preciseWidth = Math.round(aspectRatio.width); const preciseHeight = Math.round(aspectRatio.height);

Minor differences matter when dealing with high-resolution (retina) displays, or when trying to achieve pixel perfection in your layouts.

One Size Does Not Fit All

Images don't always come in standard sizes like 16:9 or 4:3. Thus, when performing the resizing, adjust the unique ratio of each image, especially while handling a gallery or a grid layout. Consistency in image ratios keeps your layout from looking like Picasso's abstract art.

Practical Examples

There are many ways to skin a cat, and differing scenarios may need unique solutions. Be sure to use a live demonstration using jsFiddle or CodePen to allow real-time user interaction.