forked from corkami/collisions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminipng.py
62 lines (46 loc) · 1.26 KB
/
minipng.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
# png chunks reader/writer
# Ange Albertini, BSD Licence, 2011-2021
import struct
import binascii
_MAGIC = b"\x89PNG\x0d\x0a\x1a\x0a"
_crc32 = lambda d:(binascii.crc32(d) % 0x100000000)
def read(f):
"""gets a file, returns a list of [type, data] chunks"""
assert f.read(8) == _MAGIC
chunks = []
while (True):
l, = struct.unpack(">I", f.read(4))
t = f.read(4)
d = f.read(l)
assert _crc32(t + d) == struct.unpack(">I", f.read(4))[0]
chunks += [[t, d]]
if t == b"IEND":
return chunks
raise(BaseException("Invalid image"))
def make(chunks):
"""returns a PNG binary string from a list of [type, data] PNG chunks"""
s = [_MAGIC]
for t, d in chunks:
assert len(t) == 4
s += [
struct.pack(">I", len(d)),
t,
d,
struct.pack(">I", _crc32(t + d))
]
return b"".join(s)
fno = "no.png"
with open(fno, "rb") as f:
no = read(f)
fyes = "yes.png"
with open(fyes, "rb") as f:
yes = read(f)
# SPOILER
# (not entirely correct but in the right direction)
final = [
[b"aLIG", 0x33*b"\0"],
[b"cOLL", 0x71*b"\0"],
] + no + yes
with open("final.png", "wb") as f:
f.write(make(final))