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.

96 lines
2.4 KiB

4 years ago
  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. __version__ = "0.6"
  24. # XBM header
  25. xbm_head = re.compile(
  26. br"\s*#define[ \t]+.*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"
  27. b"#define[ \t]+.*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"
  28. b"(?P<hotspot>"
  29. b"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"
  30. b"#define[ \t]+[^_]*_y_hot[ \t]+(?P<yhot>[0-9]+)[\r\n]+"
  31. b")?"
  32. b"[\\000-\\377]*_bits\\[\\]"
  33. )
  34. def _accept(prefix):
  35. return prefix.lstrip()[:7] == b"#define"
  36. ##
  37. # Image plugin for X11 bitmaps.
  38. class XbmImageFile(ImageFile.ImageFile):
  39. format = "XBM"
  40. format_description = "X11 Bitmap"
  41. def _open(self):
  42. m = xbm_head.match(self.fp.read(512))
  43. if m:
  44. xsize = int(m.group("width"))
  45. ysize = int(m.group("height"))
  46. if m.group("hotspot"):
  47. self.info["hotspot"] = (
  48. int(m.group("xhot")), int(m.group("yhot"))
  49. )
  50. self.mode = "1"
  51. self._size = xsize, ysize
  52. self.tile = [("xbm", (0, 0)+self.size, m.end(), None)]
  53. def _save(im, fp, filename):
  54. if im.mode != "1":
  55. raise IOError("cannot write mode %s as XBM" % im.mode)
  56. fp.write(("#define im_width %d\n" % im.size[0]).encode('ascii'))
  57. fp.write(("#define im_height %d\n" % im.size[1]).encode('ascii'))
  58. hotspot = im.encoderinfo.get("hotspot")
  59. if hotspot:
  60. fp.write(("#define im_x_hot %d\n" % hotspot[0]).encode('ascii'))
  61. fp.write(("#define im_y_hot %d\n" % hotspot[1]).encode('ascii'))
  62. fp.write(b"static char im_bits[] = {\n")
  63. ImageFile._save(im, fp, [("xbm", (0, 0)+im.size, 0, None)])
  64. fp.write(b"};\n")
  65. Image.register_open(XbmImageFile.format, XbmImageFile, _accept)
  66. Image.register_save(XbmImageFile.format, _save)
  67. Image.register_extension(XbmImageFile.format, ".xbm")
  68. Image.register_mime(XbmImageFile.format, "image/xbm")