Resizing a SMALLEST Image

This is similar to what was set before, but I cannot find a duplicate, so ...

I want the smallest image size scaled to a maximum of 200, while maintaining aspect ratio. So:

  • A 600x400 image has a smallest size of 400, which should be 200, so the scale is 0.5: the new image will be 300x200.
  • Similarly 400x800 will be 200x400
  • The smallest size for 100x300 is already <200, so it will remain 100x300.

Obviously, if this can be done using css, this is preferable to javascript.

+4
source share
1 answer

Yes, you will 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
+3

Source: https://habr.com/ru/post/1532197/


All Articles