调整最小图像尺寸

Mar*_*ark 5 javascript css aspect-ratio image-resizing

这似乎是之前有人问过的问题,但我找不到重复的东西,所以......

我希望图像的最小尺寸在保持纵横比的同时最大缩放 200。所以:

  • 600x400 图像的最小尺寸为 400,应为 200,因此按 0.5 缩放:新图像将为 300x200
  • 同样,400x800 将是 200x400
  • 100x300 的最小尺寸已经 < 200,因此它将保持为 100x300。

显然,如果它可以用 css 来完成,那么它比 javascript 更受欢迎。

Rok*_*jan 3

是的,你需要 JS:

现场演示

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
  };
}
Run Code Online (Sandbox Code Playgroud)

// 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
Run Code Online (Sandbox Code Playgroud)