GimpPaletteFile.py 1.8 KB

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