How to obtain image size using standard Python class (without using external library)?

后端 未结 10 1546
有刺的猬
有刺的猬 2020-11-29 18:02

I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.

I\'ve heard PIL (Python Image Library), but it requi

10条回答
  •  无人及你
    2020-11-29 18:44

    While it's possible to call open(filename, 'rb') and check through the binary image headers for the dimensions, it seems much more useful to install PIL and spend your time writing great new software! You gain greater file format support and the reliability that comes from widespread usage. From the PIL documentation, it appears that the code you would need to complete your task would be:

    from PIL import Image
    im = Image.open('filename.png')
    print 'width: %d - height: %d' % im.size # returns (width, height) tuple
    

    As for writing code yourself, I'm not aware of a module in the Python standard library that will do what you want. You'll have to open() the image in binary mode and start decoding it yourself. You can read about the formats at:

    • PNG file format documentation
    • Notes on the JPEG file format headers

提交回复
热议问题