-
Notifications
You must be signed in to change notification settings - Fork 13
/
encoder.py
99 lines (79 loc) · 2.53 KB
/
encoder.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import sys
import struct
import math
from PIL import Image
from io import BytesIO
class Encoder:
def __init__(self):
self.minw = 2048
self.minh = 1080
self.dep = 3
self.mode = 'RGB'
@staticmethod
def bmp_header(data):
return b"BM" \
+ struct.pack("<l", 14 + 40 + 8 + len(data)) \
+ b"\x00\x00" \
+ b"\x00\x00" \
+ b"\x3e\x00\x00\x00" \
+ b"\x28\x00\x00\x00" \
+ struct.pack("<l", len(data)) \
+ b"\x01\x00\x00\x00" \
+ b"\x01\x00" \
+ b"\x01\x00" \
+ b"\x00\x00\x00\x00" \
+ struct.pack("<l", math.ceil(len(data) / 8)) \
+ b"\x00\x00\x00\x00" \
+ b"\x00\x00\x00\x00" \
+ b"\x00\x00\x00\x00" \
+ b"\x00\x00\x00\x00" \
+ b"\x00\x00\x00\x00\xff\xff\xff\x00"
def encode_bmp(self, data):
return Encoder.bmp_header(data) + data
def decode_bmp(self, data):
return data[62:]
def encode_png(self, data):
minw = self.minw
minh = self.minh
dep = self.dep
mode = self.mode
data = struct.pack('<I', len(data)) + data
minsz = minw * minh * dep
if len(data) < minsz:
data = data + b'\0' * (minsz - len(data))
rem = len(data) % (minw * dep)
if rem != 0:
data = data + b'\0' * (minw * dep - rem)
hei = len(data) // (minw * dep)
img = Image.frombytes(mode, (minw, hei), data)
bio = BytesIO()
img.save(bio, 'png')
return bio.getvalue()
def decode_png(self, data):
img = Image.open(BytesIO(data))
data = img.tobytes()
sz = struct.unpack('<I', data[:4])[0]
data = data[4:4+sz]
return data
encode = encode_png
def decode(self, data):
if data[:4] == b'\x89PNG':
return self.decode_png(data)
elif data[:2] == b'BM':
return self.decode_bmp(data)
else: raise ValueError('unknown format')
def main():
op = sys.argv[1]
if op not in ['d', 'e']: return
fname = sys.argv[2]
data = open(fname, 'rb').read()
encoder = Encoder()
if op == 'e':
data = encoder.encode(data)
fname = fname + '.png'
else:
data = encoder.decode(data)
fname = fname + '.data'
with open(fname, 'wb') as f:
f.write(data)
if __name__ == '__main__': main()