WmfImagePlugin.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. __lazy_modules__ = {"PIL._binary"}
  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. TYPE_CHECKING = False
  28. if TYPE_CHECKING:
  29. from typing import IO
  30. #
  31. # --------------------------------------------------------------------
  32. # Read WMF file
  33. def _accept(prefix: bytes) -> bool:
  34. return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
  35. ##
  36. # Image plugin for Windows metafiles.
  37. class WmfStubImageFile(ImageFile.StubImageFile):
  38. format = "WMF"
  39. format_description = "Windows Metafile"
  40. def _open(self) -> None:
  41. # check placeable header
  42. assert self.fp is not None
  43. s = self.fp.read(44)
  44. if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
  45. # placeable Windows metafile
  46. # get units per inch
  47. inch = word(s, 14)
  48. if inch == 0:
  49. msg = "Invalid inch"
  50. raise ValueError(msg)
  51. self._inch: tuple[float, float] = inch, inch
  52. # get bounding box
  53. x0 = short(s, 6)
  54. y0 = short(s, 8)
  55. x1 = short(s, 10)
  56. y1 = short(s, 12)
  57. # normalize size to 72 dots per inch
  58. self.info["dpi"] = 72
  59. size = (
  60. (x1 - x0) * self.info["dpi"] // inch,
  61. (y1 - y0) * self.info["dpi"] // inch,
  62. )
  63. self.info["wmf_bbox"] = x0, y0, x1, y1
  64. # sanity check (standard metafile header)
  65. if s[22:26] != b"\x01\x00\t\x00":
  66. msg = "Unsupported WMF file format"
  67. raise SyntaxError(msg)
  68. elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
  69. # enhanced metafile
  70. # get bounding box
  71. x0 = _long(s, 8)
  72. y0 = _long(s, 12)
  73. x1 = _long(s, 16)
  74. y1 = _long(s, 20)
  75. # get frame (in 0.01 millimeter units)
  76. frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
  77. size = x1 - x0, y1 - y0
  78. # calculate dots per inch from bbox and frame
  79. xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
  80. ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
  81. self.info["wmf_bbox"] = x0, y0, x1, y1
  82. if xdpi == ydpi:
  83. self.info["dpi"] = xdpi
  84. else:
  85. self.info["dpi"] = xdpi, ydpi
  86. self._inch = xdpi, ydpi
  87. else:
  88. msg = "Unsupported file format"
  89. raise SyntaxError(msg)
  90. self._mode = "RGB"
  91. self._size = size
  92. def load(
  93. self, dpi: float | tuple[float, float] | None = None
  94. ) -> Image.core.PixelAccess | None:
  95. if dpi is not None:
  96. xy_dpi = dpi if isinstance(dpi, tuple) else (dpi, dpi)
  97. if any(v < 0 for v in xy_dpi):
  98. msg = "DPI must be non-negative"
  99. raise ValueError(msg)
  100. self.info["dpi"] = dpi
  101. x0, y0, x1, y1 = self.info["wmf_bbox"]
  102. self._size = (
  103. int((x1 - x0) * xy_dpi[0] / self._inch[0]),
  104. int((y1 - y0) * xy_dpi[1] / self._inch[1]),
  105. )
  106. Image._decompression_bomb_check(self.size)
  107. return super().load()
  108. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  109. if WmfStubImageFile._handler is None or not hasattr(
  110. WmfStubImageFile._handler, "save"
  111. ):
  112. msg = "WMF save handler not installed"
  113. raise OSError(msg)
  114. WmfStubImageFile._handler.save(im, fp, filename)
  115. def register_handler(handler: ImageFile.StubHandler | None) -> None:
  116. """
  117. Install application-specific WMF image handler.
  118. :param handler: Handler object.
  119. """
  120. WmfStubImageFile._handler = handler
  121. if hasattr(Image.core, "drawwmf"):
  122. # install default handler (Windows only)
  123. class WmfHandler(ImageFile.StubHandler):
  124. def open(self, im: ImageFile.StubImageFile) -> None:
  125. self.bbox = im.info["wmf_bbox"]
  126. def load(self, im: ImageFile.StubImageFile) -> Image.Image:
  127. if min(im.size) == 0:
  128. return Image.new("RGB", im.size)
  129. assert im.fp is not None
  130. im.fp.seek(0) # rewind
  131. return Image.frombytes(
  132. "RGB",
  133. im.size,
  134. Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
  135. "raw",
  136. "BGR",
  137. (im.size[0] * 3 + 3) & -4,
  138. -1,
  139. )
  140. register_handler(WmfHandler())
  141. #
  142. # --------------------------------------------------------------------
  143. # Registry stuff
  144. Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
  145. Image.register_save(WmfStubImageFile.format, _save)
  146. Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])