GimpPaletteFile.py 1.3 KB

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