Created
June 7, 2013 22:05
-
-
Save sfan5/5732742 to your computer and use it in GitHub Desktop.
Reads a .png file and outputs its sections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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