Evalute The Height Of An Image Based On A Set Width, When This Width Has Been Reduced In Size

23 Views Asked by At

I have a situation where images of varying aspect ratios will be shown inside an image grid on a website.

Because the images will be of all different sizes I'm going to need to work out a dynamic height value for an HTML height attribute to prevent layout shifts on page load.

The maximum width of each image in the grid is 450px (this is dictated by a wrapper element around each image in the grid), so for the width value I can just hardcode width="450". The width and height dimensions of the original image are stored in the database during the upload process. I don't particuarly want to use these for the width and height attributes though, because some of the images can potentially be very large. For example, having a width="5000" attribute value on a grid with small images seems like a terrible idea all round.

Question Summary

How do I work out the value for the image's new height, when the width is set to 450, so that the image retains its correct aspect ratio? An example being on an image that has original size values of say 5000px (width) x 3333px (height), where this width value is reduced to 450?

Many thanks,

1

There are 1 best solutions below

0
On

Recall that the ratio is the width/height. You want the original aspect ratio to be equivalent to the final aspect ratio. Thus, newWidth/newHeight = oldWidth/oldHeight. So, 450px/Xpx = 5000px/3333px. Simplifying the right gets you 450/x = 1.50015. Cross multiply to get x = 450/1.50015, so x = 299.97. The new height should be approximately 300px