Debian Codegraph @

third_party/color_emoji/png.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright 2013 Google, Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # Google Author(s): Behdad Esfahbod
18 #
19
20 import struct
21 import sys
22 from io import BytesIO
23
24
25 try:
26 basestring # py2
27 except NameError:
28 basestring = str # py3
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 # Width: 4 bytes
82 # Height: 4 bytes
83 # Bit depth: 1 byte
84 # Color type: 1 byte
85 # Compression method: 1 byte
86 # Filter method: 1 byte
87 # Interlace method: 1 byte
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)