I thought I’d have a crack at this to brush up my JS skills but this is probably too simplistic.
The problems I see are that if you have set a width (or width attribute) for the image then the image will be squashed unless you change the width to auto for those images. (Or if you already have the images styled with percentages in the css then you will get squashed or stretched images once again.)
If the images need to be a specific width then you will need to use object-fit in css to maintain the aspect ratio.
There are too many ‘ifs’ for a full example but hopefully the demo will be of some use.