Dealing with this issue myself was a bit of a challenge. You can determine the image ratio by dividing its width and height. If you're not using JavaScript, simply grab your calculator and divide the image width by its height. However, if you are using JavaScript, to find the flex value, you'll need to divide the image's width by its height, like so:
const imageRatio = img.naturalWidth / img.naturalHeight;
When obtaining the value, make use of the naturalWidth and naturalHeight properties that provide the original image size. Initially, I only used height and width; however, these values may be incorrect in certain cases (such as during image loading).
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth
In my case, I opted to calculate the column widths using JavaScript instead of the flex property since it doesn't function properly when text is present within the column. This made the calculations more intricate. You have to calculate the ratio of all images, sum them up to get the total ratio, and then divide the individual image ratios by this overall ratio to obtain the percentage.
Here's some sample pseudocode:
const getFullRatio = (images) => images.reduce((acc, curr) => (curr.naturalWidth / curr.naturalHeight) + acc, 0);
const containerWidth = 740;
const columnAmount = images.length;
const columnMargin = 15;
const marginPercentageToAdd = ((columnAmount * columnMargin) / containerWidth) + 1;
const fullRatio = getFullRatio(images);
const fullRatioWithMargins = fullRatio * marginPercentageToAdd;
images.forEach((img) => {
const imageRatio = img.naturalWidth / img.naturalHeight;
const columnRatio = (imageRatio / fullRatioWithMargins) * 100;
const imageParentDiv = img.closest('.COLUMNCLASS');
imageParentDiv.style.width = `${columnRatio}%`;
const image = img;
image.style.width = '100%';
});