This seems like something that would've been asked before but I can't find the duplicate so...
I want the smallest dimension of an image to be scaled max 200 while keeping aspect ratio. So:
Obviously if it can be done with css then that is preferred over javascript.
Yep, you'll need JS:
LIVE DEMO
function scale(W, H, max) {
var min = Math.min(W, H), // Get the smallest size
nr = min>max, // NeededResize (Boolean)
rat = Math.min(max/W, max/H);// Ratio
return {
W: nr?W*rat:W, // if NeededResize do W*rat, else just use the image W
H: nr?H*rat:H
};
}
// Use like: scale(imageWidth, imageHeight, maxSizeToRespect);
var resize = scale(this.width, this.height, 200);
// Where from now on
resize.W // is the returned width scale
resize.H // is the returned height scale
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With