XbmImagePlugin.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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__ is deprecated and will be removed in a future version. Use
  24. # PIL.__version__ instead.
  25. __version__ = "0.6"
  26. # XBM header
  27. xbm_head = re.compile(
  28. br"\s*#define[ \t]+.*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"
  29. b"#define[ \t]+.*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"
  30. b"(?P<hotspot>"
  31. b"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"
  32. b"#define[ \t]+[^_]*_y_hot[ \t]+(?P<yhot>[0-9]+)[\r\n]+"
  33. b")?"
  34. b"[\\000-\\377]*_bits\\[\\]"
  35. )
  36. def _accept(prefix):
  37. return prefix.lstrip()[:7] == b"#define"
  38. ##
  39. # Image plugin for X11 bitmaps.
  40. class XbmImageFile(ImageFile.ImageFile):
  41. format = "XBM"
  42. format_description = "X11 Bitmap"
  43. def _open(self):
  44. m = xbm_head.match(self.fp.read(512))
  45. if m:
  46. xsize = int(m.group("width"))
  47. ysize = int(m.group("height"))
  48. if m.group("hotspot"):
  49. self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot")))
  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")