icon.py 3.0 KB

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