Advertisement
FlyFar

png2bin.py

Mar 23rd, 2023
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | Cybersecurity | 0 0
  1. import sys, math, struct, os
  2. #from io import BytesIO
  3. from PIL import Image
  4.  
  5. doscolors = [
  6.     (0x00, 0x00, 0x00), # 0
  7.     (0x00, 0x00, 0xa8), # 1
  8.     (0x00, 0xa8, 0x00), # 2
  9.     (0x00, 0xa8, 0xa8), # 3
  10.     (0xa8, 0x00, 0x00), # 4
  11.     (0xa8, 0x00, 0xa8), # 5
  12.     (0xa8, 0xa8, 0x00), # 6
  13.     (0xa8, 0xa8, 0xa8), # 7
  14.    
  15.     (0x54, 0x54, 0x54), # 8
  16.     (0x54, 0x54, 0xff), # 9
  17.     (0x54, 0xff, 0x54), # 10
  18.     (0x54, 0xff, 0xff), # 11
  19.     (0xff, 0x54, 0x54), # 12
  20.     (0xff, 0x54, 0xff), # 13
  21.     (0xff, 0xff, 0x54), # 14
  22.     (0xff, 0xff, 0xff), # 15
  23. ]
  24.  
  25. def color_distance(a, b):
  26.     return math.sqrt( (a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2 )
  27.    
  28. def nearest_color(color):
  29.     nearest = 0
  30.    
  31.     for i in range(len(doscolors)):
  32.         if color_distance(color, doscolors[i]) < color_distance(color, doscolors[nearest]):
  33.             nearest = i
  34.    
  35.     return nearest
  36.  
  37. buf = ""
  38.  
  39. for imgf in sys.argv[1:-1]:
  40.     img = Image.open(imgf).convert("RGB")
  41.     w, h = img.size
  42.    
  43.     for y in xrange(0, h, 2):
  44.         for x in xrange(w):
  45.             b = (nearest_color(img.getpixel((x, y))) << 4) | nearest_color(img.getpixel((x, y+1)))
  46.             buf += chr(b)
  47.            
  48.     img.close()
  49.  
  50. with open(sys.argv[::-1][0], "wb") as out:
  51.     out.write(buf)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement