IconManager.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from PIL import Image
  2. import os, hashlib
  3. class IconManager:
  4. def __init__(self, icon_index = 0, image_dir = "images"):
  5. self.icon_index = icon_index
  6. self.image_index = -1 if not icon_index else int(icon_index / 441)
  7. self.image_array = []
  8. self.icon_hashes = []
  9. self.image_dir = image_dir
  10. # Load images if icon index is non-zero
  11. for i in range(self.image_index + 1):
  12. image = Image.open(os.path.join(self.image_dir, "icons{}.png".format(i)))
  13. self.image_array.append(image)
  14. # Get icon hashes from images
  15. for i in range(self.icon_index):
  16. x = int((i % 441) / 21) * 48
  17. y = ((i % 441) % 21) * 48
  18. image = self.image_array[int(i / 441)]
  19. subimage = image.crop((x, y, x + 48, y + 48))
  20. md5 = hashlib.md5(subimage.tobytes()).hexdigest()
  21. self.icon_hashes.append(md5)
  22. def __repr__(self):
  23. return "IconManager[{} icons]".format(self.icon_index)
  24. # Fits 441 48x48 icons per 1024x1024 image
  25. # Returns index of added icon
  26. def add_image(self, image):
  27. if image.size != (48, 48):
  28. image = image.resize((48, 48), 1)
  29. # Check stored hashes to prevent dulpicates
  30. md5 = hashlib.md5(image.tobytes()).hexdigest()
  31. if md5 in self.icon_hashes:
  32. return self.icon_hashes.index(md5)
  33. self.icon_hashes.append(md5)
  34. if self.icon_index > len(self.image_array) * 441 - 1:
  35. self.image_array.append(Image.new("RGB", (1024, 1024), "white"))
  36. self.image_index += 1
  37. x = int((self.icon_index % 441) / 21) * 48
  38. y = ((self.icon_index % 441) % 21) * 48
  39. self.image_array[self.image_index].paste(image, (x, y))
  40. self.icon_index += 1
  41. return self.icon_index - 1
  42. def save(self, path = "images"):
  43. if not os.path.exists(path):
  44. os.makedirs(path)
  45. for i, img in enumerate(self.image_array):
  46. img.save(os.path.join(path, "icons{}.png".format(i)), optimize=True)
  47. img.save(os.path.join(path, "icons{}.jpg".format(i)), quality=85, optimize=True)