WmfImagePlugin.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # WMF stub codec
  6. #
  7. # history:
  8. # 1996-12-14 fl Created
  9. # 2004-02-22 fl Turned into a stub driver
  10. # 2004-02-23 fl Added EMF support
  11. #
  12. # Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
  13. # Copyright (c) Fredrik Lundh 1996.
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. # WMF/EMF reference documentation:
  18. # https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf
  19. # http://wvware.sourceforge.net/caolan/index.html
  20. # http://wvware.sourceforge.net/caolan/ora-wmf.html
  21. from __future__ import annotations
  22. from typing import IO
  23. from . import Image, ImageFile
  24. from ._binary import i16le as word
  25. from ._binary import si16le as short
  26. from ._binary import si32le as _long
  27. _handler = None
  28. def register_handler(handler: ImageFile.StubHandler | None) -> None:
  29. """
  30. Install application-specific WMF image handler.
  31. :param handler: Handler object.
  32. """
  33. global _handler
  34. _handler = handler
  35. if hasattr(Image.core, "drawwmf"):
  36. # install default handler (windows only)
  37. class WmfHandler(ImageFile.StubHandler):
  38. def open(self, im: ImageFile.StubImageFile) -> None:
  39. self.bbox = im.info["wmf_bbox"]
  40. def load(self, im: ImageFile.StubImageFile) -> Image.Image:
  41. assert im.fp is not None
  42. im.fp.seek(0) # rewind
  43. return Image.frombytes(
  44. "RGB",
  45. im.size,
  46. Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
  47. "raw",
  48. "BGR",
  49. (im.size[0] * 3 + 3) & -4,
  50. -1,
  51. )
  52. register_handler(WmfHandler())
  53. #
  54. # --------------------------------------------------------------------
  55. # Read WMF file
  56. def _accept(prefix: bytes) -> bool:
  57. return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
  58. ##
  59. # Image plugin for Windows metafiles.
  60. class WmfStubImageFile(ImageFile.StubImageFile):
  61. format = "WMF"
  62. format_description = "Windows Metafile"
  63. def _open(self) -> None:
  64. # check placeable header
  65. assert self.fp is not None
  66. s = self.fp.read(44)
  67. if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
  68. # placeable windows metafile
  69. # get units per inch
  70. inch = word(s, 14)
  71. if inch == 0:
  72. msg = "Invalid inch"
  73. raise ValueError(msg)
  74. self._inch: tuple[float, float] = inch, inch
  75. # get bounding box
  76. x0 = short(s, 6)
  77. y0 = short(s, 8)
  78. x1 = short(s, 10)
  79. y1 = short(s, 12)
  80. # normalize size to 72 dots per inch
  81. self.info["dpi"] = 72
  82. size = (
  83. (x1 - x0) * self.info["dpi"] // inch,
  84. (y1 - y0) * self.info["dpi"] // inch,
  85. )
  86. self.info["wmf_bbox"] = x0, y0, x1, y1
  87. # sanity check (standard metafile header)
  88. if s[22:26] != b"\x01\x00\t\x00":
  89. msg = "Unsupported WMF file format"
  90. raise SyntaxError(msg)
  91. elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
  92. # enhanced metafile
  93. # get bounding box
  94. x0 = _long(s, 8)
  95. y0 = _long(s, 12)
  96. x1 = _long(s, 16)
  97. y1 = _long(s, 20)
  98. # get frame (in 0.01 millimeter units)
  99. frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
  100. size = x1 - x0, y1 - y0
  101. # calculate dots per inch from bbox and frame
  102. xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
  103. ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
  104. self.info["wmf_bbox"] = x0, y0, x1, y1
  105. if xdpi == ydpi:
  106. self.info["dpi"] = xdpi
  107. else:
  108. self.info["dpi"] = xdpi, ydpi
  109. self._inch = xdpi, ydpi
  110. else:
  111. msg = "Unsupported file format"
  112. raise SyntaxError(msg)
  113. self._mode = "RGB"
  114. self._size = size
  115. def _load(self) -> ImageFile.StubHandler | None:
  116. return _handler
  117. def load(
  118. self, dpi: float | tuple[float, float] | None = None
  119. ) -> Image.core.PixelAccess | None:
  120. if dpi is not None:
  121. self.info["dpi"] = dpi
  122. x0, y0, x1, y1 = self.info["wmf_bbox"]
  123. if not isinstance(dpi, tuple):
  124. dpi = dpi, dpi
  125. self._size = (
  126. int((x1 - x0) * dpi[0] / self._inch[0]),
  127. int((y1 - y0) * dpi[1] / self._inch[1]),
  128. )
  129. return super().load()
  130. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  131. if _handler is None or not hasattr(_handler, "save"):
  132. msg = "WMF save handler not installed"
  133. raise OSError(msg)
  134. _handler.save(im, fp, filename)
  135. #
  136. # --------------------------------------------------------------------
  137. # Registry stuff
  138. Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
  139. Image.register_save(WmfStubImageFile.format, _save)
  140. Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])