保持纵横比缩放图像,同时不低于目标大小

5
我想知道是否有人能够帮助我用数学/伪代码/Java代码将图像缩放到目标尺寸,要求保持宽高比,但不低于目标尺寸的x和y比例。最终计算出的尺寸可以大于请求的目标,但需要是最接近目标的尺寸。
例如:我有一张200x100的图片,需要缩小到一个30x10的目标尺寸。我需要找到保持原始宽高比的最小尺寸,其中x和y比例至少符合目标要求。在我们的例子中,20x10不好,因为x比例低于目标(即30)。最接近的尺寸将是30x15。
谢谢。
2个回答

10
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;      
} 

通过这种方式,您的最终图像:

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

  • 保持其原始纵横比。

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


谢谢您的回答:)。但是我需要的是宽度和高度始终与目标计数器部分匹配或大于它。如果完全匹配,则接受适合,否则应更大。当它变得更大时,我需要找到最小的一个,它更大,但保持纵横比。 - user890904
我点击了回车键,然后它就发布了,所以我修改了我的评论。解决方案部分满足,因为在某些情况下,其中一个维度可能会低于目标值。 - user890904
好的,那么你只需要颠倒我的if/else代码块,它就会按照预期工作。 - darma

0

好的,在你的例子中,你已经使用了你正在寻找的算法。 我将使用你提供的例子。

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);

谢谢。我在我的IDE中检查了darma的回复和评论,这非常清晰且正确。非常感谢您。是否可以接受两个答案? - user890904

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接