XbmImagePlugin.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # XBM File handling
  6. #
  7. # History:
  8. # 1995-09-08 fl Created
  9. # 1996-11-01 fl Added save support
  10. # 1997-07-07 fl Made header parser more tolerant
  11. # 1997-07-22 fl Fixed yet another parser bug
  12. # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
  13. # 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog)
  14. # 2004-02-24 fl Allow some whitespace before first #define
  15. #
  16. # Copyright (c) 1997-2004 by Secret Labs AB
  17. # Copyright (c) 1996-1997 by Fredrik Lundh
  18. #
  19. # See the README file for information on usage and redistribution.
  20. #
  21. import re
  22. from . import Image, ImageFile
  23. # XBM header
  24. xbm_head = re.compile(
  25. br"\s*#define[ \t]+.*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"
  26. b"#define[ \t]+.*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"
  27. b"(?P<hotspot>"
  28. b"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"
  29. b"#define[ \t]+[^_]*_y_hot[ \t]+(?P<yhot>[0-9]+)[\r\n]+"
  30. b")?"
  31. b"[\\000-\\377]*_bits\\[\\]"
  32. )
  33. def _accept(prefix):
  34. return prefix.lstrip()[:7] == b"#define"
  35. ##
  36. # Image plugin for X11 bitmaps.
  37. class XbmImageFile(ImageFile.ImageFile):
  38. format = "XBM"
  39. format_description = "X11 Bitmap"
  40. def _open(self):
  41. m = xbm_head.match(self.fp.read(512))
  42. if m:
  43. xsize = int(m.group("width"))
  44. ysize = int(m.group("height"))
  45. if m.group("hotspot"):
  46. self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot")))
  47. self.mode = "1"
  48. self._size = xsize, ysize
  49. self.tile = [("xbm", (0, 0) + self.size, m.end(), None)]
  50. def _save(im, fp, filename):
  51. if im.mode != "1":
  52. raise OSError(f"cannot write mode {im.mode} as XBM")
  53. fp.write(f"#define im_width {im.size[0]}\n".encode("ascii"))
  54. fp.write(f"#define im_height {im.size[1]}\n".encode("ascii"))
  55. hotspot = im.encoderinfo.get("hotspot")
  56. if hotspot:
  57. fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii"))
  58. fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii"))
  59. fp.write(b"static char im_bits[] = {\n")
  60. ImageFile._save(im, fp, [("xbm", (0, 0) + im.size, 0, None)])
  61. fp.write(b"};\n")
  62. Image.register_open(XbmImageFile.format, XbmImageFile, _accept)
  63. Image.register_save(XbmImageFile.format, _save)
  64. Image.register_extension(XbmImageFile.format, ".xbm")
  65. Image.register_mime(XbmImageFile.format, "image/xbm")