Learn how to calculate automatically the proper height of an image with custom width preserving the original aspect ratio.

How many times have we dealt with the same issue over and over again? We try to resize an image with a custom width but we need to research how to provide the image with the proper height so it doesn't look funny. For example, if you resize an image with a custom width but you don't care about the new height, you will end up with this (if you set the original height):

Resize Image Without Preserving Aspect Ratio

If you want to keep the aspect ratio of the image, you will need to calculate the new height with the following formula:

(original height / original width) x new width = new height

Which in JavaScript could be implemented like this:

/**
 * Calculates the proper height of an image with a custom width, preserving the original aspect ratio.
 * 
 * @param originalHeight 
 * @param originalWidth 
 * @param newWidth 
 */
function determineNewHeight(originalHeight, originalWidth, newWidth){
    return (originalHeight / originalWidth) * newWidth;
}

In our case, with the example image of 1600px of width and 1200px of height, if I want to resize it to a new image of 800px of width, I would be able to calculate the new height like this:

// This would return: 600
determineNewHeight(1200, 1600, 800);

The result would be 600px so the image can preserve its original aspect ratio and not look funny when resizing it:

Resize Image Preserving Aspect Ratio

Happy coding ❤️!


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors