| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
import struct |
| 21 |
import sys |
| 22 |
from io import BytesIO |
| 23 |
|
| 24 |
|
| 25 |
try: |
| 26 |
basestring |
| 27 |
except NameError: |
| 28 |
basestring = str |
| 29 |
|
| 30 |
|
| 31 |
class PNG: |
| 32 |
|
| 33 |
signature = bytearray ((137,80,78,71,13,10,26,10)) |
| 34 |
|
| 35 |
def __init__ (self, f): |
| 36 |
|
| 37 |
if isinstance(f, basestring): |
| 38 |
f = open (f, 'rb') |
| 39 |
|
| 40 |
self.f = f |
| 41 |
self.IHDR = None |
| 42 |
|
| 43 |
def tell (self): |
| 44 |
return self.f.tell () |
| 45 |
|
| 46 |
def seek (self, pos): |
| 47 |
self.f.seek (pos) |
| 48 |
|
| 49 |
def stream (self): |
| 50 |
return self.f |
| 51 |
|
| 52 |
def data (self): |
| 53 |
self.seek (0) |
| 54 |
return bytearray (self.f.read ()) |
| 55 |
|
| 56 |
class BadSignature (Exception): pass |
| 57 |
class BadChunk (Exception): pass |
| 58 |
|
| 59 |
def read_signature (self): |
| 60 |
header = bytearray (self.f.read (8)) |
| 61 |
if header != PNG.signature: |
| 62 |
raise PNG.BadSignature |
| 63 |
return PNG.signature |
| 64 |
|
| 65 |
def read_chunk (self): |
| 66 |
buf = self.f.read (4) |
| 67 |
length = struct.unpack (">I", buf)[0] |
| 68 |
chunk_type = self.f.read (4) |
| 69 |
chunk_data = self.f.read (length) |
| 70 |
if len (chunk_data) != length: |
| 71 |
raise PNG.BadChunk |
| 72 |
crc = self.f.read (4) |
| 73 |
if len (crc) != 4: |
| 74 |
raise PNG.BadChunk |
| 75 |
return (chunk_type, chunk_data, crc) |
| 76 |
|
| 77 |
def read_IHDR (self): |
| 78 |
(chunk_type, chunk_data, crc) = self.read_chunk () |
| 79 |
if chunk_type != b"IHDR": |
| 80 |
raise PNG.BadChunk |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
return struct.unpack (">IIBBBBB", chunk_data) |
| 89 |
|
| 90 |
def read_header (self): |
| 91 |
self.read_signature () |
| 92 |
self.IHDR = self.read_IHDR () |
| 93 |
return self.IHDR |
| 94 |
|
| 95 |
def get_size (self): |
| 96 |
if not self.IHDR: |
| 97 |
pos = self.tell () |
| 98 |
self.seek (0) |
| 99 |
self.read_header () |
| 100 |
self.seek (pos) |
| 101 |
return self.IHDR[0:2] |
| 102 |
|
| 103 |
def filter_chunks (self, chunks): |
| 104 |
self.seek (0); |
| 105 |
out = BytesIO () |
| 106 |
out.write (self.read_signature ()) |
| 107 |
while True: |
| 108 |
chunk_type, chunk_data, crc = self.read_chunk () |
| 109 |
if chunk_type in chunks: |
| 110 |
out.write (struct.pack (">I", len (chunk_data))) |
| 111 |
out.write (chunk_type) |
| 112 |
out.write (chunk_data) |
| 113 |
out.write (crc) |
| 114 |
if chunk_type == b"IEND": |
| 115 |
break |
| 116 |
return PNG (out) |