You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

129 lines
3.0 KiB

4 years ago
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # XPM File handling
  6. #
  7. # History:
  8. # 1996-12-29 fl Created
  9. # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
  10. #
  11. # Copyright (c) Secret Labs AB 1997-2001.
  12. # Copyright (c) Fredrik Lundh 1996-2001.
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. import re
  17. from . import Image, ImageFile, ImagePalette
  18. from ._binary import i8, o8
  19. __version__ = "0.2"
  20. # XPM header
  21. xpm_head = re.compile(b"\"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)")
  22. def _accept(prefix):
  23. return prefix[:9] == b"/* XPM */"
  24. ##
  25. # Image plugin for X11 pixel maps.
  26. class XpmImageFile(ImageFile.ImageFile):
  27. format = "XPM"
  28. format_description = "X11 Pixel Map"
  29. def _open(self):
  30. if not _accept(self.fp.read(9)):
  31. raise SyntaxError("not an XPM file")
  32. # skip forward to next string
  33. while True:
  34. s = self.fp.readline()
  35. if not s:
  36. raise SyntaxError("broken XPM file")
  37. m = xpm_head.match(s)
  38. if m:
  39. break
  40. self._size = int(m.group(1)), int(m.group(2))
  41. pal = int(m.group(3))
  42. bpp = int(m.group(4))
  43. if pal > 256 or bpp != 1:
  44. raise ValueError("cannot read this XPM file")
  45. #
  46. # load palette description
  47. palette = [b"\0\0\0"] * 256
  48. for i in range(pal):
  49. s = self.fp.readline()
  50. if s[-2:] == b'\r\n':
  51. s = s[:-2]
  52. elif s[-1:] in b'\r\n':
  53. s = s[:-1]
  54. c = i8(s[1])
  55. s = s[2:-2].split()
  56. for i in range(0, len(s), 2):
  57. if s[i] == b"c":
  58. # process colour key
  59. rgb = s[i+1]
  60. if rgb == b"None":
  61. self.info["transparency"] = c
  62. elif rgb[0:1] == b"#":
  63. # FIXME: handle colour names (see ImagePalette.py)
  64. rgb = int(rgb[1:], 16)
  65. palette[c] = (o8((rgb >> 16) & 255) +
  66. o8((rgb >> 8) & 255) +
  67. o8(rgb & 255))
  68. else:
  69. # unknown colour
  70. raise ValueError("cannot read this XPM file")
  71. break
  72. else:
  73. # missing colour key
  74. raise ValueError("cannot read this XPM file")
  75. self.mode = "P"
  76. self.palette = ImagePalette.raw("RGB", b"".join(palette))
  77. self.tile = [("raw", (0, 0)+self.size, self.fp.tell(), ("P", 0, 1))]
  78. def load_read(self, bytes):
  79. #
  80. # load all image data in one chunk
  81. xsize, ysize = self.size
  82. s = [None] * ysize
  83. for i in range(ysize):
  84. s[i] = self.fp.readline()[1:xsize+1].ljust(xsize)
  85. return b"".join(s)
  86. #
  87. # Registry
  88. Image.register_open(XpmImageFile.format, XpmImageFile, _accept)
  89. Image.register_extension(XpmImageFile.format, ".xpm")
  90. Image.register_mime(XpmImageFile.format, "image/xpm")