Search code examples
javascriptimageaspect-ratio

Calculate image ratio in JavaScript. Result can be approximate to the specification


I would like to have an approximate indication of the picture ratio. The specifications are 16/9 and 3/1;

The example image i will check has the dimensions of 1281x720px;

To calculate the ratio i use this code:

const gcd = (a, b) => b ? gcd(b, a % b): a;

const aspectRatio = (width, height)  => {
    const divisor = gcd(width, height);
    return `${width / divisor}:${height / divisor}`;
};

This code works fine.

Well, is there a possibility to check if the picture is closer to 16/9 or to 3/1? An approximate indication is enough for me


Solution

  • Maybe something like this?

    const aspectRatio = (width, height)  => {
        const ratio = (width/height)-(16/9) < 0.1
                      ? '16:9'
                      : ((width/height)-(3/1) < 0.1 ? '3:1' : 'out of spec');
    
        return `${ratio}`;
    };
    
    console.log(aspectRatio(1281, 720));
    console.log(aspectRatio(606, 202));
    console.log(aspectRatio(320, 100));

    note that the "tolerance" I chose is arbitrary at 10% now, the larger the image dimensions the more inaccurate it becomes (because 10% will be a larger pixel deviation range), so you might want to consider lowering it to your liking...the code above is definitely not elegant =), but for your specific scenario it should work.

    A more "elegant" and more flexible solution would be a slightly extended version of your function, something like this:

    const aspectRatio = (width, height, tolerance = 0.1, specs = ['16:9', '3:1'])  => {
        return specs.filter((spec) => {
            if ( Math.abs((width/height)-eval(spec.replace(':', '/'))) <= tolerance ) {
                return spec;
            }
        })[0] || false;
    };
    
    console.log(aspectRatio(1281, 720));
    console.log(aspectRatio(606, 202));
    console.log(aspectRatio(320, 100));

    this would allow to specify

    • a) the tolerance level the image dimensions can deviate from the "perferct ratio"
    • b) the image ratio-specifications that are allowed