保持纵横比

时间:2012-08-30 22:57:20

标签: javascript css image aspect-ratio jcrop

我目前正在制作一个图像裁剪工具,图像裁剪工具来自jCrop,我想要的是使用户拍摄的图像小于上传的原始图像。基本上如果上传风景图像,我需要将图像宽度设置为304px而不改变镜头的宽高比。

例如,如果用户上传肖像照片,我需要在不改变镜头宽高比的情况下制作图像237像素。

这可能吗?我可以在我的代码中访问原始图像大小,但我无法确定我是否确保不改变宽高比?

2 个答案:

答案 0 :(得分:0)

是的,如果源图像已经足够宽,则可能。如果它不够宽,则没有足够的数据进行裁剪,如果要保持纵横比,则需要在裁剪前缩放图像。

这样的事情应该让你开始:

CropWidth=237;
AspectRatio= SourceWidth/SourceHeight; 
CropHeight = CropWidth*AspectRatio;

答案 1 :(得分:0)

要正确保持宽高比,您应该使用GCD:

function gcd(a, b) {
    return (b == 0) ? a : gcd(b, a % b);
}

然后你应该做这样的事情:

function calcRatio(objectWidth, objectHeight) {
    var ratio = gcd(objectWidth, objectHeight),
        xRatio = objectWidth / ratio,
        yRatio = objectHeight / ratio;
    return  { "x": xRatio, "y": yRatio };
}

这会得到一些物体的比例。您可以使用此信息来确定生成的图像应该有多大。

function findSize (targetHeight, xRatio, yRatio) { 
    var widthCalc = Math.round((xRatio * targetHeight) / yRatio);
    return { "width" : widthCalc, "height" : targetHeight };
} 

var test = calcRatio(1280,720),
    dimensions = findSize(400, test.x, test.y); 
    //400 is what we want the new height of the image to be

这些是你的尺寸。如果您的图像周围没有任何额外的“空间”需要考虑,那么您的工作就完成了。否则你需要处理几个案例。