pythonpython-imaging-library

Use Python to find the resolution of image with any image file extension without using any non-default library


How can I find the resolution of an image with any extension without using any module that is not part of Python's standard library (except perhaps PIL)?


Solution

  • You can get an image's resolution with the Pillow package:

    from PIL import Image
    
    with Image.open("filename") as image:
        width, height = image.size
    

    You can find more in the documentation

    As pippo1980 pointed out, this is for the dimensions of the image and not for the image's resolution. For completeness, here's how to get an image's resolution:

    from PIL import Image
    
    with Image.open("filename") as image:
        xres, yres = image.info['dpi']
    

    If the info dictionary doesn't have a dpi key, it's likely because the image is missing metadata required to calculate that (pixels per inch, or something similar relating unit/distance)