GimpPaletteFile.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #
  2. # Python Imaging Library
  3. # $Id$
  4. #
  5. # stuff to read GIMP palette files
  6. #
  7. # History:
  8. # 1997-08-23 fl Created
  9. # 2004-09-07 fl Support GIMP 2.0 palette files.
  10. #
  11. # Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
  12. # Copyright (c) Fredrik Lundh 1997-2004.
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. from __future__ import annotations
  17. import re
  18. from typing import IO
  19. from ._binary import o8
  20. class GimpPaletteFile:
  21. """File handler for GIMP's palette format."""
  22. rawmode = "RGB"
  23. def __init__(self, fp: IO[bytes]) -> None:
  24. palette = [o8(i) * 3 for i in range(256)]
  25. if fp.readline()[:12] != b"GIMP Palette":
  26. msg = "not a GIMP palette file"
  27. raise SyntaxError(msg)
  28. for i in range(256):
  29. s = fp.readline()
  30. if not s:
  31. break
  32. # skip fields and comment lines
  33. if re.match(rb"\w+:|#", s):
  34. continue
  35. if len(s) > 100:
  36. msg = "bad palette file"
  37. raise SyntaxError(msg)
  38. v = tuple(map(int, s.split()[:3]))
  39. if len(v) != 3:
  40. msg = "bad palette entry"
  41. raise ValueError(msg)
  42. palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
  43. self.palette = b"".join(palette)
  44. def getpalette(self) -> tuple[bytes, str]:
  45. return self.palette, self.rawmode