比例图像调整大小

Hot*_*xel 31 language-agnostic image-manipulation

我将图像缩放到适当的预定义大小时遇到​​了一些问题.我想知道 - 因为它纯粹是数学,如果有某种常见的逻辑算法适用于每种语言(PHP,ActionScript,Javascript等),可以按比例缩放图像.

我现在正在使用它:

var maxHeight   = 300;
var maxWidth    = 300;

var ratio:Number    =   height / width;

if (height > maxHeight) {
    height = maxHeight;
    width = Math.round(height / ratio);
} 

else if(width > maxWidth) {
    width = maxWidth;
    height = Math.round(width * ratio);
}
Run Code Online (Sandbox Code Playgroud)

但它不能正常工作.图像按比例缩放,确定,但尺寸未设置为300(宽度或高度).这有点意义,但我想知道是否有一种傻瓜式,简单的方法来按比例缩放图像.

Dar*_*ari 64

ratio = MIN( maxWidth / width, maxHeight/ height );
width = ratio * width;
height = ratio * height;
Run Code Online (Sandbox Code Playgroud)

确保所有除法都是浮点数.