调整SMALLEST图像尺寸的大小

时间:2014-03-17 19:33:38

标签: javascript css image-resizing aspect-ratio

这似乎是以前会被问过但我找不到副本的东西......

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

  • 600x400图像的最小尺寸为400,应为200,因此比例为0.5:新图像为300x200
  • 同样400x800将为200x400
  • 100x300的最小尺寸已经 200所以它将保持100x300。

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

1 个答案:

答案 0 :(得分:3)

是的,你需要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
相关问题