# Identifies APNGs # Written by Foone/Popcorn Mariachi#!9i78bPeIxI # This code is in the public domain # identify_png returns: # '?' for non-png or corrupt PNG # 'png' for a standard png # 'apng' for an APNG # takes one argument, a file handle. When the function reutrns it'll be positioned at the start of the file # usage: # fop=open('tempfile.dat','rb') # type=identify_png(fop) import struct PNG_SIGNATURE='\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' def identify_png(file): data=file.read(8) if data!=PNG_SIGNATURE: return '?' # not a PNG/APNG try: while 1: buffer=file.read(8) if len(buffer)!=8: return '?' # Early EOF length,type=struct.unpack('!L4s',buffer) if type in ('IDAT','IEND'): # acTL must come before IDAT, so if we see an IDAT this is plain PNG # IEND is end of file. return 'png' if type=='acTL': return 'apng' file.seek(length+4,1) # +4 because of the CRC (not checked) finally: file.seek(0)