GimpPaletteFile.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 ._binary import o8
  19. class GimpPaletteFile:
  20. """File handler for GIMP's palette format."""
  21. rawmode = "RGB"
  22. def __init__(self, fp):
  23. self.palette = [o8(i) * 3 for i in range(256)]
  24. if fp.readline()[:12] != b"GIMP Palette":
  25. msg = "not a GIMP palette file"
  26. raise SyntaxError(msg)
  27. for i in range(256):
  28. s = fp.readline()
  29. if not s:
  30. break
  31. # skip fields and comment lines
  32. if re.match(rb"\w+:|#", s):
  33. continue
  34. if len(s) > 100:
  35. msg = "bad palette file"
  36. raise SyntaxError(msg)
  37. v = tuple(map(int, s.split()[:3]))
  38. if len(v) != 3:
  39. msg = "bad palette entry"
  40. raise ValueError(msg)
  41. self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
  42. self.palette = b"".join(self.palette)
  43. def getpalette(self):
  44. return self.palette, self.rawmode