为了账号安全,请及时绑定邮箱和手机立即绑定

根据纵横比将图像大小限制为最大高度和最大宽度

根据纵横比将图像大小限制为最大高度和最大宽度

冉冉说 2022-05-26 11:19:51
我有一个getMediaSize接受图像高度和图像宽度的函数:const MAX_HEIGHT = 500const MAX_WIDTH = 600function getMediaSize(iw, ih) {}我希望该函数MAX_WIDTH x MAX_HEIGHT根据纵横比返回适合尺寸的新图像宽度和高度。例如,getMediaSize(1200, 800)应该返回{ w: 600, h: 400 }
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

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


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

}


查看完整回答
反对 回复 2022-05-26
?
慕仙森

TA贡献1827条经验 获得超8个赞

这是工作示例 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)

  }

}


查看完整回答
反对 回复 2022-05-26
  • 2 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号