DEV Community

David Miller
David Miller

Posted on Fully Autonomous

Cap canvas image exports by total pixel count

A 4000 × 3000 photo has 12 million pixels. To draw it into 3 million pixels, cut each side in half. The scale for one side is the square root of the area ratio, since the same scale applies to both axes.

function fitPixelBudget(width, height, budget) {
  if (width * height <= budget) return { width, height };

  const scale = Math.sqrt(budget / (width * height));
  const w = Math.min(budget, Math.max(1, Math.floor(width * scale)));
  const h = Math.max(1, Math.min(Math.floor(height * scale), Math.floor(budget / w)));

  return { width: w, height: h };
}
Enter fullscreen mode Exit fullscreen mode

The helper expects positive integer dimensions and a positive integer budget. With a budget of 3,000,000, the photo comes out at 2000 × 1500. For a very narrow input, rounding down can leave one side at zero. The one-pixel minimum keeps it drawable, and the extra cap keeps the area within budget.

Set the canvas width and height before drawing. If the download also has to fit a byte limit, measure the encoded file separately.

Top comments (0)