调整最小图像尺寸

Resize SMALLEST image dimension

本文关键字:图像 调整      更新时间:2023-09-26

这似乎是以前会问的问题,但我找不到重复的,所以…

我想要一个图像的最小尺寸被缩放到最大200,同时保持长宽比。所以:

  • 一个600x400的图像的最小尺寸是400,应该是200,所以缩放0.5:新图像将是300x200
  • 类似地,400x800将是200x400
  • 100x300的最小尺寸已经是<所以它仍然是100x300。>

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

是的,你需要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
  };
}

// 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