首页 文章

保持纵横比

提问于
浏览
0

我目前正在研究一种图像裁剪工具,图像裁剪工具来自jCrop,我想要的是使用户拍摄的图像小于上传的原始图像 . 基本上如果上传风景图像,我需要使图像宽304px而不改变镜头的宽高比 .

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

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

2 回答

  • 0

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

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

    CropWidth=237;
    AspectRatio= SourceWidth/SourceHeight; 
    CropHeight = CropWidth*AspectRatio;
    
  • 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
    

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

相关问题