Skip to content

Instantly share code, notes, and snippets.

@sfan5 sfan5/readpng.py
Created Jun 7, 2013

Embed
What would you like to do?
Reads a .png file and outputs its sections
#!/usr/bin/env python2
import sys, binascii, struct
def islower(c):
return (c.upper() != c)
def countin(s, c):
i = 0
for b in s:
if b == c:
i += 1
return i
if len(sys.argv) < 2:
print("Usage: %s <png file>" % sys.argv[0])
else:
try:
f = open(sys.argv[1], "rb")
except Exception as e:
print(repr(e))
exit(1)
si = "\x89PNG\r\n\x1a\n"
if f.read(len(si)) != si:
print("Not a PNG file")
f.close()
exit(1)
print("Name\tFlags\t\t\t\tLength\tStored CRC\tComputed CRC\tCRC Status")
while True:
chklen = f.read(4)
if chklen == "" or chklen == "\0\0\0\0":
f.close()
exit(0)
chklen = struct.unpack("!L", chklen)[0]
chktype = f.read(4)
chkdata = f.read(chklen)
chkcrc = f.read(4)
realcrc = struct.pack("!L", binascii.crc32(chktype + chkdata) & 0xffffffff)
del chkdata
ancillary_bit = islower(chktype[0])
private_bit = islower(chktype[1])
reserved_bit = islower(chktype[2])
safe_to_copy_bit = islower(chktype[3])
bits = ""
if ancillary_bit:
bits += "Ancillary "
if private_bit:
bits += "Private "
if reserved_bit:
bits += "Reserved "
if safe_to_copy_bit:
bits += "Safe-to-copy "
crcstatus = "Good"
if chkcrc != realcrc:
crcstatus = "Bad"
print("%s\t%s%s%lu\t%s\t%s\t%s" % (chktype, bits, '\t'*(4-countin(bits, " ")), chklen, binascii.b2a_hex(chkcrc), binascii.b2a_hex(realcrc), crcstatus))
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.