I'm implementing a graphic related web app and I want to detect the image resolution and validate if the user is uploading an image with too low DPI
How can I achieve this?
Most modern file uploaders will give you access to image dimensions, or you can use a filereader to load the image into a hidden dom image object and get the sizes that way. Example in this SO question.
But they will not tell you if the image is suitable for your intended use. You have to do some math yourself to decide that.
To decide if an image is going to be acceptable, we need to start with the target. We need to know the final output DPI and the measured dimensions. I will look at the width only but the same calculations work for the height too. Example DPI's, for a PC screen the DPI is 96, for a decent inkjet printer it might be up to 4800 by 1200. Commercial printing ranges from 300 to 2400.
Next we need to know the target region size - in other words a measurement. I will use inches here to keep things simple.
The calculation we need to do is:
Image size dots / (target size inches * DPI)
This produces the image scaling that is needed to fit the image in the target space. If the image dot size is twice the size of the target then the scale is 0.5, if the image dot size is 3 times the target then the scale is 3.
Next we need to know the acceptable range of scaling for the image. This is arbitrary and depends on the circumstances in hand.
Let's take an example - making a business card 3.5 ins x 2 ins where we want to put an uploaded picture on the back. We are printing at 300 DPI. The user uploads an image that is 800px wide. I will ignore aspect ratio to keep it simple.
The calculation we need to complete is -