繁体   English   中英

缩放图像保持纵横比不低于目标

[英]scale an image keeping the aspect ratio without falling below the targets

我想知道是否有人可以帮助我使用数学/伪代码/java代码将图像缩放到目标尺寸。 要求是保持纵横比,但在 x 和 y 尺度上都不能低于目标尺寸。 最终计算的尺寸可以大于请求的目标,但它必须是最接近目标的尺寸。

示例:我有一个 200x100 的图像。 它需要按比例缩小到 30x10 的目标尺寸。 我需要找到保持原点纵横比的最小尺寸,其中 x 和 y 比例至少是目标中指定的比例。 在我们的示例中,20x10 并不好,因为 x 比例低于目标(即 30)。 最接近的是 30x15

谢谢你。

targetRatio = targetWidth / targetHeight;
sourceRatio = sourceWidth / sourceHeight;
if(sourceRatio >= targetRatio){ // source is wider than target in proportion
    requiredWidth = targetWidth;
    requiredHeight = requiredWidth / sourceRatio;      
}else{ // source is higher than target in proportion
    requiredHeight = targetHeight;
    requiredWidth = requiredHeight * sourceRatio;      
} 

这样你的最终图像:

  • 始终适合目标内部而不被裁剪。

  • 保持其原始纵横比。

  • 并且始终具有与目标完全匹配的宽度或高度(或两者)。

好吧,在您的示例中,您已经使用了您正在寻找的算法。 我将使用您给出的示例。

Original          Target
200 x 100   ->    30 x 10

1. You take the bigger value of the target dimensions (in our case 30)
2. Check if its smaller than the corresponding original width or height
  2.1 If its smaller define this as the new width (So 30 is the new width)
  2.2 If its not smaller check the other part
3. Now we have to calculate the height which is simply the (30/200)*100

So as result you get like you wrote: 30 x 15

希望这很清楚:)

在编码部分,您可以使用BufferedImage并简单地创建一个具有正确比例值的新 BufferedImage 。

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0); // <-- Here you should use the calculated scale factors
AffineTransformOp scaleOp = 
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM