如何根据固定长宽比要求计算最大包围盒?

时间:2019-05-28 11:54:28

标签: javascript html image

我正在构建一些用户界面,以供用户上传和裁剪照片,这是我产品所需的固定纵横比。这个固定的长宽比恰好是人像。

我需要根据此宽高比在用户提供的照片中选择最大的内部边界框。这是两个示例(人像和风景):

enter image description here

enter image description here

因此,给定动态的用户添加尺寸,如何根据固定的宽高比来计算最大的作物选择?

const FIXED_ASPECT_RATIO = 3 / 4

const usersImageWidth = 800
const usersImageHeight = 550

const cropWidth = ?
const cropHeight = ?
const cropX = ?
const cropY = ?

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确回答了您的问题,但是根据我的理解,我会这样尝试:

// Check if picture is portrait or landscape oriented
if (userImageWidth >= userImageHeight) {
// If picture is landscape oriented, max crop height = height
  cropHeight = userImageHeight;
// Width is calculated according to ratio:
  cropWidth = (cropHeight / 4) * 3;
// If picture is portrait oriented, max crop width = width
} else {
  cropWidth = userImageWidth;
// Height is calculated according to ratio:
  cropHeight = (cropWidth / 3) * 4
}