GimpPaletteFile.py 1.2 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. raise SyntaxError("not a GIMP palette file")
  25. for i in range(256):
  26. s = fp.readline()
  27. if not s:
  28. break
  29. # skip fields and comment lines
  30. if re.match(br"\w+:|#", s):
  31. continue
  32. if len(s) > 100:
  33. raise SyntaxError("bad palette file")
  34. v = tuple(map(int, s.split()[:3]))
  35. if len(v) != 3:
  36. raise ValueError("bad palette entry")
  37. self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
  38. self.palette = b"".join(self.palette)
  39. def getpalette(self):
  40. return self.palette, self.rawmode