Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImagePalette.py 8.0KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # image palette object
  6. #
  7. # History:
  8. # 1996-03-11 fl Rewritten.
  9. # 1997-01-03 fl Up and running.
  10. # 1997-08-23 fl Added load hack
  11. # 2001-04-16 fl Fixed randint shadow bug in random()
  12. #
  13. # Copyright (c) 1997-2001 by Secret Labs AB
  14. # Copyright (c) 1996-1997 by Fredrik Lundh
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. import array
  19. from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
  20. from ._deprecate import deprecate
  21. class ImagePalette:
  22. """
  23. Color palette for palette mapped images
  24. :param mode: The mode to use for the palette. See:
  25. :ref:`concept-modes`. Defaults to "RGB"
  26. :param palette: An optional palette. If given, it must be a bytearray,
  27. an array or a list of ints between 0-255. The list must consist of
  28. all channels for one color followed by the next color (e.g. RGBRGBRGB).
  29. Defaults to an empty palette.
  30. """
  31. def __init__(self, mode="RGB", palette=None, size=0):
  32. self.mode = mode
  33. self.rawmode = None # if set, palette contains raw data
  34. self.palette = palette or bytearray()
  35. self.dirty = None
  36. if size != 0:
  37. deprecate("The size parameter", 10, None)
  38. if size != len(self.palette):
  39. msg = "wrong palette size"
  40. raise ValueError(msg)
  41. @property
  42. def palette(self):
  43. return self._palette
  44. @palette.setter
  45. def palette(self, palette):
  46. self._colors = None
  47. self._palette = palette
  48. @property
  49. def colors(self):
  50. if self._colors is None:
  51. mode_len = len(self.mode)
  52. self._colors = {}
  53. for i in range(0, len(self.palette), mode_len):
  54. color = tuple(self.palette[i : i + mode_len])
  55. if color in self._colors:
  56. continue
  57. self._colors[color] = i // mode_len
  58. return self._colors
  59. @colors.setter
  60. def colors(self, colors):
  61. self._colors = colors
  62. def copy(self):
  63. new = ImagePalette()
  64. new.mode = self.mode
  65. new.rawmode = self.rawmode
  66. if self.palette is not None:
  67. new.palette = self.palette[:]
  68. new.dirty = self.dirty
  69. return new
  70. def getdata(self):
  71. """
  72. Get palette contents in format suitable for the low-level
  73. ``im.putpalette`` primitive.
  74. .. warning:: This method is experimental.
  75. """
  76. if self.rawmode:
  77. return self.rawmode, self.palette
  78. return self.mode, self.tobytes()
  79. def tobytes(self):
  80. """Convert palette to bytes.
  81. .. warning:: This method is experimental.
  82. """
  83. if self.rawmode:
  84. msg = "palette contains raw palette data"
  85. raise ValueError(msg)
  86. if isinstance(self.palette, bytes):
  87. return self.palette
  88. arr = array.array("B", self.palette)
  89. return arr.tobytes()
  90. # Declare tostring as an alias for tobytes
  91. tostring = tobytes
  92. def getcolor(self, color, image=None):
  93. """Given an rgb tuple, allocate palette entry.
  94. .. warning:: This method is experimental.
  95. """
  96. if self.rawmode:
  97. msg = "palette contains raw palette data"
  98. raise ValueError(msg)
  99. if isinstance(color, tuple):
  100. if self.mode == "RGB":
  101. if len(color) == 4:
  102. if color[3] != 255:
  103. msg = "cannot add non-opaque RGBA color to RGB palette"
  104. raise ValueError(msg)
  105. color = color[:3]
  106. elif self.mode == "RGBA":
  107. if len(color) == 3:
  108. color += (255,)
  109. try:
  110. return self.colors[color]
  111. except KeyError as e:
  112. # allocate new color slot
  113. if not isinstance(self.palette, bytearray):
  114. self._palette = bytearray(self.palette)
  115. index = len(self.palette) // 3
  116. special_colors = ()
  117. if image:
  118. special_colors = (
  119. image.info.get("background"),
  120. image.info.get("transparency"),
  121. )
  122. while index in special_colors:
  123. index += 1
  124. if index >= 256:
  125. if image:
  126. # Search for an unused index
  127. for i, count in reversed(list(enumerate(image.histogram()))):
  128. if count == 0 and i not in special_colors:
  129. index = i
  130. break
  131. if index >= 256:
  132. msg = "cannot allocate more than 256 colors"
  133. raise ValueError(msg) from e
  134. self.colors[color] = index
  135. if index * 3 < len(self.palette):
  136. self._palette = (
  137. self.palette[: index * 3]
  138. + bytes(color)
  139. + self.palette[index * 3 + 3 :]
  140. )
  141. else:
  142. self._palette += bytes(color)
  143. self.dirty = 1
  144. return index
  145. else:
  146. msg = f"unknown color specifier: {repr(color)}"
  147. raise ValueError(msg)
  148. def save(self, fp):
  149. """Save palette to text file.
  150. .. warning:: This method is experimental.
  151. """
  152. if self.rawmode:
  153. msg = "palette contains raw palette data"
  154. raise ValueError(msg)
  155. if isinstance(fp, str):
  156. fp = open(fp, "w")
  157. fp.write("# Palette\n")
  158. fp.write(f"# Mode: {self.mode}\n")
  159. for i in range(256):
  160. fp.write(f"{i}")
  161. for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
  162. try:
  163. fp.write(f" {self.palette[j]}")
  164. except IndexError:
  165. fp.write(" 0")
  166. fp.write("\n")
  167. fp.close()
  168. # --------------------------------------------------------------------
  169. # Internal
  170. def raw(rawmode, data):
  171. palette = ImagePalette()
  172. palette.rawmode = rawmode
  173. palette.palette = data
  174. palette.dirty = 1
  175. return palette
  176. # --------------------------------------------------------------------
  177. # Factories
  178. def make_linear_lut(black, white):
  179. lut = []
  180. if black == 0:
  181. for i in range(256):
  182. lut.append(white * i // 255)
  183. else:
  184. raise NotImplementedError # FIXME
  185. return lut
  186. def make_gamma_lut(exp):
  187. lut = []
  188. for i in range(256):
  189. lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5))
  190. return lut
  191. def negative(mode="RGB"):
  192. palette = list(range(256 * len(mode)))
  193. palette.reverse()
  194. return ImagePalette(mode, [i // len(mode) for i in palette])
  195. def random(mode="RGB"):
  196. from random import randint
  197. palette = []
  198. for i in range(256 * len(mode)):
  199. palette.append(randint(0, 255))
  200. return ImagePalette(mode, palette)
  201. def sepia(white="#fff0c0"):
  202. bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
  203. return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
  204. def wedge(mode="RGB"):
  205. palette = list(range(256 * len(mode)))
  206. return ImagePalette(mode, [i // len(mode) for i in palette])
  207. def load(filename):
  208. # FIXME: supports GIMP gradients only
  209. with open(filename, "rb") as fp:
  210. for paletteHandler in [
  211. GimpPaletteFile.GimpPaletteFile,
  212. GimpGradientFile.GimpGradientFile,
  213. PaletteFile.PaletteFile,
  214. ]:
  215. try:
  216. fp.seek(0)
  217. lut = paletteHandler(fp).getpalette()
  218. if lut:
  219. break
  220. except (SyntaxError, ValueError):
  221. # import traceback
  222. # traceback.print_exc()
  223. pass
  224. else:
  225. msg = "cannot load palette"
  226. raise OSError(msg)
  227. return lut # data, rawmode