【问题标题】:Scale image to completely fill bounding box缩放图像以完全填充边界框
【发布时间】:2010-10-11 16:24:45
【问题描述】:

例如,如果我需要填充 100px 宽 x 50px 高的边界框,则以下输入图像将具有以下行为:

  1. 200w x 200h 缩小 50% 并且 25% 被从顶部切掉并且 底部。

  2. 200w x 100h 缩小 50% 没有裁剪。

  3. 100w x 200h 获取未缩放,但 75px 被切掉顶部和底部。

这似乎是一个常见的调整大小功能,但我无法找到该算法的示例。

将接受任何语言的答案,包括伪代码。带有答案的页面的链接也很棒!

【问题讨论】:

  • 有人对我的回答发表了评论,我以为是你,但事实并非如此——你能澄清一下关于你的实际限制的问题吗?谢谢。
  • 一般情况是我想要的。谢谢。
  • 谢谢。我已经删除了我的答案中误导性的一半。

标签: algorithm image image-scaling


【解决方案1】:

很大程度上受到 Mark Ransom 的回答的启发(非常感谢 - 你救了我)。对于任何想要这样做 裁剪图像(刚好适合范围内)的人,我发现这是可行的:

if (maxWidth > width && maxHeight > height) {
  return { width, height };
}

aspectRatio = width / height,
scale       = max(maxWidth / width, maxHeight / height);

scaledHeight = height * scale,
scaledWidth  = width * scale;

if (scaledHeight > maxHeight) {
  scaledHeight = maxHeight;
  scaledWidth  = aspectRatio * scaledHeight;
} else if (scaledWidth > maxWidth) {
  scaledWidth  = maxWidth;
  scaledHeight = scaledWidth / aspectRatio;
}

return { scaledHeight, scaledWidth };

【讨论】:

    【解决方案2】:

    您的要求很简单。计算宽度和高度的不同比例因子,然后为您的实际比例因子选择较大的比例因子。将您的输入大小乘以比例,然后裁剪出太大的那个。

    scale = max(maxwidth/oldwidth, maxheight/oldheight)
    scaledwidth = oldwidth * scale
    scaledheight = oldheight * scale
    if scaledheight > maxheight:
        croptop = (scaledheight - maxheight) / 2
        cropbottom = (scaledheight - maxheight) - croptop
    if scaledwidth > maxwidth:
        cropleft = (scaledwidth - maxwidth) / 2
        cropright = (scaledwidth - maxwidth) - cropleft
    

    【讨论】:

    • 只有 X(宽度)在调整大小的约束下。另一个 Y(高度)正在裁剪。
    • 没有说明该约束,也没有从您的示例中明显看出。在这种情况下,请改用 scale=maxwidth/oldwidth 并删除cropleft/cropright 计算,其余保持不变。
    • 我们是否应该将输出数字四舍五入,因为它们通常是像素的分数?
    • @GringoSuave 是的,对scaledwidthscaledheight 进行四舍五入是个好主意。尤其是因为浮点数不准确,截断可能会给你留下一个错误的错误。
    【解决方案3】:

    这里我们确保仅在 X 大于 100% 时进行缩放;然后在我们完成之后,我们确保我们在 Y 上只有 50 像素。如果我们大于 50,那么我们将差值除以 2 以获得从顶部/底部移除的数量。

    double percent_x = 1.0;
    
    if(X > 100) {
     percent_x = (float)100/X;
     X *= percent_x;
     Y *= percent_x;
    }
    
    int diff_y;
    int top_cut, bott_cut;
    if( Y > 50 ) {
     diff_y = (Y - 50) / 2;
     top_cut = bott_cut = diff_y;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 2021-03-11
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      相关资源
      最近更新 更多