img_to_bin.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. from PIL import Image
  3. import sys
  4. from pathlib import Path
  5. OLED_HEIGHT = 32
  6. OLED_WIDTH = 128
  7. OLED_PAGE_HEIGHT = 8
  8. if len(sys.argv) < 2:
  9. print("No image path provided.")
  10. sys.exit()
  11. img_path = sys.argv[1]
  12. try:
  13. im = Image.open(img_path)
  14. except OSError:
  15. raise Exception("Oops! The image could not be opened.")
  16. img_width = im.size[0]
  17. img_height = im.size[1]
  18. if img_width > OLED_WIDTH or img_height > OLED_HEIGHT:
  19. print(f'Your image is {img_width} pixels wide and {img_height} pixels high, but...')
  20. raise Exception(f"OLED display only {OLED_WIDTH} pixels wide and {OLED_HEIGHT} pixels high!")
  21. # 2値化
  22. im = im.convert("L")
  23. out = im.convert("1")
  24. img_name = "ssd1306img"
  25. pixels = list(out.getdata())
  26. pixels = [0 if x == 255 else 1 for x in pixels]
  27. buffer = []
  28. for i in range(img_height // OLED_PAGE_HEIGHT):
  29. start_index = i*img_width*OLED_PAGE_HEIGHT
  30. for j in range(img_width):
  31. out_byte = 0
  32. for k in range(OLED_PAGE_HEIGHT):
  33. out_byte |= pixels[k*img_width + start_index + j] << k
  34. buffer.append(out_byte)
  35. with open(f'{img_name}.bin', 'wb') as f:
  36. f.write(bytearray(buffer))
  37. print(f"Successfully created binary file: {img_name}.bin")
  38. print(f"Image dimensions: {img_width}x{img_height}")