7

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:

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

Obviously if it can be done with css then that is preferred over javascript.

Mark
  • 18,730
  • 7
  • 107
  • 130
  • 2
    Those aren't duplicates, they make the LARGEST dimension 200... – Mark Mar 17 '14 at 19:49
  • 3
    Wouldn't you just invert the logic and do the same thing? – George Stocker Mar 17 '14 at 19:53
  • Have you tried anything? Also, I don't think this can be done with pure css.. probably you should write some JS to test for the largest dimension and then set width/height accordingly. The other dimension should be set to auto so the image remains proportions – donnywals Mar 17 '14 at 19:53
  • 1
    This fiddle will get you started - http://jsfiddle.net/kP3TC/ – TimSPQR Mar 17 '14 at 21:43
  • @George Stocker: how would that work? I can make the largest dimension 200 by fitting it inside a 200x200 box. What box would I pick to make the smallest dimension 200? (I'm only asking this to show why it's not possible). – Mark Mar 20 '14 at 15:55

1 Answers1

3

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
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313