CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
WmfImagePlugin.py189 linesDownload Raw Back to PIL
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
21from __future__ import annotations
22
23from typing import IO
24
25from . import Image, ImageFile
26from ._binary import i16le as word
27from ._binary import si16le as short
28from ._binary import si32le as _long
29
30_handler = None
31
32
33def register_handler(handler: ImageFile.StubHandler | None) -> None:
34    """
35    Install application-specific WMF image handler.
36
37    :param handler: Handler object.
38    """
39    global _handler
40    _handler = handler
41
42
43if hasattr(Image.core, "drawwmf"):
44    # install default handler (windows only)
45
46    class WmfHandler(ImageFile.StubHandler):
47        def open(self, im: ImageFile.StubImageFile) -> None:
48            im._mode = "RGB"
49            self.bbox = im.info["wmf_bbox"]
50
51        def load(self, im: ImageFile.StubImageFile) -> Image.Image:
52            assert im.fp is not None
53            im.fp.seek(0)  # rewind
54            return Image.frombytes(
55                "RGB",
56                im.size,
57                Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
58                "raw",
59                "BGR",
60                (im.size[0] * 3 + 3) & -4,
61                -1,
62            )
63
64    register_handler(WmfHandler())
65
66#
67# --------------------------------------------------------------------
68# Read WMF file
69
70
71def _accept(prefix: bytes) -> bool:
72    return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
73
74
75##
76# Image plugin for Windows metafiles.
77
78
79class WmfStubImageFile(ImageFile.StubImageFile):
80    format = "WMF"
81    format_description = "Windows Metafile"
82
83    def _open(self) -> None:
84        # check placeable header
85        assert self.fp is not None
86        s = self.fp.read(44)
87
88        if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
89            # placeable windows metafile
90
91            # get units per inch
92            inch = word(s, 14)
93            if inch == 0:
94                msg = "Invalid inch"
95                raise ValueError(msg)
96            self._inch: tuple[float, float] = inch, inch
97
98            # get bounding box
99            x0 = short(s, 6)
100            y0 = short(s, 8)
101            x1 = short(s, 10)
102            y1 = short(s, 12)
103
104            # normalize size to 72 dots per inch
105            self.info["dpi"] = 72
106            size = (
107                (x1 - x0) * self.info["dpi"] // inch,
108                (y1 - y0) * self.info["dpi"] // inch,
109            )
110
111            self.info["wmf_bbox"] = x0, y0, x1, y1
112
113            # sanity check (standard metafile header)
114            if s[22:26] != b"\x01\x00\t\x00":
115                msg = "Unsupported WMF file format"
116                raise SyntaxError(msg)
117
118        elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
119            # enhanced metafile
120
121            # get bounding box
122            x0 = _long(s, 8)
123            y0 = _long(s, 12)
124            x1 = _long(s, 16)
125            y1 = _long(s, 20)
126
127            # get frame (in 0.01 millimeter units)
128            frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
129
130            size = x1 - x0, y1 - y0
131
132            # calculate dots per inch from bbox and frame
133            xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
134            ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
135
136            self.info["wmf_bbox"] = x0, y0, x1, y1
137
138            if xdpi == ydpi:
139                self.info["dpi"] = xdpi
140            else:
141                self.info["dpi"] = xdpi, ydpi
142            self._inch = xdpi, ydpi
143
144        else:
145            msg = "Unsupported file format"
146            raise SyntaxError(msg)
147
148        self._mode = "RGB"
149        self._size = size
150
151        loader = self._load()
152        if loader:
153            loader.open(self)
154
155    def _load(self) -> ImageFile.StubHandler | None:
156        return _handler
157
158    def load(
159        self, dpi: float | tuple[float, float] | None = None
160    ) -> Image.core.PixelAccess | None:
161        if dpi is not None:
162            self.info["dpi"] = dpi
163            x0, y0, x1, y1 = self.info["wmf_bbox"]
164            if not isinstance(dpi, tuple):
165                dpi = dpi, dpi
166            self._size = (
167                int((x1 - x0) * dpi[0] / self._inch[0]),
168                int((y1 - y0) * dpi[1] / self._inch[1]),
169            )
170        return super().load()
171
172
173def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
174    if _handler is None or not hasattr(_handler, "save"):
175        msg = "WMF save handler not installed"
176        raise OSError(msg)
177    _handler.save(im, fp, filename)
178
179
180#
181# --------------------------------------------------------------------
182# Registry stuff
183
184
185Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
186Image.register_save(WmfStubImageFile.format, _save)
187
188Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])
189 
Aluode/PerceptionLabPortable · CoolFace