S
S
Sergey Ganzhela2021-09-10 12:45:41
JavaScript
Sergey Ganzhela, 2021-09-10 12:45:41

How to properly compress an image knowing the final height in pixels?

Good afternoon!
Tell me, is there a formula or a method by which you can calculate the image compression size knowing that at the output it should not exceed 200px in height
In general, how to correctly calculate the width of the output image,
The image is loaded by the user, then it should be drawn in the Canvas window? If you set the compression in the canvas,
then it does not compress correctly!
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-10
@Sergiy_Hanzhela

function calcSize(w, h, limitW, limitH) {
    if (h <= limitH && w <= limitW) {
        return [w, h];
    }
    const r = Math.min(limitW / w, limitH / h);
    return [Math.round(r * w), Math.round(r * h)];
}

const realSizes = calcSize(imgW, imgH, Infinity, 200);

Proportionally sized to fit within width and height limits

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question