-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpng2bin.py
54 lines (42 loc) · 1.45 KB
/
png2bin.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
from PIL import Image
def write_image(image, filename):
height = image.height
width = image.width
f = open(filename, "wb")
f.write(height.to_bytes(2, byteorder='big'))
f.write(width.to_bytes(2, byteorder='big'))
img_raster = []
for i in range(height):
for j in range(width):
img_raster.extend(image.getpixel((j, i))[:3])
f.write(bytearray(img_raster))
f.close()
def read_2bytes(f):
bytes = f.read(2) # [int(f.read(1)), int(f.read(1))]
return int.from_bytes(bytes, byteorder = 'big')
def read_image(filename):
f = open(filename, "rb")
height = read_2bytes(f)
width = read_2bytes(f)
image = Image.new("RGB", (width, height))
bytes = f.read()
for i in range(height):
for j in range(width):
image.putpixel((j, i), (bytes[3*(i*width + j)+0],
bytes[3*(i*width + j)+1],
bytes[3*(i*width + j)+2]))
return image
if __name__ == '__main__':
#Write a png image to bin
image = Image.open("6x5.png")
write_image(image, "6x5.bin")
image = Image.open("3x4.png")
write_image(image, "3x4.bin")
#Read image from a bin file, save it to png
im2 = read_image("a.bin")
im3 = read_image("6x5_grad.bin")
im3.save("grad.png")
# Write multiple images from bin to png
for i in range(200):
image = read_image("img%d.bin" % i)
image.save("img%d.png" % i)