根据宽高比将图像尺寸限制为最大高度和最大宽度

时间:2020-03-22 19:39:51

标签: javascript image math

我有一个名为getMediaSize的函数,可以接受图像高度和图像宽度:

const MAX_HEIGHT = 500
const MAX_WIDTH = 600
function getMediaSize(iw, ih) {

}

我希望该函数根据宽高比返回适合MAX_WIDTH x MAX_HEIGHT尺寸的新图像宽度和高度。

例如,getMediaSize(1200, 800)应该返回{ w: 600, h: 400 }

2 个答案:

答案 0 :(得分:1)

如果我们逐个查看每个维度,就很容易看到调整数学。

MAX_DIMENSION = CURRENT_DIMENSION * ADJUSTMENT

// We need to figure out what the adjustment is, we have the other two values
// do some algebra and we get
ADJUSTMENT = MAX_DIMENSION / CURRENT_DIMENSION

出现的问题是每个尺寸将具有其自己的调整值,这将导致图像被拉伸/压缩(纵横比不保持不变)。因此,我们只需要选择一个要使用的调整值,但选择哪一个呢?当然是最小的,否则其中一个尺寸会溢出。

// Calculate which adjustment is the smallest, width or height
// otherwise we'd overflow one of them.
let widthPercent = MAX_WIDTH / iw;
let heightPercent = MAX_HEIGHT / ih;
let smallestPercent = Math.min(widthPercent, heightPercent);

// This works for both scaling up and scaling down
return {
    w: iw * smallestPercent,
    h: ih * smallestPercent
}

答案 1 :(得分:1)

这里是工作示例 https://codepen.io/Kison/pen/JjdaMda

这是源代码

const MAX_HEIGHT = 500;
const MAX_WIDTH = 600;

function getMediaSize(iw, ih) {
  let 
    ratio = 0,
    height = ih,
    width = iw
  ;  

  if (iw > MAX_WIDTH && iw > ih) 
  {   
      height = MAX_WIDTH / (iw / ih /* aspect ratio */);
      width = MAX_WIDTH;
  } 
  else if (ih > MAX_HEIGHT && ih > iw) 
  {    
      width = MAX_HEIGHT / (ih / iw /* aspect ratio */);
      height = MAX_HEIGHT;
  }

  return {
    width: Math.round(width),
    height: Math.round(height)
  }
}