GimpPaletteFile.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 io import BytesIO
  19. from typing import IO
  20. class GimpPaletteFile:
  21. """File handler for GIMP's palette format."""
  22. rawmode = "RGB"
  23. def _read(self, fp: IO[bytes], limit: bool = True) -> None:
  24. if not fp.readline().startswith(b"GIMP Palette"):
  25. msg = "not a GIMP palette file"
  26. raise SyntaxError(msg)
  27. palette: list[int] = []
  28. i = 0
  29. while True:
  30. if limit and i == 256 + 3:
  31. break
  32. i += 1
  33. s = fp.readline()
  34. if not s:
  35. break
  36. # skip fields and comment lines
  37. if re.match(rb"\w+:|#", s):
  38. continue
  39. if limit and len(s) > 100:
  40. msg = "bad palette file"
  41. raise SyntaxError(msg)
  42. v = s.split(maxsplit=3)
  43. if len(v) < 3:
  44. msg = "bad palette entry"
  45. raise ValueError(msg)
  46. palette += (int(v[i]) for i in range(3))
  47. if limit and len(palette) == 768:
  48. break
  49. self.palette = bytes(palette)
  50. def __init__(self, fp: IO[bytes]) -> None:
  51. self._read(fp)
  52. @classmethod
  53. def frombytes(cls, data: bytes) -> GimpPaletteFile:
  54. self = cls.__new__(cls)
  55. self._read(BytesIO(data), False)
  56. return self
  57. def getpalette(self) -> tuple[bytes, str]:
  58. return self.palette, self.rawmode