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

后端 未结 10 1549
有刺的猬
有刺的猬 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:53

    Here's a python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (ie what Kurt McKee referenced above). Should be relatively easy to transfer it to Python 2.

    import struct
    import imghdr
    
    def get_image_size(fname):
        '''Determine the image type of fhandle and return its size.
        from draco'''
        with open(fname, 'rb') as fhandle:
            head = fhandle.read(24)
            if len(head) != 24:
                return
            if imghdr.what(fname) == 'png':
                check = struct.unpack('>i', head[4:8])[0]
                if check != 0x0d0a1a0a:
                    return
                width, height = struct.unpack('>ii', head[16:24])
            elif imghdr.what(fname) == 'gif':
                width, height = struct.unpack('H', fhandle.read(2))[0] - 2
                    # We are at a SOFn block
                    fhandle.seek(1, 1)  # Skip `precision' byte.
                    height, width = struct.unpack('>HH', fhandle.read(4))
                except Exception: #IGNORE:W0703
                    return
            else:
                return
            return width, height
    

提交回复
热议问题