Getting image DPI to calculate printing size

Hi, I've recently started to build small app with Tauri. The task is to parse all image files in user selected folder and display in table information about the image (name, width in meters, height in meters, area in sq. m). The issue I'm facing is that I can't reliably get DPI info from images, which is required to convert images dimension from pixels to meters units.

I have previously written this functionality in Python and it works. Here is the code -

from PIL import Image
def calculate_area_from_file(file_path):

        # Open image and get dimensions in pixels
        image = Image.open(file_path)
        width, height = image.size

        # Extract DPI and convert to meters (default to 300 DPI if not available)
        dpi = image.info.get('dpi', (300, 300))[0]
        width_m = width / dpi * 0.0254
        height_m = height / dpi * 0.0254

        # Calculate area
        area_m2 = width_m * height_m

        return area_m2, f"File: {os.path.basename(file_path)}, Height: {height_m:.2f} m, Width: {width_m:.2f} m, " \
                        f"Area: {area_m2:.2f} m²"

I've tried using kamadak-exif to get XResolution tag, but it doesn't work with PNG format and fails to retrieve DPI in the images where Python code succeeds.

Image metadata is a messy subject — there are multiple ways it can be stored.

You could dig into the image files which fail (perhaps with a hex-dump, perhaps by writing a program using a low-level library (e.g. png), determine where and whether the image has DPI information, and then you can submit a patch to the library you'd like to succeed at the job so that it does.

For PNG in particular (I am not an expert here and there may be complications) it looks like you should ideally be able to just look at the pHYs chunk (which is not a container of EXIF data).

lodepng can read the pHYs chunk, but keep in mind that DPI of an image is an arbitrary made-up number. Any image can have any DPI it wants. Size in meters is not a property of digital files, just like weight in kilograms isn't a property of digital files. The metadata is just storing some number that someone has written there previously.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.