icon.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import logging
  2. import argparse
  3. import subprocess
  4. import io
  5. import os
  6. import sys
  7. ICONS_SUPPORTED_FORMATS = ["png"]
  8. class Image:
  9. def __init__(self, width: int, height: int, data: bytes):
  10. self.width = width
  11. self.height = height
  12. self.data = data
  13. def write(self, filename):
  14. file = open(filename, "wb")
  15. file.write(self.data)
  16. def is_file_an_icon(filename):
  17. extension = filename.lower().split(".")[-1]
  18. return extension in ICONS_SUPPORTED_FORMATS
  19. def file2image(file):
  20. output = subprocess.check_output(["convert", file, "xbm:-"])
  21. assert output
  22. # Extract data from text
  23. f = io.StringIO(output.decode().strip())
  24. width = int(f.readline().strip().split(" ")[2])
  25. height = int(f.readline().strip().split(" ")[2])
  26. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  27. data_str = data[1:-1].replace(",", " ").replace("0x", "")
  28. data_bin = bytearray.fromhex(data_str)
  29. # Encode icon data with LZSS
  30. data_encoded_str = subprocess.check_output(
  31. ["heatshrink", "-e", "-w8", "-l4"], input=data_bin
  32. )
  33. assert data_encoded_str
  34. data_enc = bytearray(data_encoded_str)
  35. data_enc = bytearray([len(data_enc) & 0xFF, len(data_enc) >> 8]) + data_enc
  36. # Use encoded data only if its lenght less than original, including header
  37. if len(data_enc) < len(data_bin) + 1:
  38. data = b"\x01\x00" + data_enc
  39. else:
  40. data = b"\x00" + data_bin
  41. return Image(width, height, data)