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

5 java image

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

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

谢谢.

dar*_*rma 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;      
} 
Run Code Online (Sandbox Code Playgroud)

这样你的最终形象:

  • 总是适合目标而不是被裁剪.

  • 保持其原始宽高比.

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