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

时间:2011-08-11 23:39:20

标签: java image

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

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

谢谢。

2 个答案:

答案 0 :(得分: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;      
} 

这样你的最终形象:

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

  • 保持原有的宽高比。

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

答案 1 :(得分: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);