GimpPaletteFile.py 1.8 KB

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