icon.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import logging
  2. import subprocess
  3. import io
  4. ICONS_SUPPORTED_FORMATS = ["png"]
  5. class Image:
  6. def __init__(self, width: int, height: int, data: bytes):
  7. self.width = width
  8. self.height = height
  9. self.data = data
  10. def write(self, filename):
  11. with open(filename, "wb") as file:
  12. file.write(self.data)
  13. def data_as_carray(self):
  14. return (
  15. "{" + "".join("0x{:02x},".format(img_byte) for img_byte in self.data) + "}"
  16. )
  17. def is_file_an_icon(filename):
  18. extension = filename.lower().split(".")[-1]
  19. return extension in ICONS_SUPPORTED_FORMATS
  20. class ImageTools:
  21. __pil_unavailable = False
  22. __hs2_unavailable = False
  23. @staticmethod
  24. def is_processing_slow():
  25. try:
  26. return False
  27. except ImportError:
  28. return True
  29. def __init__(self):
  30. self.logger = logging.getLogger()
  31. def png2xbm(self, file):
  32. if self.__pil_unavailable:
  33. return subprocess.check_output(["convert", file, "xbm:-"])
  34. try:
  35. from PIL import Image, ImageOps
  36. except ImportError:
  37. self.__pil_unavailable = True
  38. self.logger.info("pillow module is missing, using convert cli util")
  39. return self.png2xbm(file)
  40. with Image.open(file) as im:
  41. with io.BytesIO() as output:
  42. bw = im.convert("1")
  43. bw = ImageOps.invert(bw)
  44. bw.save(output, format="XBM")
  45. return output.getvalue()
  46. def xbm2hs(self, data):
  47. if self.__hs2_unavailable:
  48. return subprocess.check_output(
  49. ["heatshrink", "-e", "-w8", "-l4"], input=data
  50. )
  51. try:
  52. import heatshrink2
  53. except ImportError:
  54. self.__hs2_unavailable = True
  55. self.logger.info("heatshrink2 module is missing, using heatshrink cli util")
  56. return self.xbm2hs(data)
  57. return heatshrink2.compress(data, window_sz2=8, lookahead_sz2=4)
  58. __tools = ImageTools()
  59. def file2image(file):
  60. output = __tools.png2xbm(file)
  61. assert output
  62. # Extract data from text
  63. f = io.StringIO(output.decode().strip())
  64. width = int(f.readline().strip().split(" ")[2])
  65. height = int(f.readline().strip().split(" ")[2])
  66. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  67. data_str = data[1:-1].replace(",", " ").replace("0x", "")
  68. data_bin = bytearray.fromhex(data_str)
  69. # Encode icon data with LZSS
  70. data_encoded_str = __tools.xbm2hs(data_bin)
  71. assert data_encoded_str
  72. data_enc = bytearray(data_encoded_str)
  73. data_enc = bytearray([len(data_enc) & 0xFF, len(data_enc) >> 8]) + data_enc
  74. # Use encoded data only if its length less than original, including header
  75. if len(data_enc) + 2 < len(data_bin) + 1:
  76. data = b"\x01\x00" + data_enc
  77. else:
  78. data = b"\x00" + data_bin
  79. return Image(width, height, data)