Converting cm to pixels in code (the passport photo gotcha)
You would think converting centimeters to pixels is a fixed conversion. It is not. It depends on DPI, and that one detail quietly breaks photo-upload forms for millions of people every year. Here is the function, and th
You would think converting centimeters to pixels is a fixed conversion. It is not. It depends on DPI, and that one detail quietly breaks photo-upload forms for millions of people every year.
Here is the function, and the gotcha.
The formula
pixels = cm / 2.54 * dpi
In JavaScript
const cmToPx = (cm, dpi = 300) => Math.round((cm / 2.54) * dpi);
cmToPx(3.5); // 413
cmToPx(4.5); // 531
In Python
def cm_to_px(cm, dpi=300):
return round(cm / 2.54 * dpi)
cm_to_px(3.5) # 413
cm_to_px(4.5) # 531
So a 3.5 x 4.5 cm passport photo is 413 x 531 px at 300 DPI. And 35 x 45 mm is the same size.
The gotcha: DPI
The same centimeters map to a different pixel count at a different DPI:
| DPI | 3.5 x 4.5 cm |
|---|---|
| 300 | 413 x 531 (print) |
| 96 | 132 x 170 (screen) |
| 72 | 99 x 128 (legacy) |
If you build any image or document tool, default to 300 DPI for print and official output. Default to a screen DPI and your users ship blurry passport photos that get rejected.
Why it matters in the real world
Passport, visa, PAN, and exam forms ask for the size in cm but upload in pixels, with no conversion shown. 413 x 531 at 300 DPI is the value that works for almost all of them.
If you just need the output and not the code, I built a browser tool that locks to 413 x 531 at 300 DPI (nothing uploaded): 3.5 x 4.5 cm resizer. Full writeup with the size table: here.
What DPI does your image pipeline default to?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.
