AljoSt AljoSt - 1 year ago 108
Python Question

Read number of significant bits of .png?

I have a set of 16bit pngs-files, recorded with LabVIEW. For some reason I need to bitshift them to use them. And for this, I need the number of significant bits. How can I read those using Python? In Matlab, there is a method called imfinfo which returns the significant bits.

Answer Source

As suggested by @Glen Randers-Pehrson, I just read the sBIT chunk:

import struct
import binascii

def __header(bytes):
    return struct.unpack('>NNccccc', bytes)

def __getSBit(bytes):
    bytes = bytes[8:]

    sBit = 0

    while bytes:
        length = struct.unpack('>I', bytes[:4])[0]
        bytes = bytes[4:]

        chunk_type = bytes[:4]

        bytes = bytes[4:]

        chunk_data = bytes[:length]
        bytes = bytes[length:]

        if chunk_type == "sBIT":
            sBit = int(chunk_data.encode("hex"), 16)

        bytes = bytes[4:]

    return sBit

def getSigniticantBits(filename):
    with open(filename, 'rb') as f:
        bytes =

    return __getSBit(bytes)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download