How to scale image to be a set height and have a max width with respect to aspect ratio?


I am receiving images through a backend service, and I need them to be scaled to fit a set height and up to a maximum width. I cannot seem to find the best/most efficient way to do this.

I have tried using the flexItem: {maxWidth: 500} property on an element, but this does not affect the image. I have also tried using the Img component like Img(url).portrait(100), but this does not seem to do anything. It doesn’t set the height to 100px nor maintain the aspect ratio in respect to the height as the docs say it’s supposed to; the image is the same size as it would be normally. Perhaps I am using Img wrong, but the docs page does not show how to actually use it. I see it returns an object with a src tag, so I assumed it should be spread over the component? Either way, it doesn’t set a maximum width, so it wouldn’t even be the right choice, unless that could also be done.

I’m trying to make sure the aspect ratio is preserved in an image, keeping the height of it locked to 100px always, and having the width be dynamically adjustable up to a maximum of 500px, at which point it would just squish the image to fit the constraint. What is the easiest/simplest method to do this in Lightning?


The SDK Img works with the Metrological backend to scale the images server side, which you’re probably not using and won’t work for you.

Instead you can use resizeMode on the image: