Spaces:
Paused
Paused
Upload 654 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- MLPY/Lib/site-packages/PIL/BdfFontFile.py +133 -0
- MLPY/Lib/site-packages/PIL/BlpImagePlugin.py +488 -0
- MLPY/Lib/site-packages/PIL/BmpImagePlugin.py +489 -0
- MLPY/Lib/site-packages/PIL/BufrStubImagePlugin.py +76 -0
- MLPY/Lib/site-packages/PIL/ContainerIO.py +121 -0
- MLPY/Lib/site-packages/PIL/CurImagePlugin.py +75 -0
- MLPY/Lib/site-packages/PIL/DcxImagePlugin.py +80 -0
- MLPY/Lib/site-packages/PIL/DdsImagePlugin.py +575 -0
- MLPY/Lib/site-packages/PIL/EpsImagePlugin.py +478 -0
- MLPY/Lib/site-packages/PIL/ExifTags.py +381 -0
- MLPY/Lib/site-packages/PIL/FitsImagePlugin.py +152 -0
- MLPY/Lib/site-packages/PIL/FliImagePlugin.py +174 -0
- MLPY/Lib/site-packages/PIL/FontFile.py +134 -0
- MLPY/Lib/site-packages/PIL/FpxImagePlugin.py +255 -0
- MLPY/Lib/site-packages/PIL/FtexImagePlugin.py +115 -0
- MLPY/Lib/site-packages/PIL/GbrImagePlugin.py +103 -0
- MLPY/Lib/site-packages/PIL/GdImageFile.py +102 -0
- MLPY/Lib/site-packages/PIL/GifImagePlugin.py +1159 -0
- MLPY/Lib/site-packages/PIL/GimpGradientFile.py +149 -0
- MLPY/Lib/site-packages/PIL/GimpPaletteFile.py +58 -0
- MLPY/Lib/site-packages/PIL/GribStubImagePlugin.py +76 -0
- MLPY/Lib/site-packages/PIL/Hdf5StubImagePlugin.py +76 -0
- MLPY/Lib/site-packages/PIL/IcnsImagePlugin.py +399 -0
- MLPY/Lib/site-packages/PIL/IcoImagePlugin.py +360 -0
- MLPY/Lib/site-packages/PIL/ImImagePlugin.py +374 -0
- MLPY/Lib/site-packages/PIL/Image.py +0 -0
- MLPY/Lib/site-packages/PIL/ImageChops.py +311 -0
- MLPY/Lib/site-packages/PIL/ImageCms.py +1127 -0
- MLPY/Lib/site-packages/PIL/ImageColor.py +320 -0
- MLPY/Lib/site-packages/PIL/ImageDraw.py +1206 -0
- MLPY/Lib/site-packages/PIL/ImageDraw2.py +206 -0
- MLPY/Lib/site-packages/PIL/ImageEnhance.py +107 -0
- MLPY/Lib/site-packages/PIL/ImageFile.py +810 -0
- MLPY/Lib/site-packages/PIL/ImageFilter.py +604 -0
- MLPY/Lib/site-packages/PIL/ImageFont.py +1290 -0
- MLPY/Lib/site-packages/PIL/ImageGrab.py +194 -0
- MLPY/Lib/site-packages/PIL/ImageMath.py +357 -0
- MLPY/Lib/site-packages/PIL/ImageMode.py +92 -0
- MLPY/Lib/site-packages/PIL/ImageMorph.py +265 -0
- MLPY/Lib/site-packages/PIL/ImageOps.py +728 -0
- MLPY/Lib/site-packages/PIL/ImagePalette.py +284 -0
- MLPY/Lib/site-packages/PIL/ImagePath.py +20 -0
- MLPY/Lib/site-packages/PIL/ImageQt.py +205 -0
- MLPY/Lib/site-packages/PIL/ImageSequence.py +86 -0
- MLPY/Lib/site-packages/PIL/ImageShow.py +363 -0
- MLPY/Lib/site-packages/PIL/ImageStat.py +160 -0
- MLPY/Lib/site-packages/PIL/ImageTk.py +284 -0
- MLPY/Lib/site-packages/PIL/ImageTransform.py +135 -0
- MLPY/Lib/site-packages/PIL/ImageWin.py +238 -0
.gitattributes
CHANGED
@@ -82,3 +82,5 @@ MLPY/Lib/site-packages/numpy/.libs/libopenblas.XWYDX2IKJW2NMTWSFYNGFUWKQU3LYTCZ.
|
|
82 |
MLPY/Lib/site-packages/numpy/core/_multiarray_umath.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
83 |
MLPY/Lib/site-packages/numpy/core/_simd.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
84 |
MLPY/Lib/site-packages/onnx/onnx_cpp2py_export.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
82 |
MLPY/Lib/site-packages/numpy/core/_multiarray_umath.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
83 |
MLPY/Lib/site-packages/numpy/core/_simd.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
84 |
MLPY/Lib/site-packages/onnx/onnx_cpp2py_export.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
85 |
+
MLPY/Lib/site-packages/PIL/_imaging.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
86 |
+
MLPY/Lib/site-packages/PIL/_imagingft.cp39-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
|
MLPY/Lib/site-packages/PIL/BdfFontFile.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# bitmap distribution font (bdf) file parser
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 1996-05-16 fl created (as bdf2pil)
|
9 |
+
# 1997-08-25 fl converted to FontFile driver
|
10 |
+
# 2001-05-25 fl removed bogus __init__ call
|
11 |
+
# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
|
12 |
+
# 2003-04-22 fl more robustification (from Graham Dumpleton)
|
13 |
+
#
|
14 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
15 |
+
# Copyright (c) 1997-2003 by Fredrik Lundh.
|
16 |
+
#
|
17 |
+
# See the README file for information on usage and redistribution.
|
18 |
+
#
|
19 |
+
|
20 |
+
"""
|
21 |
+
Parse X Bitmap Distribution Format (BDF)
|
22 |
+
"""
|
23 |
+
from __future__ import annotations
|
24 |
+
|
25 |
+
from typing import BinaryIO
|
26 |
+
|
27 |
+
from . import FontFile, Image
|
28 |
+
|
29 |
+
bdf_slant = {
|
30 |
+
"R": "Roman",
|
31 |
+
"I": "Italic",
|
32 |
+
"O": "Oblique",
|
33 |
+
"RI": "Reverse Italic",
|
34 |
+
"RO": "Reverse Oblique",
|
35 |
+
"OT": "Other",
|
36 |
+
}
|
37 |
+
|
38 |
+
bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
|
39 |
+
|
40 |
+
|
41 |
+
def bdf_char(
|
42 |
+
f: BinaryIO,
|
43 |
+
) -> (
|
44 |
+
tuple[
|
45 |
+
str,
|
46 |
+
int,
|
47 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
|
48 |
+
Image.Image,
|
49 |
+
]
|
50 |
+
| None
|
51 |
+
):
|
52 |
+
# skip to STARTCHAR
|
53 |
+
while True:
|
54 |
+
s = f.readline()
|
55 |
+
if not s:
|
56 |
+
return None
|
57 |
+
if s[:9] == b"STARTCHAR":
|
58 |
+
break
|
59 |
+
id = s[9:].strip().decode("ascii")
|
60 |
+
|
61 |
+
# load symbol properties
|
62 |
+
props = {}
|
63 |
+
while True:
|
64 |
+
s = f.readline()
|
65 |
+
if not s or s[:6] == b"BITMAP":
|
66 |
+
break
|
67 |
+
i = s.find(b" ")
|
68 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
69 |
+
|
70 |
+
# load bitmap
|
71 |
+
bitmap = bytearray()
|
72 |
+
while True:
|
73 |
+
s = f.readline()
|
74 |
+
if not s or s[:7] == b"ENDCHAR":
|
75 |
+
break
|
76 |
+
bitmap += s[:-1]
|
77 |
+
|
78 |
+
# The word BBX
|
79 |
+
# followed by the width in x (BBw), height in y (BBh),
|
80 |
+
# and x and y displacement (BBxoff0, BByoff0)
|
81 |
+
# of the lower left corner from the origin of the character.
|
82 |
+
width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
|
83 |
+
|
84 |
+
# The word DWIDTH
|
85 |
+
# followed by the width in x and y of the character in device pixels.
|
86 |
+
dwx, dwy = (int(p) for p in props["DWIDTH"].split())
|
87 |
+
|
88 |
+
bbox = (
|
89 |
+
(dwx, dwy),
|
90 |
+
(x_disp, -y_disp - height, width + x_disp, -y_disp),
|
91 |
+
(0, 0, width, height),
|
92 |
+
)
|
93 |
+
|
94 |
+
try:
|
95 |
+
im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
|
96 |
+
except ValueError:
|
97 |
+
# deal with zero-width characters
|
98 |
+
im = Image.new("1", (width, height))
|
99 |
+
|
100 |
+
return id, int(props["ENCODING"]), bbox, im
|
101 |
+
|
102 |
+
|
103 |
+
class BdfFontFile(FontFile.FontFile):
|
104 |
+
"""Font file plugin for the X11 BDF format."""
|
105 |
+
|
106 |
+
def __init__(self, fp: BinaryIO) -> None:
|
107 |
+
super().__init__()
|
108 |
+
|
109 |
+
s = fp.readline()
|
110 |
+
if s[:13] != b"STARTFONT 2.1":
|
111 |
+
msg = "not a valid BDF file"
|
112 |
+
raise SyntaxError(msg)
|
113 |
+
|
114 |
+
props = {}
|
115 |
+
comments = []
|
116 |
+
|
117 |
+
while True:
|
118 |
+
s = fp.readline()
|
119 |
+
if not s or s[:13] == b"ENDPROPERTIES":
|
120 |
+
break
|
121 |
+
i = s.find(b" ")
|
122 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
123 |
+
if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
|
124 |
+
if s.find(b"LogicalFontDescription") < 0:
|
125 |
+
comments.append(s[i + 1 : -1].decode("ascii"))
|
126 |
+
|
127 |
+
while True:
|
128 |
+
c = bdf_char(fp)
|
129 |
+
if not c:
|
130 |
+
break
|
131 |
+
id, ch, (xy, dst, src), im = c
|
132 |
+
if 0 <= ch < len(self.glyph):
|
133 |
+
self.glyph[ch] = xy, dst, src, im
|
MLPY/Lib/site-packages/PIL/BlpImagePlugin.py
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Blizzard Mipmap Format (.blp)
|
3 |
+
Jerome Leclanche <[email protected]>
|
4 |
+
|
5 |
+
The contents of this file are hereby released in the public domain (CC0)
|
6 |
+
Full text of the CC0 license:
|
7 |
+
https://creativecommons.org/publicdomain/zero/1.0/
|
8 |
+
|
9 |
+
BLP1 files, used mostly in Warcraft III, are not fully supported.
|
10 |
+
All types of BLP2 files used in World of Warcraft are supported.
|
11 |
+
|
12 |
+
The BLP file structure consists of a header, up to 16 mipmaps of the
|
13 |
+
texture
|
14 |
+
|
15 |
+
Texture sizes must be powers of two, though the two dimensions do
|
16 |
+
not have to be equal; 512x256 is valid, but 512x200 is not.
|
17 |
+
The first mipmap (mipmap #0) is the full size image; each subsequent
|
18 |
+
mipmap halves both dimensions. The final mipmap should be 1x1.
|
19 |
+
|
20 |
+
BLP files come in many different flavours:
|
21 |
+
* JPEG-compressed (type == 0) - only supported for BLP1.
|
22 |
+
* RAW images (type == 1, encoding == 1). Each mipmap is stored as an
|
23 |
+
array of 8-bit values, one per pixel, left to right, top to bottom.
|
24 |
+
Each value is an index to the palette.
|
25 |
+
* DXT-compressed (type == 1, encoding == 2):
|
26 |
+
- DXT1 compression is used if alpha_encoding == 0.
|
27 |
+
- An additional alpha bit is used if alpha_depth == 1.
|
28 |
+
- DXT3 compression is used if alpha_encoding == 1.
|
29 |
+
- DXT5 compression is used if alpha_encoding == 7.
|
30 |
+
"""
|
31 |
+
|
32 |
+
from __future__ import annotations
|
33 |
+
|
34 |
+
import abc
|
35 |
+
import os
|
36 |
+
import struct
|
37 |
+
from enum import IntEnum
|
38 |
+
from io import BytesIO
|
39 |
+
from typing import IO
|
40 |
+
|
41 |
+
from . import Image, ImageFile
|
42 |
+
|
43 |
+
|
44 |
+
class Format(IntEnum):
|
45 |
+
JPEG = 0
|
46 |
+
|
47 |
+
|
48 |
+
class Encoding(IntEnum):
|
49 |
+
UNCOMPRESSED = 1
|
50 |
+
DXT = 2
|
51 |
+
UNCOMPRESSED_RAW_BGRA = 3
|
52 |
+
|
53 |
+
|
54 |
+
class AlphaEncoding(IntEnum):
|
55 |
+
DXT1 = 0
|
56 |
+
DXT3 = 1
|
57 |
+
DXT5 = 7
|
58 |
+
|
59 |
+
|
60 |
+
def unpack_565(i: int) -> tuple[int, int, int]:
|
61 |
+
return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
|
62 |
+
|
63 |
+
|
64 |
+
def decode_dxt1(
|
65 |
+
data: bytes, alpha: bool = False
|
66 |
+
) -> tuple[bytearray, bytearray, bytearray, bytearray]:
|
67 |
+
"""
|
68 |
+
input: one "row" of data (i.e. will produce 4*width pixels)
|
69 |
+
"""
|
70 |
+
|
71 |
+
blocks = len(data) // 8 # number of blocks in row
|
72 |
+
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
73 |
+
|
74 |
+
for block_index in range(blocks):
|
75 |
+
# Decode next 8-byte block.
|
76 |
+
idx = block_index * 8
|
77 |
+
color0, color1, bits = struct.unpack_from("<HHI", data, idx)
|
78 |
+
|
79 |
+
r0, g0, b0 = unpack_565(color0)
|
80 |
+
r1, g1, b1 = unpack_565(color1)
|
81 |
+
|
82 |
+
# Decode this block into 4x4 pixels
|
83 |
+
# Accumulate the results onto our 4 row accumulators
|
84 |
+
for j in range(4):
|
85 |
+
for i in range(4):
|
86 |
+
# get next control op and generate a pixel
|
87 |
+
|
88 |
+
control = bits & 3
|
89 |
+
bits = bits >> 2
|
90 |
+
|
91 |
+
a = 0xFF
|
92 |
+
if control == 0:
|
93 |
+
r, g, b = r0, g0, b0
|
94 |
+
elif control == 1:
|
95 |
+
r, g, b = r1, g1, b1
|
96 |
+
elif control == 2:
|
97 |
+
if color0 > color1:
|
98 |
+
r = (2 * r0 + r1) // 3
|
99 |
+
g = (2 * g0 + g1) // 3
|
100 |
+
b = (2 * b0 + b1) // 3
|
101 |
+
else:
|
102 |
+
r = (r0 + r1) // 2
|
103 |
+
g = (g0 + g1) // 2
|
104 |
+
b = (b0 + b1) // 2
|
105 |
+
elif control == 3:
|
106 |
+
if color0 > color1:
|
107 |
+
r = (2 * r1 + r0) // 3
|
108 |
+
g = (2 * g1 + g0) // 3
|
109 |
+
b = (2 * b1 + b0) // 3
|
110 |
+
else:
|
111 |
+
r, g, b, a = 0, 0, 0, 0
|
112 |
+
|
113 |
+
if alpha:
|
114 |
+
ret[j].extend([r, g, b, a])
|
115 |
+
else:
|
116 |
+
ret[j].extend([r, g, b])
|
117 |
+
|
118 |
+
return ret
|
119 |
+
|
120 |
+
|
121 |
+
def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
|
122 |
+
"""
|
123 |
+
input: one "row" of data (i.e. will produce 4*width pixels)
|
124 |
+
"""
|
125 |
+
|
126 |
+
blocks = len(data) // 16 # number of blocks in row
|
127 |
+
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
128 |
+
|
129 |
+
for block_index in range(blocks):
|
130 |
+
idx = block_index * 16
|
131 |
+
block = data[idx : idx + 16]
|
132 |
+
# Decode next 16-byte block.
|
133 |
+
bits = struct.unpack_from("<8B", block)
|
134 |
+
color0, color1 = struct.unpack_from("<HH", block, 8)
|
135 |
+
|
136 |
+
(code,) = struct.unpack_from("<I", block, 12)
|
137 |
+
|
138 |
+
r0, g0, b0 = unpack_565(color0)
|
139 |
+
r1, g1, b1 = unpack_565(color1)
|
140 |
+
|
141 |
+
for j in range(4):
|
142 |
+
high = False # Do we want the higher bits?
|
143 |
+
for i in range(4):
|
144 |
+
alphacode_index = (4 * j + i) // 2
|
145 |
+
a = bits[alphacode_index]
|
146 |
+
if high:
|
147 |
+
high = False
|
148 |
+
a >>= 4
|
149 |
+
else:
|
150 |
+
high = True
|
151 |
+
a &= 0xF
|
152 |
+
a *= 17 # We get a value between 0 and 15
|
153 |
+
|
154 |
+
color_code = (code >> 2 * (4 * j + i)) & 0x03
|
155 |
+
|
156 |
+
if color_code == 0:
|
157 |
+
r, g, b = r0, g0, b0
|
158 |
+
elif color_code == 1:
|
159 |
+
r, g, b = r1, g1, b1
|
160 |
+
elif color_code == 2:
|
161 |
+
r = (2 * r0 + r1) // 3
|
162 |
+
g = (2 * g0 + g1) // 3
|
163 |
+
b = (2 * b0 + b1) // 3
|
164 |
+
elif color_code == 3:
|
165 |
+
r = (2 * r1 + r0) // 3
|
166 |
+
g = (2 * g1 + g0) // 3
|
167 |
+
b = (2 * b1 + b0) // 3
|
168 |
+
|
169 |
+
ret[j].extend([r, g, b, a])
|
170 |
+
|
171 |
+
return ret
|
172 |
+
|
173 |
+
|
174 |
+
def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
|
175 |
+
"""
|
176 |
+
input: one "row" of data (i.e. will produce 4 * width pixels)
|
177 |
+
"""
|
178 |
+
|
179 |
+
blocks = len(data) // 16 # number of blocks in row
|
180 |
+
ret = (bytearray(), bytearray(), bytearray(), bytearray())
|
181 |
+
|
182 |
+
for block_index in range(blocks):
|
183 |
+
idx = block_index * 16
|
184 |
+
block = data[idx : idx + 16]
|
185 |
+
# Decode next 16-byte block.
|
186 |
+
a0, a1 = struct.unpack_from("<BB", block)
|
187 |
+
|
188 |
+
bits = struct.unpack_from("<6B", block, 2)
|
189 |
+
alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
|
190 |
+
alphacode2 = bits[0] | (bits[1] << 8)
|
191 |
+
|
192 |
+
color0, color1 = struct.unpack_from("<HH", block, 8)
|
193 |
+
|
194 |
+
(code,) = struct.unpack_from("<I", block, 12)
|
195 |
+
|
196 |
+
r0, g0, b0 = unpack_565(color0)
|
197 |
+
r1, g1, b1 = unpack_565(color1)
|
198 |
+
|
199 |
+
for j in range(4):
|
200 |
+
for i in range(4):
|
201 |
+
# get next control op and generate a pixel
|
202 |
+
alphacode_index = 3 * (4 * j + i)
|
203 |
+
|
204 |
+
if alphacode_index <= 12:
|
205 |
+
alphacode = (alphacode2 >> alphacode_index) & 0x07
|
206 |
+
elif alphacode_index == 15:
|
207 |
+
alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
|
208 |
+
else: # alphacode_index >= 18 and alphacode_index <= 45
|
209 |
+
alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
|
210 |
+
|
211 |
+
if alphacode == 0:
|
212 |
+
a = a0
|
213 |
+
elif alphacode == 1:
|
214 |
+
a = a1
|
215 |
+
elif a0 > a1:
|
216 |
+
a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
|
217 |
+
elif alphacode == 6:
|
218 |
+
a = 0
|
219 |
+
elif alphacode == 7:
|
220 |
+
a = 255
|
221 |
+
else:
|
222 |
+
a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
|
223 |
+
|
224 |
+
color_code = (code >> 2 * (4 * j + i)) & 0x03
|
225 |
+
|
226 |
+
if color_code == 0:
|
227 |
+
r, g, b = r0, g0, b0
|
228 |
+
elif color_code == 1:
|
229 |
+
r, g, b = r1, g1, b1
|
230 |
+
elif color_code == 2:
|
231 |
+
r = (2 * r0 + r1) // 3
|
232 |
+
g = (2 * g0 + g1) // 3
|
233 |
+
b = (2 * b0 + b1) // 3
|
234 |
+
elif color_code == 3:
|
235 |
+
r = (2 * r1 + r0) // 3
|
236 |
+
g = (2 * g1 + g0) // 3
|
237 |
+
b = (2 * b1 + b0) // 3
|
238 |
+
|
239 |
+
ret[j].extend([r, g, b, a])
|
240 |
+
|
241 |
+
return ret
|
242 |
+
|
243 |
+
|
244 |
+
class BLPFormatError(NotImplementedError):
|
245 |
+
pass
|
246 |
+
|
247 |
+
|
248 |
+
def _accept(prefix: bytes) -> bool:
|
249 |
+
return prefix[:4] in (b"BLP1", b"BLP2")
|
250 |
+
|
251 |
+
|
252 |
+
class BlpImageFile(ImageFile.ImageFile):
|
253 |
+
"""
|
254 |
+
Blizzard Mipmap Format
|
255 |
+
"""
|
256 |
+
|
257 |
+
format = "BLP"
|
258 |
+
format_description = "Blizzard Mipmap Format"
|
259 |
+
|
260 |
+
def _open(self) -> None:
|
261 |
+
self.magic = self.fp.read(4)
|
262 |
+
|
263 |
+
self.fp.seek(5, os.SEEK_CUR)
|
264 |
+
(self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1))
|
265 |
+
|
266 |
+
self.fp.seek(2, os.SEEK_CUR)
|
267 |
+
self._size = struct.unpack("<II", self.fp.read(8))
|
268 |
+
|
269 |
+
if self.magic in (b"BLP1", b"BLP2"):
|
270 |
+
decoder = self.magic.decode()
|
271 |
+
else:
|
272 |
+
msg = f"Bad BLP magic {repr(self.magic)}"
|
273 |
+
raise BLPFormatError(msg)
|
274 |
+
|
275 |
+
self._mode = "RGBA" if self._blp_alpha_depth else "RGB"
|
276 |
+
self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
|
277 |
+
|
278 |
+
|
279 |
+
class _BLPBaseDecoder(ImageFile.PyDecoder):
|
280 |
+
_pulls_fd = True
|
281 |
+
|
282 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
283 |
+
try:
|
284 |
+
self._read_blp_header()
|
285 |
+
self._load()
|
286 |
+
except struct.error as e:
|
287 |
+
msg = "Truncated BLP file"
|
288 |
+
raise OSError(msg) from e
|
289 |
+
return -1, 0
|
290 |
+
|
291 |
+
@abc.abstractmethod
|
292 |
+
def _load(self) -> None:
|
293 |
+
pass
|
294 |
+
|
295 |
+
def _read_blp_header(self) -> None:
|
296 |
+
assert self.fd is not None
|
297 |
+
self.fd.seek(4)
|
298 |
+
(self._blp_compression,) = struct.unpack("<i", self._safe_read(4))
|
299 |
+
|
300 |
+
(self._blp_encoding,) = struct.unpack("<b", self._safe_read(1))
|
301 |
+
(self._blp_alpha_depth,) = struct.unpack("<b", self._safe_read(1))
|
302 |
+
(self._blp_alpha_encoding,) = struct.unpack("<b", self._safe_read(1))
|
303 |
+
self.fd.seek(1, os.SEEK_CUR) # mips
|
304 |
+
|
305 |
+
self.size = struct.unpack("<II", self._safe_read(8))
|
306 |
+
|
307 |
+
if isinstance(self, BLP1Decoder):
|
308 |
+
# Only present for BLP1
|
309 |
+
(self._blp_encoding,) = struct.unpack("<i", self._safe_read(4))
|
310 |
+
self.fd.seek(4, os.SEEK_CUR) # subtype
|
311 |
+
|
312 |
+
self._blp_offsets = struct.unpack("<16I", self._safe_read(16 * 4))
|
313 |
+
self._blp_lengths = struct.unpack("<16I", self._safe_read(16 * 4))
|
314 |
+
|
315 |
+
def _safe_read(self, length: int) -> bytes:
|
316 |
+
return ImageFile._safe_read(self.fd, length)
|
317 |
+
|
318 |
+
def _read_palette(self) -> list[tuple[int, int, int, int]]:
|
319 |
+
ret = []
|
320 |
+
for i in range(256):
|
321 |
+
try:
|
322 |
+
b, g, r, a = struct.unpack("<4B", self._safe_read(4))
|
323 |
+
except struct.error:
|
324 |
+
break
|
325 |
+
ret.append((b, g, r, a))
|
326 |
+
return ret
|
327 |
+
|
328 |
+
def _read_bgra(self, palette: list[tuple[int, int, int, int]]) -> bytearray:
|
329 |
+
data = bytearray()
|
330 |
+
_data = BytesIO(self._safe_read(self._blp_lengths[0]))
|
331 |
+
while True:
|
332 |
+
try:
|
333 |
+
(offset,) = struct.unpack("<B", _data.read(1))
|
334 |
+
except struct.error:
|
335 |
+
break
|
336 |
+
b, g, r, a = palette[offset]
|
337 |
+
d: tuple[int, ...] = (r, g, b)
|
338 |
+
if self._blp_alpha_depth:
|
339 |
+
d += (a,)
|
340 |
+
data.extend(d)
|
341 |
+
return data
|
342 |
+
|
343 |
+
|
344 |
+
class BLP1Decoder(_BLPBaseDecoder):
|
345 |
+
def _load(self) -> None:
|
346 |
+
if self._blp_compression == Format.JPEG:
|
347 |
+
self._decode_jpeg_stream()
|
348 |
+
|
349 |
+
elif self._blp_compression == 1:
|
350 |
+
if self._blp_encoding in (4, 5):
|
351 |
+
palette = self._read_palette()
|
352 |
+
data = self._read_bgra(palette)
|
353 |
+
self.set_as_raw(data)
|
354 |
+
else:
|
355 |
+
msg = f"Unsupported BLP encoding {repr(self._blp_encoding)}"
|
356 |
+
raise BLPFormatError(msg)
|
357 |
+
else:
|
358 |
+
msg = f"Unsupported BLP compression {repr(self._blp_encoding)}"
|
359 |
+
raise BLPFormatError(msg)
|
360 |
+
|
361 |
+
def _decode_jpeg_stream(self) -> None:
|
362 |
+
from .JpegImagePlugin import JpegImageFile
|
363 |
+
|
364 |
+
(jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
|
365 |
+
jpeg_header = self._safe_read(jpeg_header_size)
|
366 |
+
assert self.fd is not None
|
367 |
+
self._safe_read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
|
368 |
+
data = self._safe_read(self._blp_lengths[0])
|
369 |
+
data = jpeg_header + data
|
370 |
+
image = JpegImageFile(BytesIO(data))
|
371 |
+
Image._decompression_bomb_check(image.size)
|
372 |
+
if image.mode == "CMYK":
|
373 |
+
decoder_name, extents, offset, args = image.tile[0]
|
374 |
+
image.tile = [(decoder_name, extents, offset, (args[0], "CMYK"))]
|
375 |
+
r, g, b = image.convert("RGB").split()
|
376 |
+
reversed_image = Image.merge("RGB", (b, g, r))
|
377 |
+
self.set_as_raw(reversed_image.tobytes())
|
378 |
+
|
379 |
+
|
380 |
+
class BLP2Decoder(_BLPBaseDecoder):
|
381 |
+
def _load(self) -> None:
|
382 |
+
palette = self._read_palette()
|
383 |
+
|
384 |
+
assert self.fd is not None
|
385 |
+
self.fd.seek(self._blp_offsets[0])
|
386 |
+
|
387 |
+
if self._blp_compression == 1:
|
388 |
+
# Uncompressed or DirectX compression
|
389 |
+
|
390 |
+
if self._blp_encoding == Encoding.UNCOMPRESSED:
|
391 |
+
data = self._read_bgra(palette)
|
392 |
+
|
393 |
+
elif self._blp_encoding == Encoding.DXT:
|
394 |
+
data = bytearray()
|
395 |
+
if self._blp_alpha_encoding == AlphaEncoding.DXT1:
|
396 |
+
linesize = (self.size[0] + 3) // 4 * 8
|
397 |
+
for yb in range((self.size[1] + 3) // 4):
|
398 |
+
for d in decode_dxt1(
|
399 |
+
self._safe_read(linesize), alpha=bool(self._blp_alpha_depth)
|
400 |
+
):
|
401 |
+
data += d
|
402 |
+
|
403 |
+
elif self._blp_alpha_encoding == AlphaEncoding.DXT3:
|
404 |
+
linesize = (self.size[0] + 3) // 4 * 16
|
405 |
+
for yb in range((self.size[1] + 3) // 4):
|
406 |
+
for d in decode_dxt3(self._safe_read(linesize)):
|
407 |
+
data += d
|
408 |
+
|
409 |
+
elif self._blp_alpha_encoding == AlphaEncoding.DXT5:
|
410 |
+
linesize = (self.size[0] + 3) // 4 * 16
|
411 |
+
for yb in range((self.size[1] + 3) // 4):
|
412 |
+
for d in decode_dxt5(self._safe_read(linesize)):
|
413 |
+
data += d
|
414 |
+
else:
|
415 |
+
msg = f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
|
416 |
+
raise BLPFormatError(msg)
|
417 |
+
else:
|
418 |
+
msg = f"Unknown BLP encoding {repr(self._blp_encoding)}"
|
419 |
+
raise BLPFormatError(msg)
|
420 |
+
|
421 |
+
else:
|
422 |
+
msg = f"Unknown BLP compression {repr(self._blp_compression)}"
|
423 |
+
raise BLPFormatError(msg)
|
424 |
+
|
425 |
+
self.set_as_raw(data)
|
426 |
+
|
427 |
+
|
428 |
+
class BLPEncoder(ImageFile.PyEncoder):
|
429 |
+
_pushes_fd = True
|
430 |
+
|
431 |
+
def _write_palette(self) -> bytes:
|
432 |
+
data = b""
|
433 |
+
assert self.im is not None
|
434 |
+
palette = self.im.getpalette("RGBA", "RGBA")
|
435 |
+
for i in range(len(palette) // 4):
|
436 |
+
r, g, b, a = palette[i * 4 : (i + 1) * 4]
|
437 |
+
data += struct.pack("<4B", b, g, r, a)
|
438 |
+
while len(data) < 256 * 4:
|
439 |
+
data += b"\x00" * 4
|
440 |
+
return data
|
441 |
+
|
442 |
+
def encode(self, bufsize: int) -> tuple[int, int, bytes]:
|
443 |
+
palette_data = self._write_palette()
|
444 |
+
|
445 |
+
offset = 20 + 16 * 4 * 2 + len(palette_data)
|
446 |
+
data = struct.pack("<16I", offset, *((0,) * 15))
|
447 |
+
|
448 |
+
assert self.im is not None
|
449 |
+
w, h = self.im.size
|
450 |
+
data += struct.pack("<16I", w * h, *((0,) * 15))
|
451 |
+
|
452 |
+
data += palette_data
|
453 |
+
|
454 |
+
for y in range(h):
|
455 |
+
for x in range(w):
|
456 |
+
data += struct.pack("<B", self.im.getpixel((x, y)))
|
457 |
+
|
458 |
+
return len(data), 0, data
|
459 |
+
|
460 |
+
|
461 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
462 |
+
if im.mode != "P":
|
463 |
+
msg = "Unsupported BLP image mode"
|
464 |
+
raise ValueError(msg)
|
465 |
+
|
466 |
+
magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
|
467 |
+
fp.write(magic)
|
468 |
+
|
469 |
+
fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
|
470 |
+
fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
|
471 |
+
fp.write(struct.pack("<b", 1 if im.palette.mode == "RGBA" else 0))
|
472 |
+
fp.write(struct.pack("<b", 0)) # alpha encoding
|
473 |
+
fp.write(struct.pack("<b", 0)) # mips
|
474 |
+
fp.write(struct.pack("<II", *im.size))
|
475 |
+
if magic == b"BLP1":
|
476 |
+
fp.write(struct.pack("<i", 5))
|
477 |
+
fp.write(struct.pack("<i", 0))
|
478 |
+
|
479 |
+
ImageFile._save(im, fp, [("BLP", (0, 0) + im.size, 0, im.mode)])
|
480 |
+
|
481 |
+
|
482 |
+
Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
|
483 |
+
Image.register_extension(BlpImageFile.format, ".blp")
|
484 |
+
Image.register_decoder("BLP1", BLP1Decoder)
|
485 |
+
Image.register_decoder("BLP2", BLP2Decoder)
|
486 |
+
|
487 |
+
Image.register_save(BlpImageFile.format, _save)
|
488 |
+
Image.register_encoder("BLP", BLPEncoder)
|
MLPY/Lib/site-packages/PIL/BmpImagePlugin.py
ADDED
@@ -0,0 +1,489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# BMP file handler
|
6 |
+
#
|
7 |
+
# Windows (and OS/2) native bitmap storage format.
|
8 |
+
#
|
9 |
+
# history:
|
10 |
+
# 1995-09-01 fl Created
|
11 |
+
# 1996-04-30 fl Added save
|
12 |
+
# 1997-08-27 fl Fixed save of 1-bit images
|
13 |
+
# 1998-03-06 fl Load P images as L where possible
|
14 |
+
# 1998-07-03 fl Load P images as 1 where possible
|
15 |
+
# 1998-12-29 fl Handle small palettes
|
16 |
+
# 2002-12-30 fl Fixed load of 1-bit palette images
|
17 |
+
# 2003-04-21 fl Fixed load of 1-bit monochrome images
|
18 |
+
# 2003-04-23 fl Added limited support for BI_BITFIELDS compression
|
19 |
+
#
|
20 |
+
# Copyright (c) 1997-2003 by Secret Labs AB
|
21 |
+
# Copyright (c) 1995-2003 by Fredrik Lundh
|
22 |
+
#
|
23 |
+
# See the README file for information on usage and redistribution.
|
24 |
+
#
|
25 |
+
from __future__ import annotations
|
26 |
+
|
27 |
+
import os
|
28 |
+
from typing import IO
|
29 |
+
|
30 |
+
from . import Image, ImageFile, ImagePalette
|
31 |
+
from ._binary import i16le as i16
|
32 |
+
from ._binary import i32le as i32
|
33 |
+
from ._binary import o8
|
34 |
+
from ._binary import o16le as o16
|
35 |
+
from ._binary import o32le as o32
|
36 |
+
|
37 |
+
#
|
38 |
+
# --------------------------------------------------------------------
|
39 |
+
# Read BMP file
|
40 |
+
|
41 |
+
BIT2MODE = {
|
42 |
+
# bits => mode, rawmode
|
43 |
+
1: ("P", "P;1"),
|
44 |
+
4: ("P", "P;4"),
|
45 |
+
8: ("P", "P"),
|
46 |
+
16: ("RGB", "BGR;15"),
|
47 |
+
24: ("RGB", "BGR"),
|
48 |
+
32: ("RGB", "BGRX"),
|
49 |
+
}
|
50 |
+
|
51 |
+
|
52 |
+
def _accept(prefix: bytes) -> bool:
|
53 |
+
return prefix[:2] == b"BM"
|
54 |
+
|
55 |
+
|
56 |
+
def _dib_accept(prefix: bytes) -> bool:
|
57 |
+
return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
|
58 |
+
|
59 |
+
|
60 |
+
# =============================================================================
|
61 |
+
# Image plugin for the Windows BMP format.
|
62 |
+
# =============================================================================
|
63 |
+
class BmpImageFile(ImageFile.ImageFile):
|
64 |
+
"""Image plugin for the Windows Bitmap format (BMP)"""
|
65 |
+
|
66 |
+
# ------------------------------------------------------------- Description
|
67 |
+
format_description = "Windows Bitmap"
|
68 |
+
format = "BMP"
|
69 |
+
|
70 |
+
# -------------------------------------------------- BMP Compression values
|
71 |
+
COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
|
72 |
+
for k, v in COMPRESSIONS.items():
|
73 |
+
vars()[k] = v
|
74 |
+
|
75 |
+
def _bitmap(self, header=0, offset=0):
|
76 |
+
"""Read relevant info about the BMP"""
|
77 |
+
read, seek = self.fp.read, self.fp.seek
|
78 |
+
if header:
|
79 |
+
seek(header)
|
80 |
+
# read bmp header size @offset 14 (this is part of the header size)
|
81 |
+
file_info = {"header_size": i32(read(4)), "direction": -1}
|
82 |
+
|
83 |
+
# -------------------- If requested, read header at a specific position
|
84 |
+
# read the rest of the bmp header, without its size
|
85 |
+
header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
|
86 |
+
|
87 |
+
# ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
|
88 |
+
# ----- This format has different offsets because of width/height types
|
89 |
+
# 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
|
90 |
+
if file_info["header_size"] == 12:
|
91 |
+
file_info["width"] = i16(header_data, 0)
|
92 |
+
file_info["height"] = i16(header_data, 2)
|
93 |
+
file_info["planes"] = i16(header_data, 4)
|
94 |
+
file_info["bits"] = i16(header_data, 6)
|
95 |
+
file_info["compression"] = self.RAW
|
96 |
+
file_info["palette_padding"] = 3
|
97 |
+
|
98 |
+
# --------------------------------------------- Windows Bitmap v3 to v5
|
99 |
+
# 40: BITMAPINFOHEADER
|
100 |
+
# 52: BITMAPV2HEADER
|
101 |
+
# 56: BITMAPV3HEADER
|
102 |
+
# 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
|
103 |
+
# 108: BITMAPV4HEADER
|
104 |
+
# 124: BITMAPV5HEADER
|
105 |
+
elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
|
106 |
+
file_info["y_flip"] = header_data[7] == 0xFF
|
107 |
+
file_info["direction"] = 1 if file_info["y_flip"] else -1
|
108 |
+
file_info["width"] = i32(header_data, 0)
|
109 |
+
file_info["height"] = (
|
110 |
+
i32(header_data, 4)
|
111 |
+
if not file_info["y_flip"]
|
112 |
+
else 2**32 - i32(header_data, 4)
|
113 |
+
)
|
114 |
+
file_info["planes"] = i16(header_data, 8)
|
115 |
+
file_info["bits"] = i16(header_data, 10)
|
116 |
+
file_info["compression"] = i32(header_data, 12)
|
117 |
+
# byte size of pixel data
|
118 |
+
file_info["data_size"] = i32(header_data, 16)
|
119 |
+
file_info["pixels_per_meter"] = (
|
120 |
+
i32(header_data, 20),
|
121 |
+
i32(header_data, 24),
|
122 |
+
)
|
123 |
+
file_info["colors"] = i32(header_data, 28)
|
124 |
+
file_info["palette_padding"] = 4
|
125 |
+
self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
|
126 |
+
if file_info["compression"] == self.BITFIELDS:
|
127 |
+
masks = ["r_mask", "g_mask", "b_mask"]
|
128 |
+
if len(header_data) >= 48:
|
129 |
+
if len(header_data) >= 52:
|
130 |
+
masks.append("a_mask")
|
131 |
+
else:
|
132 |
+
file_info["a_mask"] = 0x0
|
133 |
+
for idx, mask in enumerate(masks):
|
134 |
+
file_info[mask] = i32(header_data, 36 + idx * 4)
|
135 |
+
else:
|
136 |
+
# 40 byte headers only have the three components in the
|
137 |
+
# bitfields masks, ref:
|
138 |
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
|
139 |
+
# See also
|
140 |
+
# https://github.com/python-pillow/Pillow/issues/1293
|
141 |
+
# There is a 4th component in the RGBQuad, in the alpha
|
142 |
+
# location, but it is listed as a reserved component,
|
143 |
+
# and it is not generally an alpha channel
|
144 |
+
file_info["a_mask"] = 0x0
|
145 |
+
for mask in masks:
|
146 |
+
file_info[mask] = i32(read(4))
|
147 |
+
file_info["rgb_mask"] = (
|
148 |
+
file_info["r_mask"],
|
149 |
+
file_info["g_mask"],
|
150 |
+
file_info["b_mask"],
|
151 |
+
)
|
152 |
+
file_info["rgba_mask"] = (
|
153 |
+
file_info["r_mask"],
|
154 |
+
file_info["g_mask"],
|
155 |
+
file_info["b_mask"],
|
156 |
+
file_info["a_mask"],
|
157 |
+
)
|
158 |
+
else:
|
159 |
+
msg = f"Unsupported BMP header type ({file_info['header_size']})"
|
160 |
+
raise OSError(msg)
|
161 |
+
|
162 |
+
# ------------------ Special case : header is reported 40, which
|
163 |
+
# ---------------------- is shorter than real size for bpp >= 16
|
164 |
+
self._size = file_info["width"], file_info["height"]
|
165 |
+
|
166 |
+
# ------- If color count was not found in the header, compute from bits
|
167 |
+
file_info["colors"] = (
|
168 |
+
file_info["colors"]
|
169 |
+
if file_info.get("colors", 0)
|
170 |
+
else (1 << file_info["bits"])
|
171 |
+
)
|
172 |
+
if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
|
173 |
+
offset += 4 * file_info["colors"]
|
174 |
+
|
175 |
+
# ---------------------- Check bit depth for unusual unsupported values
|
176 |
+
self._mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
|
177 |
+
if self.mode is None:
|
178 |
+
msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
|
179 |
+
raise OSError(msg)
|
180 |
+
|
181 |
+
# ---------------- Process BMP with Bitfields compression (not palette)
|
182 |
+
decoder_name = "raw"
|
183 |
+
if file_info["compression"] == self.BITFIELDS:
|
184 |
+
SUPPORTED = {
|
185 |
+
32: [
|
186 |
+
(0xFF0000, 0xFF00, 0xFF, 0x0),
|
187 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0x0),
|
188 |
+
(0xFF000000, 0xFF00, 0xFF, 0x0),
|
189 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0xFF),
|
190 |
+
(0xFF, 0xFF00, 0xFF0000, 0xFF000000),
|
191 |
+
(0xFF0000, 0xFF00, 0xFF, 0xFF000000),
|
192 |
+
(0xFF000000, 0xFF00, 0xFF, 0xFF0000),
|
193 |
+
(0x0, 0x0, 0x0, 0x0),
|
194 |
+
],
|
195 |
+
24: [(0xFF0000, 0xFF00, 0xFF)],
|
196 |
+
16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
|
197 |
+
}
|
198 |
+
MASK_MODES = {
|
199 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
|
200 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
|
201 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
|
202 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
|
203 |
+
(32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
|
204 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
|
205 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
|
206 |
+
(32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
|
207 |
+
(24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
|
208 |
+
(16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
|
209 |
+
(16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
|
210 |
+
}
|
211 |
+
if file_info["bits"] in SUPPORTED:
|
212 |
+
if (
|
213 |
+
file_info["bits"] == 32
|
214 |
+
and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
|
215 |
+
):
|
216 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
|
217 |
+
self._mode = "RGBA" if "A" in raw_mode else self.mode
|
218 |
+
elif (
|
219 |
+
file_info["bits"] in (24, 16)
|
220 |
+
and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
|
221 |
+
):
|
222 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
|
223 |
+
else:
|
224 |
+
msg = "Unsupported BMP bitfields layout"
|
225 |
+
raise OSError(msg)
|
226 |
+
else:
|
227 |
+
msg = "Unsupported BMP bitfields layout"
|
228 |
+
raise OSError(msg)
|
229 |
+
elif file_info["compression"] == self.RAW:
|
230 |
+
if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
|
231 |
+
raw_mode, self._mode = "BGRA", "RGBA"
|
232 |
+
elif file_info["compression"] in (self.RLE8, self.RLE4):
|
233 |
+
decoder_name = "bmp_rle"
|
234 |
+
else:
|
235 |
+
msg = f"Unsupported BMP compression ({file_info['compression']})"
|
236 |
+
raise OSError(msg)
|
237 |
+
|
238 |
+
# --------------- Once the header is processed, process the palette/LUT
|
239 |
+
if self.mode == "P": # Paletted for 1, 4 and 8 bit images
|
240 |
+
# ---------------------------------------------------- 1-bit images
|
241 |
+
if not (0 < file_info["colors"] <= 65536):
|
242 |
+
msg = f"Unsupported BMP Palette size ({file_info['colors']})"
|
243 |
+
raise OSError(msg)
|
244 |
+
else:
|
245 |
+
padding = file_info["palette_padding"]
|
246 |
+
palette = read(padding * file_info["colors"])
|
247 |
+
grayscale = True
|
248 |
+
indices = (
|
249 |
+
(0, 255)
|
250 |
+
if file_info["colors"] == 2
|
251 |
+
else list(range(file_info["colors"]))
|
252 |
+
)
|
253 |
+
|
254 |
+
# ----------------- Check if grayscale and ignore palette if so
|
255 |
+
for ind, val in enumerate(indices):
|
256 |
+
rgb = palette[ind * padding : ind * padding + 3]
|
257 |
+
if rgb != o8(val) * 3:
|
258 |
+
grayscale = False
|
259 |
+
|
260 |
+
# ------- If all colors are gray, white or black, ditch palette
|
261 |
+
if grayscale:
|
262 |
+
self._mode = "1" if file_info["colors"] == 2 else "L"
|
263 |
+
raw_mode = self.mode
|
264 |
+
else:
|
265 |
+
self._mode = "P"
|
266 |
+
self.palette = ImagePalette.raw(
|
267 |
+
"BGRX" if padding == 4 else "BGR", palette
|
268 |
+
)
|
269 |
+
|
270 |
+
# ---------------------------- Finally set the tile data for the plugin
|
271 |
+
self.info["compression"] = file_info["compression"]
|
272 |
+
args = [raw_mode]
|
273 |
+
if decoder_name == "bmp_rle":
|
274 |
+
args.append(file_info["compression"] == self.RLE4)
|
275 |
+
else:
|
276 |
+
args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
|
277 |
+
args.append(file_info["direction"])
|
278 |
+
self.tile = [
|
279 |
+
(
|
280 |
+
decoder_name,
|
281 |
+
(0, 0, file_info["width"], file_info["height"]),
|
282 |
+
offset or self.fp.tell(),
|
283 |
+
tuple(args),
|
284 |
+
)
|
285 |
+
]
|
286 |
+
|
287 |
+
def _open(self) -> None:
|
288 |
+
"""Open file, check magic number and read header"""
|
289 |
+
# read 14 bytes: magic number, filesize, reserved, header final offset
|
290 |
+
head_data = self.fp.read(14)
|
291 |
+
# choke if the file does not have the required magic bytes
|
292 |
+
if not _accept(head_data):
|
293 |
+
msg = "Not a BMP file"
|
294 |
+
raise SyntaxError(msg)
|
295 |
+
# read the start position of the BMP image data (u32)
|
296 |
+
offset = i32(head_data, 10)
|
297 |
+
# load bitmap information (offset=raster info)
|
298 |
+
self._bitmap(offset=offset)
|
299 |
+
|
300 |
+
|
301 |
+
class BmpRleDecoder(ImageFile.PyDecoder):
|
302 |
+
_pulls_fd = True
|
303 |
+
|
304 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
305 |
+
assert self.fd is not None
|
306 |
+
rle4 = self.args[1]
|
307 |
+
data = bytearray()
|
308 |
+
x = 0
|
309 |
+
dest_length = self.state.xsize * self.state.ysize
|
310 |
+
while len(data) < dest_length:
|
311 |
+
pixels = self.fd.read(1)
|
312 |
+
byte = self.fd.read(1)
|
313 |
+
if not pixels or not byte:
|
314 |
+
break
|
315 |
+
num_pixels = pixels[0]
|
316 |
+
if num_pixels:
|
317 |
+
# encoded mode
|
318 |
+
if x + num_pixels > self.state.xsize:
|
319 |
+
# Too much data for row
|
320 |
+
num_pixels = max(0, self.state.xsize - x)
|
321 |
+
if rle4:
|
322 |
+
first_pixel = o8(byte[0] >> 4)
|
323 |
+
second_pixel = o8(byte[0] & 0x0F)
|
324 |
+
for index in range(num_pixels):
|
325 |
+
if index % 2 == 0:
|
326 |
+
data += first_pixel
|
327 |
+
else:
|
328 |
+
data += second_pixel
|
329 |
+
else:
|
330 |
+
data += byte * num_pixels
|
331 |
+
x += num_pixels
|
332 |
+
else:
|
333 |
+
if byte[0] == 0:
|
334 |
+
# end of line
|
335 |
+
while len(data) % self.state.xsize != 0:
|
336 |
+
data += b"\x00"
|
337 |
+
x = 0
|
338 |
+
elif byte[0] == 1:
|
339 |
+
# end of bitmap
|
340 |
+
break
|
341 |
+
elif byte[0] == 2:
|
342 |
+
# delta
|
343 |
+
bytes_read = self.fd.read(2)
|
344 |
+
if len(bytes_read) < 2:
|
345 |
+
break
|
346 |
+
right, up = self.fd.read(2)
|
347 |
+
data += b"\x00" * (right + up * self.state.xsize)
|
348 |
+
x = len(data) % self.state.xsize
|
349 |
+
else:
|
350 |
+
# absolute mode
|
351 |
+
if rle4:
|
352 |
+
# 2 pixels per byte
|
353 |
+
byte_count = byte[0] // 2
|
354 |
+
bytes_read = self.fd.read(byte_count)
|
355 |
+
for byte_read in bytes_read:
|
356 |
+
data += o8(byte_read >> 4)
|
357 |
+
data += o8(byte_read & 0x0F)
|
358 |
+
else:
|
359 |
+
byte_count = byte[0]
|
360 |
+
bytes_read = self.fd.read(byte_count)
|
361 |
+
data += bytes_read
|
362 |
+
if len(bytes_read) < byte_count:
|
363 |
+
break
|
364 |
+
x += byte[0]
|
365 |
+
|
366 |
+
# align to 16-bit word boundary
|
367 |
+
if self.fd.tell() % 2 != 0:
|
368 |
+
self.fd.seek(1, os.SEEK_CUR)
|
369 |
+
rawmode = "L" if self.mode == "L" else "P"
|
370 |
+
self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
|
371 |
+
return -1, 0
|
372 |
+
|
373 |
+
|
374 |
+
# =============================================================================
|
375 |
+
# Image plugin for the DIB format (BMP alias)
|
376 |
+
# =============================================================================
|
377 |
+
class DibImageFile(BmpImageFile):
|
378 |
+
format = "DIB"
|
379 |
+
format_description = "Windows Bitmap"
|
380 |
+
|
381 |
+
def _open(self) -> None:
|
382 |
+
self._bitmap()
|
383 |
+
|
384 |
+
|
385 |
+
#
|
386 |
+
# --------------------------------------------------------------------
|
387 |
+
# Write BMP file
|
388 |
+
|
389 |
+
|
390 |
+
SAVE = {
|
391 |
+
"1": ("1", 1, 2),
|
392 |
+
"L": ("L", 8, 256),
|
393 |
+
"P": ("P", 8, 256),
|
394 |
+
"RGB": ("BGR", 24, 0),
|
395 |
+
"RGBA": ("BGRA", 32, 0),
|
396 |
+
}
|
397 |
+
|
398 |
+
|
399 |
+
def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
400 |
+
_save(im, fp, filename, False)
|
401 |
+
|
402 |
+
|
403 |
+
def _save(
|
404 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
|
405 |
+
) -> None:
|
406 |
+
try:
|
407 |
+
rawmode, bits, colors = SAVE[im.mode]
|
408 |
+
except KeyError as e:
|
409 |
+
msg = f"cannot write mode {im.mode} as BMP"
|
410 |
+
raise OSError(msg) from e
|
411 |
+
|
412 |
+
info = im.encoderinfo
|
413 |
+
|
414 |
+
dpi = info.get("dpi", (96, 96))
|
415 |
+
|
416 |
+
# 1 meter == 39.3701 inches
|
417 |
+
ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
|
418 |
+
|
419 |
+
stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
|
420 |
+
header = 40 # or 64 for OS/2 version 2
|
421 |
+
image = stride * im.size[1]
|
422 |
+
|
423 |
+
if im.mode == "1":
|
424 |
+
palette = b"".join(o8(i) * 4 for i in (0, 255))
|
425 |
+
elif im.mode == "L":
|
426 |
+
palette = b"".join(o8(i) * 4 for i in range(256))
|
427 |
+
elif im.mode == "P":
|
428 |
+
palette = im.im.getpalette("RGB", "BGRX")
|
429 |
+
colors = len(palette) // 4
|
430 |
+
else:
|
431 |
+
palette = None
|
432 |
+
|
433 |
+
# bitmap header
|
434 |
+
if bitmap_header:
|
435 |
+
offset = 14 + header + colors * 4
|
436 |
+
file_size = offset + image
|
437 |
+
if file_size > 2**32 - 1:
|
438 |
+
msg = "File size is too large for the BMP format"
|
439 |
+
raise ValueError(msg)
|
440 |
+
fp.write(
|
441 |
+
b"BM" # file type (magic)
|
442 |
+
+ o32(file_size) # file size
|
443 |
+
+ o32(0) # reserved
|
444 |
+
+ o32(offset) # image data offset
|
445 |
+
)
|
446 |
+
|
447 |
+
# bitmap info header
|
448 |
+
fp.write(
|
449 |
+
o32(header) # info header size
|
450 |
+
+ o32(im.size[0]) # width
|
451 |
+
+ o32(im.size[1]) # height
|
452 |
+
+ o16(1) # planes
|
453 |
+
+ o16(bits) # depth
|
454 |
+
+ o32(0) # compression (0=uncompressed)
|
455 |
+
+ o32(image) # size of bitmap
|
456 |
+
+ o32(ppm[0]) # resolution
|
457 |
+
+ o32(ppm[1]) # resolution
|
458 |
+
+ o32(colors) # colors used
|
459 |
+
+ o32(colors) # colors important
|
460 |
+
)
|
461 |
+
|
462 |
+
fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
|
463 |
+
|
464 |
+
if palette:
|
465 |
+
fp.write(palette)
|
466 |
+
|
467 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
|
468 |
+
|
469 |
+
|
470 |
+
#
|
471 |
+
# --------------------------------------------------------------------
|
472 |
+
# Registry
|
473 |
+
|
474 |
+
|
475 |
+
Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
|
476 |
+
Image.register_save(BmpImageFile.format, _save)
|
477 |
+
|
478 |
+
Image.register_extension(BmpImageFile.format, ".bmp")
|
479 |
+
|
480 |
+
Image.register_mime(BmpImageFile.format, "image/bmp")
|
481 |
+
|
482 |
+
Image.register_decoder("bmp_rle", BmpRleDecoder)
|
483 |
+
|
484 |
+
Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
|
485 |
+
Image.register_save(DibImageFile.format, _dib_save)
|
486 |
+
|
487 |
+
Image.register_extension(DibImageFile.format, ".dib")
|
488 |
+
|
489 |
+
Image.register_mime(DibImageFile.format, "image/bmp")
|
MLPY/Lib/site-packages/PIL/BufrStubImagePlugin.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# BUFR stub adapter
|
6 |
+
#
|
7 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
8 |
+
#
|
9 |
+
# See the README file for information on usage and redistribution.
|
10 |
+
#
|
11 |
+
from __future__ import annotations
|
12 |
+
|
13 |
+
from typing import IO
|
14 |
+
|
15 |
+
from . import Image, ImageFile
|
16 |
+
|
17 |
+
_handler = None
|
18 |
+
|
19 |
+
|
20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
21 |
+
"""
|
22 |
+
Install application-specific BUFR image handler.
|
23 |
+
|
24 |
+
:param handler: Handler object.
|
25 |
+
"""
|
26 |
+
global _handler
|
27 |
+
_handler = handler
|
28 |
+
|
29 |
+
|
30 |
+
# --------------------------------------------------------------------
|
31 |
+
# Image adapter
|
32 |
+
|
33 |
+
|
34 |
+
def _accept(prefix: bytes) -> bool:
|
35 |
+
return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
|
36 |
+
|
37 |
+
|
38 |
+
class BufrStubImageFile(ImageFile.StubImageFile):
|
39 |
+
format = "BUFR"
|
40 |
+
format_description = "BUFR"
|
41 |
+
|
42 |
+
def _open(self) -> None:
|
43 |
+
offset = self.fp.tell()
|
44 |
+
|
45 |
+
if not _accept(self.fp.read(4)):
|
46 |
+
msg = "Not a BUFR file"
|
47 |
+
raise SyntaxError(msg)
|
48 |
+
|
49 |
+
self.fp.seek(offset)
|
50 |
+
|
51 |
+
# make something up
|
52 |
+
self._mode = "F"
|
53 |
+
self._size = 1, 1
|
54 |
+
|
55 |
+
loader = self._load()
|
56 |
+
if loader:
|
57 |
+
loader.open(self)
|
58 |
+
|
59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
60 |
+
return _handler
|
61 |
+
|
62 |
+
|
63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
65 |
+
msg = "BUFR save handler not installed"
|
66 |
+
raise OSError(msg)
|
67 |
+
_handler.save(im, fp, filename)
|
68 |
+
|
69 |
+
|
70 |
+
# --------------------------------------------------------------------
|
71 |
+
# Registry
|
72 |
+
|
73 |
+
Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
|
74 |
+
Image.register_save(BufrStubImageFile.format, _save)
|
75 |
+
|
76 |
+
Image.register_extension(BufrStubImageFile.format, ".bufr")
|
MLPY/Lib/site-packages/PIL/ContainerIO.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# a class to read from a container file
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1995-06-18 fl Created
|
9 |
+
# 1995-09-07 fl Added readline(), readlines()
|
10 |
+
#
|
11 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
12 |
+
# Copyright (c) 1995 by Fredrik Lundh
|
13 |
+
#
|
14 |
+
# See the README file for information on usage and redistribution.
|
15 |
+
#
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
import io
|
19 |
+
from typing import IO, AnyStr, Generic, Literal
|
20 |
+
|
21 |
+
|
22 |
+
class ContainerIO(Generic[AnyStr]):
|
23 |
+
"""
|
24 |
+
A file object that provides read access to a part of an existing
|
25 |
+
file (for example a TAR file).
|
26 |
+
"""
|
27 |
+
|
28 |
+
def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
|
29 |
+
"""
|
30 |
+
Create file object.
|
31 |
+
|
32 |
+
:param file: Existing file.
|
33 |
+
:param offset: Start of region, in bytes.
|
34 |
+
:param length: Size of region, in bytes.
|
35 |
+
"""
|
36 |
+
self.fh: IO[AnyStr] = file
|
37 |
+
self.pos = 0
|
38 |
+
self.offset = offset
|
39 |
+
self.length = length
|
40 |
+
self.fh.seek(offset)
|
41 |
+
|
42 |
+
##
|
43 |
+
# Always false.
|
44 |
+
|
45 |
+
def isatty(self) -> bool:
|
46 |
+
return False
|
47 |
+
|
48 |
+
def seek(self, offset: int, mode: Literal[0, 1, 2] = io.SEEK_SET) -> None:
|
49 |
+
"""
|
50 |
+
Move file pointer.
|
51 |
+
|
52 |
+
:param offset: Offset in bytes.
|
53 |
+
:param mode: Starting position. Use 0 for beginning of region, 1
|
54 |
+
for current offset, and 2 for end of region. You cannot move
|
55 |
+
the pointer outside the defined region.
|
56 |
+
"""
|
57 |
+
if mode == 1:
|
58 |
+
self.pos = self.pos + offset
|
59 |
+
elif mode == 2:
|
60 |
+
self.pos = self.length + offset
|
61 |
+
else:
|
62 |
+
self.pos = offset
|
63 |
+
# clamp
|
64 |
+
self.pos = max(0, min(self.pos, self.length))
|
65 |
+
self.fh.seek(self.offset + self.pos)
|
66 |
+
|
67 |
+
def tell(self) -> int:
|
68 |
+
"""
|
69 |
+
Get current file pointer.
|
70 |
+
|
71 |
+
:returns: Offset from start of region, in bytes.
|
72 |
+
"""
|
73 |
+
return self.pos
|
74 |
+
|
75 |
+
def read(self, n: int = 0) -> AnyStr:
|
76 |
+
"""
|
77 |
+
Read data.
|
78 |
+
|
79 |
+
:param n: Number of bytes to read. If omitted or zero,
|
80 |
+
read until end of region.
|
81 |
+
:returns: An 8-bit string.
|
82 |
+
"""
|
83 |
+
if n:
|
84 |
+
n = min(n, self.length - self.pos)
|
85 |
+
else:
|
86 |
+
n = self.length - self.pos
|
87 |
+
if not n: # EOF
|
88 |
+
return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
|
89 |
+
self.pos = self.pos + n
|
90 |
+
return self.fh.read(n)
|
91 |
+
|
92 |
+
def readline(self) -> AnyStr:
|
93 |
+
"""
|
94 |
+
Read a line of text.
|
95 |
+
|
96 |
+
:returns: An 8-bit string.
|
97 |
+
"""
|
98 |
+
s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
|
99 |
+
newline_character = b"\n" if "b" in self.fh.mode else "\n"
|
100 |
+
while True:
|
101 |
+
c = self.read(1)
|
102 |
+
if not c:
|
103 |
+
break
|
104 |
+
s = s + c
|
105 |
+
if c == newline_character:
|
106 |
+
break
|
107 |
+
return s
|
108 |
+
|
109 |
+
def readlines(self) -> list[AnyStr]:
|
110 |
+
"""
|
111 |
+
Read multiple lines of text.
|
112 |
+
|
113 |
+
:returns: A list of 8-bit strings.
|
114 |
+
"""
|
115 |
+
lines = []
|
116 |
+
while True:
|
117 |
+
s = self.readline()
|
118 |
+
if not s:
|
119 |
+
break
|
120 |
+
lines.append(s)
|
121 |
+
return lines
|
MLPY/Lib/site-packages/PIL/CurImagePlugin.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# Windows Cursor support for PIL
|
6 |
+
#
|
7 |
+
# notes:
|
8 |
+
# uses BmpImagePlugin.py to read the bitmap data.
|
9 |
+
#
|
10 |
+
# history:
|
11 |
+
# 96-05-27 fl Created
|
12 |
+
#
|
13 |
+
# Copyright (c) Secret Labs AB 1997.
|
14 |
+
# Copyright (c) Fredrik Lundh 1996.
|
15 |
+
#
|
16 |
+
# See the README file for information on usage and redistribution.
|
17 |
+
#
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
from . import BmpImagePlugin, Image
|
21 |
+
from ._binary import i16le as i16
|
22 |
+
from ._binary import i32le as i32
|
23 |
+
|
24 |
+
#
|
25 |
+
# --------------------------------------------------------------------
|
26 |
+
|
27 |
+
|
28 |
+
def _accept(prefix: bytes) -> bool:
|
29 |
+
return prefix[:4] == b"\0\0\2\0"
|
30 |
+
|
31 |
+
|
32 |
+
##
|
33 |
+
# Image plugin for Windows Cursor files.
|
34 |
+
|
35 |
+
|
36 |
+
class CurImageFile(BmpImagePlugin.BmpImageFile):
|
37 |
+
format = "CUR"
|
38 |
+
format_description = "Windows Cursor"
|
39 |
+
|
40 |
+
def _open(self) -> None:
|
41 |
+
offset = self.fp.tell()
|
42 |
+
|
43 |
+
# check magic
|
44 |
+
s = self.fp.read(6)
|
45 |
+
if not _accept(s):
|
46 |
+
msg = "not a CUR file"
|
47 |
+
raise SyntaxError(msg)
|
48 |
+
|
49 |
+
# pick the largest cursor in the file
|
50 |
+
m = b""
|
51 |
+
for i in range(i16(s, 4)):
|
52 |
+
s = self.fp.read(16)
|
53 |
+
if not m:
|
54 |
+
m = s
|
55 |
+
elif s[0] > m[0] and s[1] > m[1]:
|
56 |
+
m = s
|
57 |
+
if not m:
|
58 |
+
msg = "No cursors were found"
|
59 |
+
raise TypeError(msg)
|
60 |
+
|
61 |
+
# load as bitmap
|
62 |
+
self._bitmap(i32(m, 12) + offset)
|
63 |
+
|
64 |
+
# patch up the bitmap height
|
65 |
+
self._size = self.size[0], self.size[1] // 2
|
66 |
+
d, e, o, a = self.tile[0]
|
67 |
+
self.tile[0] = d, (0, 0) + self.size, o, a
|
68 |
+
|
69 |
+
|
70 |
+
#
|
71 |
+
# --------------------------------------------------------------------
|
72 |
+
|
73 |
+
Image.register_open(CurImageFile.format, CurImageFile, _accept)
|
74 |
+
|
75 |
+
Image.register_extension(CurImageFile.format, ".cur")
|
MLPY/Lib/site-packages/PIL/DcxImagePlugin.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# DCX file handling
|
6 |
+
#
|
7 |
+
# DCX is a container file format defined by Intel, commonly used
|
8 |
+
# for fax applications. Each DCX file consists of a directory
|
9 |
+
# (a list of file offsets) followed by a set of (usually 1-bit)
|
10 |
+
# PCX files.
|
11 |
+
#
|
12 |
+
# History:
|
13 |
+
# 1995-09-09 fl Created
|
14 |
+
# 1996-03-20 fl Properly derived from PcxImageFile.
|
15 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
16 |
+
# 2002-07-30 fl Fixed file handling
|
17 |
+
#
|
18 |
+
# Copyright (c) 1997-98 by Secret Labs AB.
|
19 |
+
# Copyright (c) 1995-96 by Fredrik Lundh.
|
20 |
+
#
|
21 |
+
# See the README file for information on usage and redistribution.
|
22 |
+
#
|
23 |
+
from __future__ import annotations
|
24 |
+
|
25 |
+
from . import Image
|
26 |
+
from ._binary import i32le as i32
|
27 |
+
from .PcxImagePlugin import PcxImageFile
|
28 |
+
|
29 |
+
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
|
30 |
+
|
31 |
+
|
32 |
+
def _accept(prefix: bytes) -> bool:
|
33 |
+
return len(prefix) >= 4 and i32(prefix) == MAGIC
|
34 |
+
|
35 |
+
|
36 |
+
##
|
37 |
+
# Image plugin for the Intel DCX format.
|
38 |
+
|
39 |
+
|
40 |
+
class DcxImageFile(PcxImageFile):
|
41 |
+
format = "DCX"
|
42 |
+
format_description = "Intel DCX"
|
43 |
+
_close_exclusive_fp_after_loading = False
|
44 |
+
|
45 |
+
def _open(self) -> None:
|
46 |
+
# Header
|
47 |
+
s = self.fp.read(4)
|
48 |
+
if not _accept(s):
|
49 |
+
msg = "not a DCX file"
|
50 |
+
raise SyntaxError(msg)
|
51 |
+
|
52 |
+
# Component directory
|
53 |
+
self._offset = []
|
54 |
+
for i in range(1024):
|
55 |
+
offset = i32(self.fp.read(4))
|
56 |
+
if not offset:
|
57 |
+
break
|
58 |
+
self._offset.append(offset)
|
59 |
+
|
60 |
+
self._fp = self.fp
|
61 |
+
self.frame = -1
|
62 |
+
self.n_frames = len(self._offset)
|
63 |
+
self.is_animated = self.n_frames > 1
|
64 |
+
self.seek(0)
|
65 |
+
|
66 |
+
def seek(self, frame: int) -> None:
|
67 |
+
if not self._seek_check(frame):
|
68 |
+
return
|
69 |
+
self.frame = frame
|
70 |
+
self.fp = self._fp
|
71 |
+
self.fp.seek(self._offset[frame])
|
72 |
+
PcxImageFile._open(self)
|
73 |
+
|
74 |
+
def tell(self) -> int:
|
75 |
+
return self.frame
|
76 |
+
|
77 |
+
|
78 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A Pillow loader for .dds files (S3TC-compressed aka DXTC)
|
3 |
+
Jerome Leclanche <[email protected]>
|
4 |
+
|
5 |
+
Documentation:
|
6 |
+
https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
|
7 |
+
|
8 |
+
The contents of this file are hereby released in the public domain (CC0)
|
9 |
+
Full text of the CC0 license:
|
10 |
+
https://creativecommons.org/publicdomain/zero/1.0/
|
11 |
+
"""
|
12 |
+
|
13 |
+
from __future__ import annotations
|
14 |
+
|
15 |
+
import io
|
16 |
+
import struct
|
17 |
+
import sys
|
18 |
+
from enum import IntEnum, IntFlag
|
19 |
+
from typing import IO
|
20 |
+
|
21 |
+
from . import Image, ImageFile, ImagePalette
|
22 |
+
from ._binary import i32le as i32
|
23 |
+
from ._binary import o8
|
24 |
+
from ._binary import o32le as o32
|
25 |
+
|
26 |
+
# Magic ("DDS ")
|
27 |
+
DDS_MAGIC = 0x20534444
|
28 |
+
|
29 |
+
|
30 |
+
# DDS flags
|
31 |
+
class DDSD(IntFlag):
|
32 |
+
CAPS = 0x1
|
33 |
+
HEIGHT = 0x2
|
34 |
+
WIDTH = 0x4
|
35 |
+
PITCH = 0x8
|
36 |
+
PIXELFORMAT = 0x1000
|
37 |
+
MIPMAPCOUNT = 0x20000
|
38 |
+
LINEARSIZE = 0x80000
|
39 |
+
DEPTH = 0x800000
|
40 |
+
|
41 |
+
|
42 |
+
# DDS caps
|
43 |
+
class DDSCAPS(IntFlag):
|
44 |
+
COMPLEX = 0x8
|
45 |
+
TEXTURE = 0x1000
|
46 |
+
MIPMAP = 0x400000
|
47 |
+
|
48 |
+
|
49 |
+
class DDSCAPS2(IntFlag):
|
50 |
+
CUBEMAP = 0x200
|
51 |
+
CUBEMAP_POSITIVEX = 0x400
|
52 |
+
CUBEMAP_NEGATIVEX = 0x800
|
53 |
+
CUBEMAP_POSITIVEY = 0x1000
|
54 |
+
CUBEMAP_NEGATIVEY = 0x2000
|
55 |
+
CUBEMAP_POSITIVEZ = 0x4000
|
56 |
+
CUBEMAP_NEGATIVEZ = 0x8000
|
57 |
+
VOLUME = 0x200000
|
58 |
+
|
59 |
+
|
60 |
+
# Pixel Format
|
61 |
+
class DDPF(IntFlag):
|
62 |
+
ALPHAPIXELS = 0x1
|
63 |
+
ALPHA = 0x2
|
64 |
+
FOURCC = 0x4
|
65 |
+
PALETTEINDEXED8 = 0x20
|
66 |
+
RGB = 0x40
|
67 |
+
LUMINANCE = 0x20000
|
68 |
+
|
69 |
+
|
70 |
+
# dxgiformat.h
|
71 |
+
class DXGI_FORMAT(IntEnum):
|
72 |
+
UNKNOWN = 0
|
73 |
+
R32G32B32A32_TYPELESS = 1
|
74 |
+
R32G32B32A32_FLOAT = 2
|
75 |
+
R32G32B32A32_UINT = 3
|
76 |
+
R32G32B32A32_SINT = 4
|
77 |
+
R32G32B32_TYPELESS = 5
|
78 |
+
R32G32B32_FLOAT = 6
|
79 |
+
R32G32B32_UINT = 7
|
80 |
+
R32G32B32_SINT = 8
|
81 |
+
R16G16B16A16_TYPELESS = 9
|
82 |
+
R16G16B16A16_FLOAT = 10
|
83 |
+
R16G16B16A16_UNORM = 11
|
84 |
+
R16G16B16A16_UINT = 12
|
85 |
+
R16G16B16A16_SNORM = 13
|
86 |
+
R16G16B16A16_SINT = 14
|
87 |
+
R32G32_TYPELESS = 15
|
88 |
+
R32G32_FLOAT = 16
|
89 |
+
R32G32_UINT = 17
|
90 |
+
R32G32_SINT = 18
|
91 |
+
R32G8X24_TYPELESS = 19
|
92 |
+
D32_FLOAT_S8X24_UINT = 20
|
93 |
+
R32_FLOAT_X8X24_TYPELESS = 21
|
94 |
+
X32_TYPELESS_G8X24_UINT = 22
|
95 |
+
R10G10B10A2_TYPELESS = 23
|
96 |
+
R10G10B10A2_UNORM = 24
|
97 |
+
R10G10B10A2_UINT = 25
|
98 |
+
R11G11B10_FLOAT = 26
|
99 |
+
R8G8B8A8_TYPELESS = 27
|
100 |
+
R8G8B8A8_UNORM = 28
|
101 |
+
R8G8B8A8_UNORM_SRGB = 29
|
102 |
+
R8G8B8A8_UINT = 30
|
103 |
+
R8G8B8A8_SNORM = 31
|
104 |
+
R8G8B8A8_SINT = 32
|
105 |
+
R16G16_TYPELESS = 33
|
106 |
+
R16G16_FLOAT = 34
|
107 |
+
R16G16_UNORM = 35
|
108 |
+
R16G16_UINT = 36
|
109 |
+
R16G16_SNORM = 37
|
110 |
+
R16G16_SINT = 38
|
111 |
+
R32_TYPELESS = 39
|
112 |
+
D32_FLOAT = 40
|
113 |
+
R32_FLOAT = 41
|
114 |
+
R32_UINT = 42
|
115 |
+
R32_SINT = 43
|
116 |
+
R24G8_TYPELESS = 44
|
117 |
+
D24_UNORM_S8_UINT = 45
|
118 |
+
R24_UNORM_X8_TYPELESS = 46
|
119 |
+
X24_TYPELESS_G8_UINT = 47
|
120 |
+
R8G8_TYPELESS = 48
|
121 |
+
R8G8_UNORM = 49
|
122 |
+
R8G8_UINT = 50
|
123 |
+
R8G8_SNORM = 51
|
124 |
+
R8G8_SINT = 52
|
125 |
+
R16_TYPELESS = 53
|
126 |
+
R16_FLOAT = 54
|
127 |
+
D16_UNORM = 55
|
128 |
+
R16_UNORM = 56
|
129 |
+
R16_UINT = 57
|
130 |
+
R16_SNORM = 58
|
131 |
+
R16_SINT = 59
|
132 |
+
R8_TYPELESS = 60
|
133 |
+
R8_UNORM = 61
|
134 |
+
R8_UINT = 62
|
135 |
+
R8_SNORM = 63
|
136 |
+
R8_SINT = 64
|
137 |
+
A8_UNORM = 65
|
138 |
+
R1_UNORM = 66
|
139 |
+
R9G9B9E5_SHAREDEXP = 67
|
140 |
+
R8G8_B8G8_UNORM = 68
|
141 |
+
G8R8_G8B8_UNORM = 69
|
142 |
+
BC1_TYPELESS = 70
|
143 |
+
BC1_UNORM = 71
|
144 |
+
BC1_UNORM_SRGB = 72
|
145 |
+
BC2_TYPELESS = 73
|
146 |
+
BC2_UNORM = 74
|
147 |
+
BC2_UNORM_SRGB = 75
|
148 |
+
BC3_TYPELESS = 76
|
149 |
+
BC3_UNORM = 77
|
150 |
+
BC3_UNORM_SRGB = 78
|
151 |
+
BC4_TYPELESS = 79
|
152 |
+
BC4_UNORM = 80
|
153 |
+
BC4_SNORM = 81
|
154 |
+
BC5_TYPELESS = 82
|
155 |
+
BC5_UNORM = 83
|
156 |
+
BC5_SNORM = 84
|
157 |
+
B5G6R5_UNORM = 85
|
158 |
+
B5G5R5A1_UNORM = 86
|
159 |
+
B8G8R8A8_UNORM = 87
|
160 |
+
B8G8R8X8_UNORM = 88
|
161 |
+
R10G10B10_XR_BIAS_A2_UNORM = 89
|
162 |
+
B8G8R8A8_TYPELESS = 90
|
163 |
+
B8G8R8A8_UNORM_SRGB = 91
|
164 |
+
B8G8R8X8_TYPELESS = 92
|
165 |
+
B8G8R8X8_UNORM_SRGB = 93
|
166 |
+
BC6H_TYPELESS = 94
|
167 |
+
BC6H_UF16 = 95
|
168 |
+
BC6H_SF16 = 96
|
169 |
+
BC7_TYPELESS = 97
|
170 |
+
BC7_UNORM = 98
|
171 |
+
BC7_UNORM_SRGB = 99
|
172 |
+
AYUV = 100
|
173 |
+
Y410 = 101
|
174 |
+
Y416 = 102
|
175 |
+
NV12 = 103
|
176 |
+
P010 = 104
|
177 |
+
P016 = 105
|
178 |
+
OPAQUE_420 = 106
|
179 |
+
YUY2 = 107
|
180 |
+
Y210 = 108
|
181 |
+
Y216 = 109
|
182 |
+
NV11 = 110
|
183 |
+
AI44 = 111
|
184 |
+
IA44 = 112
|
185 |
+
P8 = 113
|
186 |
+
A8P8 = 114
|
187 |
+
B4G4R4A4_UNORM = 115
|
188 |
+
P208 = 130
|
189 |
+
V208 = 131
|
190 |
+
V408 = 132
|
191 |
+
SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189
|
192 |
+
SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190
|
193 |
+
|
194 |
+
|
195 |
+
class D3DFMT(IntEnum):
|
196 |
+
UNKNOWN = 0
|
197 |
+
R8G8B8 = 20
|
198 |
+
A8R8G8B8 = 21
|
199 |
+
X8R8G8B8 = 22
|
200 |
+
R5G6B5 = 23
|
201 |
+
X1R5G5B5 = 24
|
202 |
+
A1R5G5B5 = 25
|
203 |
+
A4R4G4B4 = 26
|
204 |
+
R3G3B2 = 27
|
205 |
+
A8 = 28
|
206 |
+
A8R3G3B2 = 29
|
207 |
+
X4R4G4B4 = 30
|
208 |
+
A2B10G10R10 = 31
|
209 |
+
A8B8G8R8 = 32
|
210 |
+
X8B8G8R8 = 33
|
211 |
+
G16R16 = 34
|
212 |
+
A2R10G10B10 = 35
|
213 |
+
A16B16G16R16 = 36
|
214 |
+
A8P8 = 40
|
215 |
+
P8 = 41
|
216 |
+
L8 = 50
|
217 |
+
A8L8 = 51
|
218 |
+
A4L4 = 52
|
219 |
+
V8U8 = 60
|
220 |
+
L6V5U5 = 61
|
221 |
+
X8L8V8U8 = 62
|
222 |
+
Q8W8V8U8 = 63
|
223 |
+
V16U16 = 64
|
224 |
+
A2W10V10U10 = 67
|
225 |
+
D16_LOCKABLE = 70
|
226 |
+
D32 = 71
|
227 |
+
D15S1 = 73
|
228 |
+
D24S8 = 75
|
229 |
+
D24X8 = 77
|
230 |
+
D24X4S4 = 79
|
231 |
+
D16 = 80
|
232 |
+
D32F_LOCKABLE = 82
|
233 |
+
D24FS8 = 83
|
234 |
+
D32_LOCKABLE = 84
|
235 |
+
S8_LOCKABLE = 85
|
236 |
+
L16 = 81
|
237 |
+
VERTEXDATA = 100
|
238 |
+
INDEX16 = 101
|
239 |
+
INDEX32 = 102
|
240 |
+
Q16W16V16U16 = 110
|
241 |
+
R16F = 111
|
242 |
+
G16R16F = 112
|
243 |
+
A16B16G16R16F = 113
|
244 |
+
R32F = 114
|
245 |
+
G32R32F = 115
|
246 |
+
A32B32G32R32F = 116
|
247 |
+
CxV8U8 = 117
|
248 |
+
A1 = 118
|
249 |
+
A2B10G10R10_XR_BIAS = 119
|
250 |
+
BINARYBUFFER = 199
|
251 |
+
|
252 |
+
UYVY = i32(b"UYVY")
|
253 |
+
R8G8_B8G8 = i32(b"RGBG")
|
254 |
+
YUY2 = i32(b"YUY2")
|
255 |
+
G8R8_G8B8 = i32(b"GRGB")
|
256 |
+
DXT1 = i32(b"DXT1")
|
257 |
+
DXT2 = i32(b"DXT2")
|
258 |
+
DXT3 = i32(b"DXT3")
|
259 |
+
DXT4 = i32(b"DXT4")
|
260 |
+
DXT5 = i32(b"DXT5")
|
261 |
+
DX10 = i32(b"DX10")
|
262 |
+
BC4S = i32(b"BC4S")
|
263 |
+
BC4U = i32(b"BC4U")
|
264 |
+
BC5S = i32(b"BC5S")
|
265 |
+
BC5U = i32(b"BC5U")
|
266 |
+
ATI1 = i32(b"ATI1")
|
267 |
+
ATI2 = i32(b"ATI2")
|
268 |
+
MULTI2_ARGB8 = i32(b"MET1")
|
269 |
+
|
270 |
+
|
271 |
+
# Backward compatibility layer
|
272 |
+
module = sys.modules[__name__]
|
273 |
+
for item in DDSD:
|
274 |
+
assert item.name is not None
|
275 |
+
setattr(module, f"DDSD_{item.name}", item.value)
|
276 |
+
for item1 in DDSCAPS:
|
277 |
+
assert item1.name is not None
|
278 |
+
setattr(module, f"DDSCAPS_{item1.name}", item1.value)
|
279 |
+
for item2 in DDSCAPS2:
|
280 |
+
assert item2.name is not None
|
281 |
+
setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
|
282 |
+
for item3 in DDPF:
|
283 |
+
assert item3.name is not None
|
284 |
+
setattr(module, f"DDPF_{item3.name}", item3.value)
|
285 |
+
|
286 |
+
DDS_FOURCC = DDPF.FOURCC
|
287 |
+
DDS_RGB = DDPF.RGB
|
288 |
+
DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
|
289 |
+
DDS_LUMINANCE = DDPF.LUMINANCE
|
290 |
+
DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
|
291 |
+
DDS_ALPHA = DDPF.ALPHA
|
292 |
+
DDS_PAL8 = DDPF.PALETTEINDEXED8
|
293 |
+
|
294 |
+
DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
|
295 |
+
DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
|
296 |
+
DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
|
297 |
+
DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
|
298 |
+
DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
|
299 |
+
|
300 |
+
DDS_HEIGHT = DDSD.HEIGHT
|
301 |
+
DDS_WIDTH = DDSD.WIDTH
|
302 |
+
|
303 |
+
DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
|
304 |
+
DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
|
305 |
+
DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
|
306 |
+
|
307 |
+
DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
|
308 |
+
DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
|
309 |
+
DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
|
310 |
+
DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
|
311 |
+
DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
|
312 |
+
DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
|
313 |
+
|
314 |
+
DXT1_FOURCC = D3DFMT.DXT1
|
315 |
+
DXT3_FOURCC = D3DFMT.DXT3
|
316 |
+
DXT5_FOURCC = D3DFMT.DXT5
|
317 |
+
|
318 |
+
DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
|
319 |
+
DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
|
320 |
+
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
|
321 |
+
DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
|
322 |
+
DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
|
323 |
+
DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
|
324 |
+
DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
|
325 |
+
DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
|
326 |
+
DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
|
327 |
+
DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
|
328 |
+
DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
|
329 |
+
|
330 |
+
|
331 |
+
class DdsImageFile(ImageFile.ImageFile):
|
332 |
+
format = "DDS"
|
333 |
+
format_description = "DirectDraw Surface"
|
334 |
+
|
335 |
+
def _open(self) -> None:
|
336 |
+
if not _accept(self.fp.read(4)):
|
337 |
+
msg = "not a DDS file"
|
338 |
+
raise SyntaxError(msg)
|
339 |
+
(header_size,) = struct.unpack("<I", self.fp.read(4))
|
340 |
+
if header_size != 124:
|
341 |
+
msg = f"Unsupported header size {repr(header_size)}"
|
342 |
+
raise OSError(msg)
|
343 |
+
header_bytes = self.fp.read(header_size - 4)
|
344 |
+
if len(header_bytes) != 120:
|
345 |
+
msg = f"Incomplete header: {len(header_bytes)} bytes"
|
346 |
+
raise OSError(msg)
|
347 |
+
header = io.BytesIO(header_bytes)
|
348 |
+
|
349 |
+
flags, height, width = struct.unpack("<3I", header.read(12))
|
350 |
+
self._size = (width, height)
|
351 |
+
extents = (0, 0) + self.size
|
352 |
+
|
353 |
+
pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
|
354 |
+
struct.unpack("<11I", header.read(44)) # reserved
|
355 |
+
|
356 |
+
# pixel format
|
357 |
+
pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header.read(16))
|
358 |
+
n = 0
|
359 |
+
rawmode = None
|
360 |
+
if pfflags & DDPF.RGB:
|
361 |
+
# Texture contains uncompressed RGB data
|
362 |
+
if pfflags & DDPF.ALPHAPIXELS:
|
363 |
+
self._mode = "RGBA"
|
364 |
+
mask_count = 4
|
365 |
+
else:
|
366 |
+
self._mode = "RGB"
|
367 |
+
mask_count = 3
|
368 |
+
|
369 |
+
masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4))
|
370 |
+
self.tile = [("dds_rgb", extents, 0, (bitcount, masks))]
|
371 |
+
return
|
372 |
+
elif pfflags & DDPF.LUMINANCE:
|
373 |
+
if bitcount == 8:
|
374 |
+
self._mode = "L"
|
375 |
+
elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
|
376 |
+
self._mode = "LA"
|
377 |
+
else:
|
378 |
+
msg = f"Unsupported bitcount {bitcount} for {pfflags}"
|
379 |
+
raise OSError(msg)
|
380 |
+
elif pfflags & DDPF.PALETTEINDEXED8:
|
381 |
+
self._mode = "P"
|
382 |
+
self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
|
383 |
+
self.palette.mode = "RGBA"
|
384 |
+
elif pfflags & DDPF.FOURCC:
|
385 |
+
offset = header_size + 4
|
386 |
+
if fourcc == D3DFMT.DXT1:
|
387 |
+
self._mode = "RGBA"
|
388 |
+
self.pixel_format = "DXT1"
|
389 |
+
n = 1
|
390 |
+
elif fourcc == D3DFMT.DXT3:
|
391 |
+
self._mode = "RGBA"
|
392 |
+
self.pixel_format = "DXT3"
|
393 |
+
n = 2
|
394 |
+
elif fourcc == D3DFMT.DXT5:
|
395 |
+
self._mode = "RGBA"
|
396 |
+
self.pixel_format = "DXT5"
|
397 |
+
n = 3
|
398 |
+
elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
|
399 |
+
self._mode = "L"
|
400 |
+
self.pixel_format = "BC4"
|
401 |
+
n = 4
|
402 |
+
elif fourcc == D3DFMT.BC5S:
|
403 |
+
self._mode = "RGB"
|
404 |
+
self.pixel_format = "BC5S"
|
405 |
+
n = 5
|
406 |
+
elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
|
407 |
+
self._mode = "RGB"
|
408 |
+
self.pixel_format = "BC5"
|
409 |
+
n = 5
|
410 |
+
elif fourcc == D3DFMT.DX10:
|
411 |
+
offset += 20
|
412 |
+
# ignoring flags which pertain to volume textures and cubemaps
|
413 |
+
(dxgi_format,) = struct.unpack("<I", self.fp.read(4))
|
414 |
+
self.fp.read(16)
|
415 |
+
if dxgi_format in (
|
416 |
+
DXGI_FORMAT.BC1_UNORM,
|
417 |
+
DXGI_FORMAT.BC1_TYPELESS,
|
418 |
+
):
|
419 |
+
self._mode = "RGBA"
|
420 |
+
self.pixel_format = "BC1"
|
421 |
+
n = 1
|
422 |
+
elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
|
423 |
+
self._mode = "L"
|
424 |
+
self.pixel_format = "BC4"
|
425 |
+
n = 4
|
426 |
+
elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
|
427 |
+
self._mode = "RGB"
|
428 |
+
self.pixel_format = "BC5"
|
429 |
+
n = 5
|
430 |
+
elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
|
431 |
+
self._mode = "RGB"
|
432 |
+
self.pixel_format = "BC5S"
|
433 |
+
n = 5
|
434 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
|
435 |
+
self._mode = "RGB"
|
436 |
+
self.pixel_format = "BC6H"
|
437 |
+
n = 6
|
438 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
|
439 |
+
self._mode = "RGB"
|
440 |
+
self.pixel_format = "BC6HS"
|
441 |
+
n = 6
|
442 |
+
elif dxgi_format in (
|
443 |
+
DXGI_FORMAT.BC7_TYPELESS,
|
444 |
+
DXGI_FORMAT.BC7_UNORM,
|
445 |
+
DXGI_FORMAT.BC7_UNORM_SRGB,
|
446 |
+
):
|
447 |
+
self._mode = "RGBA"
|
448 |
+
self.pixel_format = "BC7"
|
449 |
+
n = 7
|
450 |
+
if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
|
451 |
+
self.info["gamma"] = 1 / 2.2
|
452 |
+
elif dxgi_format in (
|
453 |
+
DXGI_FORMAT.R8G8B8A8_TYPELESS,
|
454 |
+
DXGI_FORMAT.R8G8B8A8_UNORM,
|
455 |
+
DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
|
456 |
+
):
|
457 |
+
self._mode = "RGBA"
|
458 |
+
if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
|
459 |
+
self.info["gamma"] = 1 / 2.2
|
460 |
+
else:
|
461 |
+
msg = f"Unimplemented DXGI format {dxgi_format}"
|
462 |
+
raise NotImplementedError(msg)
|
463 |
+
else:
|
464 |
+
msg = f"Unimplemented pixel format {repr(fourcc)}"
|
465 |
+
raise NotImplementedError(msg)
|
466 |
+
else:
|
467 |
+
msg = f"Unknown pixel format flags {pfflags}"
|
468 |
+
raise NotImplementedError(msg)
|
469 |
+
|
470 |
+
if n:
|
471 |
+
self.tile = [
|
472 |
+
ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
|
473 |
+
]
|
474 |
+
else:
|
475 |
+
self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
|
476 |
+
|
477 |
+
def load_seek(self, pos: int) -> None:
|
478 |
+
pass
|
479 |
+
|
480 |
+
|
481 |
+
class DdsRgbDecoder(ImageFile.PyDecoder):
|
482 |
+
_pulls_fd = True
|
483 |
+
|
484 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
485 |
+
assert self.fd is not None
|
486 |
+
bitcount, masks = self.args
|
487 |
+
|
488 |
+
# Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
|
489 |
+
# Calculate how many zeros each mask is padded with
|
490 |
+
mask_offsets = []
|
491 |
+
# And the maximum value of each channel without the padding
|
492 |
+
mask_totals = []
|
493 |
+
for mask in masks:
|
494 |
+
offset = 0
|
495 |
+
if mask != 0:
|
496 |
+
while mask >> (offset + 1) << (offset + 1) == mask:
|
497 |
+
offset += 1
|
498 |
+
mask_offsets.append(offset)
|
499 |
+
mask_totals.append(mask >> offset)
|
500 |
+
|
501 |
+
data = bytearray()
|
502 |
+
bytecount = bitcount // 8
|
503 |
+
dest_length = self.state.xsize * self.state.ysize * len(masks)
|
504 |
+
while len(data) < dest_length:
|
505 |
+
value = int.from_bytes(self.fd.read(bytecount), "little")
|
506 |
+
for i, mask in enumerate(masks):
|
507 |
+
masked_value = value & mask
|
508 |
+
# Remove the zero padding, and scale it to 8 bits
|
509 |
+
data += o8(
|
510 |
+
int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
|
511 |
+
)
|
512 |
+
self.set_as_raw(data)
|
513 |
+
return -1, 0
|
514 |
+
|
515 |
+
|
516 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
517 |
+
if im.mode not in ("RGB", "RGBA", "L", "LA"):
|
518 |
+
msg = f"cannot write mode {im.mode} as DDS"
|
519 |
+
raise OSError(msg)
|
520 |
+
|
521 |
+
alpha = im.mode[-1] == "A"
|
522 |
+
if im.mode[0] == "L":
|
523 |
+
pixel_flags = DDPF.LUMINANCE
|
524 |
+
rawmode = im.mode
|
525 |
+
if alpha:
|
526 |
+
rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
|
527 |
+
else:
|
528 |
+
rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
|
529 |
+
else:
|
530 |
+
pixel_flags = DDPF.RGB
|
531 |
+
rawmode = im.mode[::-1]
|
532 |
+
rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
|
533 |
+
|
534 |
+
if alpha:
|
535 |
+
r, g, b, a = im.split()
|
536 |
+
im = Image.merge("RGBA", (a, r, g, b))
|
537 |
+
if alpha:
|
538 |
+
pixel_flags |= DDPF.ALPHAPIXELS
|
539 |
+
rgba_mask.append(0xFF000000 if alpha else 0)
|
540 |
+
|
541 |
+
flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PITCH | DDSD.PIXELFORMAT
|
542 |
+
bitcount = len(im.getbands()) * 8
|
543 |
+
pitch = (im.width * bitcount + 7) // 8
|
544 |
+
|
545 |
+
fp.write(
|
546 |
+
o32(DDS_MAGIC)
|
547 |
+
+ struct.pack(
|
548 |
+
"<7I",
|
549 |
+
124, # header size
|
550 |
+
flags, # flags
|
551 |
+
im.height,
|
552 |
+
im.width,
|
553 |
+
pitch,
|
554 |
+
0, # depth
|
555 |
+
0, # mipmaps
|
556 |
+
)
|
557 |
+
+ struct.pack("11I", *((0,) * 11)) # reserved
|
558 |
+
# pfsize, pfflags, fourcc, bitcount
|
559 |
+
+ struct.pack("<4I", 32, pixel_flags, 0, bitcount)
|
560 |
+
+ struct.pack("<4I", *rgba_mask) # dwRGBABitMask
|
561 |
+
+ struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
|
562 |
+
)
|
563 |
+
ImageFile._save(
|
564 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]
|
565 |
+
)
|
566 |
+
|
567 |
+
|
568 |
+
def _accept(prefix: bytes) -> bool:
|
569 |
+
return prefix[:4] == b"DDS "
|
570 |
+
|
571 |
+
|
572 |
+
Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
|
573 |
+
Image.register_decoder("dds_rgb", DdsRgbDecoder)
|
574 |
+
Image.register_save(DdsImageFile.format, _save)
|
575 |
+
Image.register_extension(DdsImageFile.format, ".dds")
|
MLPY/Lib/site-packages/PIL/EpsImagePlugin.py
ADDED
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# EPS file handling
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1995-09-01 fl Created (0.1)
|
9 |
+
# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
|
10 |
+
# 1996-08-22 fl Don't choke on floating point BoundingBox values
|
11 |
+
# 1996-08-23 fl Handle files from Macintosh (0.3)
|
12 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
|
13 |
+
# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
|
14 |
+
# 2014-05-07 e Handling of EPS with binary preview and fixed resolution
|
15 |
+
# resizing
|
16 |
+
#
|
17 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
18 |
+
# Copyright (c) 1995-2003 by Fredrik Lundh
|
19 |
+
#
|
20 |
+
# See the README file for information on usage and redistribution.
|
21 |
+
#
|
22 |
+
from __future__ import annotations
|
23 |
+
|
24 |
+
import io
|
25 |
+
import os
|
26 |
+
import re
|
27 |
+
import subprocess
|
28 |
+
import sys
|
29 |
+
import tempfile
|
30 |
+
from typing import IO
|
31 |
+
|
32 |
+
from . import Image, ImageFile
|
33 |
+
from ._binary import i32le as i32
|
34 |
+
from ._deprecate import deprecate
|
35 |
+
|
36 |
+
# --------------------------------------------------------------------
|
37 |
+
|
38 |
+
|
39 |
+
split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
|
40 |
+
field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
|
41 |
+
|
42 |
+
gs_binary: str | bool | None = None
|
43 |
+
gs_windows_binary = None
|
44 |
+
|
45 |
+
|
46 |
+
def has_ghostscript() -> bool:
|
47 |
+
global gs_binary, gs_windows_binary
|
48 |
+
if gs_binary is None:
|
49 |
+
if sys.platform.startswith("win"):
|
50 |
+
if gs_windows_binary is None:
|
51 |
+
import shutil
|
52 |
+
|
53 |
+
for binary in ("gswin32c", "gswin64c", "gs"):
|
54 |
+
if shutil.which(binary) is not None:
|
55 |
+
gs_windows_binary = binary
|
56 |
+
break
|
57 |
+
else:
|
58 |
+
gs_windows_binary = False
|
59 |
+
gs_binary = gs_windows_binary
|
60 |
+
else:
|
61 |
+
try:
|
62 |
+
subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
|
63 |
+
gs_binary = "gs"
|
64 |
+
except OSError:
|
65 |
+
gs_binary = False
|
66 |
+
return gs_binary is not False
|
67 |
+
|
68 |
+
|
69 |
+
def Ghostscript(tile, size, fp, scale=1, transparency=False):
|
70 |
+
"""Render an image using Ghostscript"""
|
71 |
+
global gs_binary
|
72 |
+
if not has_ghostscript():
|
73 |
+
msg = "Unable to locate Ghostscript on paths"
|
74 |
+
raise OSError(msg)
|
75 |
+
|
76 |
+
# Unpack decoder tile
|
77 |
+
decoder, tile, offset, data = tile[0]
|
78 |
+
length, bbox = data
|
79 |
+
|
80 |
+
# Hack to support hi-res rendering
|
81 |
+
scale = int(scale) or 1
|
82 |
+
width = size[0] * scale
|
83 |
+
height = size[1] * scale
|
84 |
+
# resolution is dependent on bbox and size
|
85 |
+
res_x = 72.0 * width / (bbox[2] - bbox[0])
|
86 |
+
res_y = 72.0 * height / (bbox[3] - bbox[1])
|
87 |
+
|
88 |
+
out_fd, outfile = tempfile.mkstemp()
|
89 |
+
os.close(out_fd)
|
90 |
+
|
91 |
+
infile_temp = None
|
92 |
+
if hasattr(fp, "name") and os.path.exists(fp.name):
|
93 |
+
infile = fp.name
|
94 |
+
else:
|
95 |
+
in_fd, infile_temp = tempfile.mkstemp()
|
96 |
+
os.close(in_fd)
|
97 |
+
infile = infile_temp
|
98 |
+
|
99 |
+
# Ignore length and offset!
|
100 |
+
# Ghostscript can read it
|
101 |
+
# Copy whole file to read in Ghostscript
|
102 |
+
with open(infile_temp, "wb") as f:
|
103 |
+
# fetch length of fp
|
104 |
+
fp.seek(0, io.SEEK_END)
|
105 |
+
fsize = fp.tell()
|
106 |
+
# ensure start position
|
107 |
+
# go back
|
108 |
+
fp.seek(0)
|
109 |
+
lengthfile = fsize
|
110 |
+
while lengthfile > 0:
|
111 |
+
s = fp.read(min(lengthfile, 100 * 1024))
|
112 |
+
if not s:
|
113 |
+
break
|
114 |
+
lengthfile -= len(s)
|
115 |
+
f.write(s)
|
116 |
+
|
117 |
+
device = "pngalpha" if transparency else "ppmraw"
|
118 |
+
|
119 |
+
# Build Ghostscript command
|
120 |
+
command = [
|
121 |
+
gs_binary,
|
122 |
+
"-q", # quiet mode
|
123 |
+
f"-g{width:d}x{height:d}", # set output geometry (pixels)
|
124 |
+
f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
|
125 |
+
"-dBATCH", # exit after processing
|
126 |
+
"-dNOPAUSE", # don't pause between pages
|
127 |
+
"-dSAFER", # safe mode
|
128 |
+
f"-sDEVICE={device}",
|
129 |
+
f"-sOutputFile={outfile}", # output file
|
130 |
+
# adjust for image origin
|
131 |
+
"-c",
|
132 |
+
f"{-bbox[0]} {-bbox[1]} translate",
|
133 |
+
"-f",
|
134 |
+
infile, # input file
|
135 |
+
# showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
|
136 |
+
"-c",
|
137 |
+
"showpage",
|
138 |
+
]
|
139 |
+
|
140 |
+
# push data through Ghostscript
|
141 |
+
try:
|
142 |
+
startupinfo = None
|
143 |
+
if sys.platform.startswith("win"):
|
144 |
+
startupinfo = subprocess.STARTUPINFO()
|
145 |
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
146 |
+
subprocess.check_call(command, startupinfo=startupinfo)
|
147 |
+
out_im = Image.open(outfile)
|
148 |
+
out_im.load()
|
149 |
+
finally:
|
150 |
+
try:
|
151 |
+
os.unlink(outfile)
|
152 |
+
if infile_temp:
|
153 |
+
os.unlink(infile_temp)
|
154 |
+
except OSError:
|
155 |
+
pass
|
156 |
+
|
157 |
+
im = out_im.im.copy()
|
158 |
+
out_im.close()
|
159 |
+
return im
|
160 |
+
|
161 |
+
|
162 |
+
class PSFile:
|
163 |
+
"""
|
164 |
+
Wrapper for bytesio object that treats either CR or LF as end of line.
|
165 |
+
This class is no longer used internally, but kept for backwards compatibility.
|
166 |
+
"""
|
167 |
+
|
168 |
+
def __init__(self, fp):
|
169 |
+
deprecate(
|
170 |
+
"PSFile",
|
171 |
+
11,
|
172 |
+
action="If you need the functionality of this class "
|
173 |
+
"you will need to implement it yourself.",
|
174 |
+
)
|
175 |
+
self.fp = fp
|
176 |
+
self.char = None
|
177 |
+
|
178 |
+
def seek(self, offset, whence=io.SEEK_SET):
|
179 |
+
self.char = None
|
180 |
+
self.fp.seek(offset, whence)
|
181 |
+
|
182 |
+
def readline(self) -> str:
|
183 |
+
s = [self.char or b""]
|
184 |
+
self.char = None
|
185 |
+
|
186 |
+
c = self.fp.read(1)
|
187 |
+
while (c not in b"\r\n") and len(c):
|
188 |
+
s.append(c)
|
189 |
+
c = self.fp.read(1)
|
190 |
+
|
191 |
+
self.char = self.fp.read(1)
|
192 |
+
# line endings can be 1 or 2 of \r \n, in either order
|
193 |
+
if self.char in b"\r\n":
|
194 |
+
self.char = None
|
195 |
+
|
196 |
+
return b"".join(s).decode("latin-1")
|
197 |
+
|
198 |
+
|
199 |
+
def _accept(prefix: bytes) -> bool:
|
200 |
+
return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)
|
201 |
+
|
202 |
+
|
203 |
+
##
|
204 |
+
# Image plugin for Encapsulated PostScript. This plugin supports only
|
205 |
+
# a few variants of this format.
|
206 |
+
|
207 |
+
|
208 |
+
class EpsImageFile(ImageFile.ImageFile):
|
209 |
+
"""EPS File Parser for the Python Imaging Library"""
|
210 |
+
|
211 |
+
format = "EPS"
|
212 |
+
format_description = "Encapsulated Postscript"
|
213 |
+
|
214 |
+
mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
|
215 |
+
|
216 |
+
def _open(self) -> None:
|
217 |
+
(length, offset) = self._find_offset(self.fp)
|
218 |
+
|
219 |
+
# go to offset - start of "%!PS"
|
220 |
+
self.fp.seek(offset)
|
221 |
+
|
222 |
+
self._mode = "RGB"
|
223 |
+
self._size = None
|
224 |
+
|
225 |
+
byte_arr = bytearray(255)
|
226 |
+
bytes_mv = memoryview(byte_arr)
|
227 |
+
bytes_read = 0
|
228 |
+
reading_header_comments = True
|
229 |
+
reading_trailer_comments = False
|
230 |
+
trailer_reached = False
|
231 |
+
|
232 |
+
def check_required_header_comments() -> None:
|
233 |
+
"""
|
234 |
+
The EPS specification requires that some headers exist.
|
235 |
+
This should be checked when the header comments formally end,
|
236 |
+
when image data starts, or when the file ends, whichever comes first.
|
237 |
+
"""
|
238 |
+
if "PS-Adobe" not in self.info:
|
239 |
+
msg = 'EPS header missing "%!PS-Adobe" comment'
|
240 |
+
raise SyntaxError(msg)
|
241 |
+
if "BoundingBox" not in self.info:
|
242 |
+
msg = 'EPS header missing "%%BoundingBox" comment'
|
243 |
+
raise SyntaxError(msg)
|
244 |
+
|
245 |
+
def _read_comment(s: str) -> bool:
|
246 |
+
nonlocal reading_trailer_comments
|
247 |
+
try:
|
248 |
+
m = split.match(s)
|
249 |
+
except re.error as e:
|
250 |
+
msg = "not an EPS file"
|
251 |
+
raise SyntaxError(msg) from e
|
252 |
+
|
253 |
+
if not m:
|
254 |
+
return False
|
255 |
+
|
256 |
+
k, v = m.group(1, 2)
|
257 |
+
self.info[k] = v
|
258 |
+
if k == "BoundingBox":
|
259 |
+
if v == "(atend)":
|
260 |
+
reading_trailer_comments = True
|
261 |
+
elif not self._size or (trailer_reached and reading_trailer_comments):
|
262 |
+
try:
|
263 |
+
# Note: The DSC spec says that BoundingBox
|
264 |
+
# fields should be integers, but some drivers
|
265 |
+
# put floating point values there anyway.
|
266 |
+
box = [int(float(i)) for i in v.split()]
|
267 |
+
self._size = box[2] - box[0], box[3] - box[1]
|
268 |
+
self.tile = [("eps", (0, 0) + self.size, offset, (length, box))]
|
269 |
+
except Exception:
|
270 |
+
pass
|
271 |
+
return True
|
272 |
+
|
273 |
+
while True:
|
274 |
+
byte = self.fp.read(1)
|
275 |
+
if byte == b"":
|
276 |
+
# if we didn't read a byte we must be at the end of the file
|
277 |
+
if bytes_read == 0:
|
278 |
+
if reading_header_comments:
|
279 |
+
check_required_header_comments()
|
280 |
+
break
|
281 |
+
elif byte in b"\r\n":
|
282 |
+
# if we read a line ending character, ignore it and parse what
|
283 |
+
# we have already read. if we haven't read any other characters,
|
284 |
+
# continue reading
|
285 |
+
if bytes_read == 0:
|
286 |
+
continue
|
287 |
+
else:
|
288 |
+
# ASCII/hexadecimal lines in an EPS file must not exceed
|
289 |
+
# 255 characters, not including line ending characters
|
290 |
+
if bytes_read >= 255:
|
291 |
+
# only enforce this for lines starting with a "%",
|
292 |
+
# otherwise assume it's binary data
|
293 |
+
if byte_arr[0] == ord("%"):
|
294 |
+
msg = "not an EPS file"
|
295 |
+
raise SyntaxError(msg)
|
296 |
+
else:
|
297 |
+
if reading_header_comments:
|
298 |
+
check_required_header_comments()
|
299 |
+
reading_header_comments = False
|
300 |
+
# reset bytes_read so we can keep reading
|
301 |
+
# data until the end of the line
|
302 |
+
bytes_read = 0
|
303 |
+
byte_arr[bytes_read] = byte[0]
|
304 |
+
bytes_read += 1
|
305 |
+
continue
|
306 |
+
|
307 |
+
if reading_header_comments:
|
308 |
+
# Load EPS header
|
309 |
+
|
310 |
+
# if this line doesn't start with a "%",
|
311 |
+
# or does start with "%%EndComments",
|
312 |
+
# then we've reached the end of the header/comments
|
313 |
+
if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
|
314 |
+
check_required_header_comments()
|
315 |
+
reading_header_comments = False
|
316 |
+
continue
|
317 |
+
|
318 |
+
s = str(bytes_mv[:bytes_read], "latin-1")
|
319 |
+
if not _read_comment(s):
|
320 |
+
m = field.match(s)
|
321 |
+
if m:
|
322 |
+
k = m.group(1)
|
323 |
+
if k[:8] == "PS-Adobe":
|
324 |
+
self.info["PS-Adobe"] = k[9:]
|
325 |
+
else:
|
326 |
+
self.info[k] = ""
|
327 |
+
elif s[0] == "%":
|
328 |
+
# handle non-DSC PostScript comments that some
|
329 |
+
# tools mistakenly put in the Comments section
|
330 |
+
pass
|
331 |
+
else:
|
332 |
+
msg = "bad EPS header"
|
333 |
+
raise OSError(msg)
|
334 |
+
elif bytes_mv[:11] == b"%ImageData:":
|
335 |
+
# Check for an "ImageData" descriptor
|
336 |
+
# https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
|
337 |
+
|
338 |
+
# Values:
|
339 |
+
# columns
|
340 |
+
# rows
|
341 |
+
# bit depth (1 or 8)
|
342 |
+
# mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
|
343 |
+
# number of padding channels
|
344 |
+
# block size (number of bytes per row per channel)
|
345 |
+
# binary/ascii (1: binary, 2: ascii)
|
346 |
+
# data start identifier (the image data follows after a single line
|
347 |
+
# consisting only of this quoted value)
|
348 |
+
image_data_values = byte_arr[11:bytes_read].split(None, 7)
|
349 |
+
columns, rows, bit_depth, mode_id = (
|
350 |
+
int(value) for value in image_data_values[:4]
|
351 |
+
)
|
352 |
+
|
353 |
+
if bit_depth == 1:
|
354 |
+
self._mode = "1"
|
355 |
+
elif bit_depth == 8:
|
356 |
+
try:
|
357 |
+
self._mode = self.mode_map[mode_id]
|
358 |
+
except ValueError:
|
359 |
+
break
|
360 |
+
else:
|
361 |
+
break
|
362 |
+
|
363 |
+
self._size = columns, rows
|
364 |
+
return
|
365 |
+
elif bytes_mv[:5] == b"%%EOF":
|
366 |
+
break
|
367 |
+
elif trailer_reached and reading_trailer_comments:
|
368 |
+
# Load EPS trailer
|
369 |
+
s = str(bytes_mv[:bytes_read], "latin-1")
|
370 |
+
_read_comment(s)
|
371 |
+
elif bytes_mv[:9] == b"%%Trailer":
|
372 |
+
trailer_reached = True
|
373 |
+
bytes_read = 0
|
374 |
+
|
375 |
+
if not self._size:
|
376 |
+
msg = "cannot determine EPS bounding box"
|
377 |
+
raise OSError(msg)
|
378 |
+
|
379 |
+
def _find_offset(self, fp):
|
380 |
+
s = fp.read(4)
|
381 |
+
|
382 |
+
if s == b"%!PS":
|
383 |
+
# for HEAD without binary preview
|
384 |
+
fp.seek(0, io.SEEK_END)
|
385 |
+
length = fp.tell()
|
386 |
+
offset = 0
|
387 |
+
elif i32(s) == 0xC6D3D0C5:
|
388 |
+
# FIX for: Some EPS file not handled correctly / issue #302
|
389 |
+
# EPS can contain binary data
|
390 |
+
# or start directly with latin coding
|
391 |
+
# more info see:
|
392 |
+
# https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
|
393 |
+
s = fp.read(8)
|
394 |
+
offset = i32(s)
|
395 |
+
length = i32(s, 4)
|
396 |
+
else:
|
397 |
+
msg = "not an EPS file"
|
398 |
+
raise SyntaxError(msg)
|
399 |
+
|
400 |
+
return length, offset
|
401 |
+
|
402 |
+
def load(self, scale=1, transparency=False):
|
403 |
+
# Load EPS via Ghostscript
|
404 |
+
if self.tile:
|
405 |
+
self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
|
406 |
+
self._mode = self.im.mode
|
407 |
+
self._size = self.im.size
|
408 |
+
self.tile = []
|
409 |
+
return Image.Image.load(self)
|
410 |
+
|
411 |
+
def load_seek(self, pos: int) -> None:
|
412 |
+
# we can't incrementally load, so force ImageFile.parser to
|
413 |
+
# use our custom load method by defining this method.
|
414 |
+
pass
|
415 |
+
|
416 |
+
|
417 |
+
# --------------------------------------------------------------------
|
418 |
+
|
419 |
+
|
420 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
|
421 |
+
"""EPS Writer for the Python Imaging Library."""
|
422 |
+
|
423 |
+
# make sure image data is available
|
424 |
+
im.load()
|
425 |
+
|
426 |
+
# determine PostScript image mode
|
427 |
+
if im.mode == "L":
|
428 |
+
operator = (8, 1, b"image")
|
429 |
+
elif im.mode == "RGB":
|
430 |
+
operator = (8, 3, b"false 3 colorimage")
|
431 |
+
elif im.mode == "CMYK":
|
432 |
+
operator = (8, 4, b"false 4 colorimage")
|
433 |
+
else:
|
434 |
+
msg = "image mode is not supported"
|
435 |
+
raise ValueError(msg)
|
436 |
+
|
437 |
+
if eps:
|
438 |
+
# write EPS header
|
439 |
+
fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
|
440 |
+
fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
|
441 |
+
# fp.write("%%CreationDate: %s"...)
|
442 |
+
fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
|
443 |
+
fp.write(b"%%Pages: 1\n")
|
444 |
+
fp.write(b"%%EndComments\n")
|
445 |
+
fp.write(b"%%Page: 1 1\n")
|
446 |
+
fp.write(b"%%ImageData: %d %d " % im.size)
|
447 |
+
fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
|
448 |
+
|
449 |
+
# image header
|
450 |
+
fp.write(b"gsave\n")
|
451 |
+
fp.write(b"10 dict begin\n")
|
452 |
+
fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
|
453 |
+
fp.write(b"%d %d scale\n" % im.size)
|
454 |
+
fp.write(b"%d %d 8\n" % im.size) # <= bits
|
455 |
+
fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
|
456 |
+
fp.write(b"{ currentfile buf readhexstring pop } bind\n")
|
457 |
+
fp.write(operator[2] + b"\n")
|
458 |
+
if hasattr(fp, "flush"):
|
459 |
+
fp.flush()
|
460 |
+
|
461 |
+
ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)])
|
462 |
+
|
463 |
+
fp.write(b"\n%%%%EndBinary\n")
|
464 |
+
fp.write(b"grestore end\n")
|
465 |
+
if hasattr(fp, "flush"):
|
466 |
+
fp.flush()
|
467 |
+
|
468 |
+
|
469 |
+
# --------------------------------------------------------------------
|
470 |
+
|
471 |
+
|
472 |
+
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
|
473 |
+
|
474 |
+
Image.register_save(EpsImageFile.format, _save)
|
475 |
+
|
476 |
+
Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
|
477 |
+
|
478 |
+
Image.register_mime(EpsImageFile.format, "application/postscript")
|
MLPY/Lib/site-packages/PIL/ExifTags.py
ADDED
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# EXIF tags
|
6 |
+
#
|
7 |
+
# Copyright (c) 2003 by Secret Labs AB
|
8 |
+
#
|
9 |
+
# See the README file for information on usage and redistribution.
|
10 |
+
#
|
11 |
+
|
12 |
+
"""
|
13 |
+
This module provides constants and clear-text names for various
|
14 |
+
well-known EXIF tags.
|
15 |
+
"""
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
from enum import IntEnum
|
19 |
+
|
20 |
+
|
21 |
+
class Base(IntEnum):
|
22 |
+
# possibly incomplete
|
23 |
+
InteropIndex = 0x0001
|
24 |
+
ProcessingSoftware = 0x000B
|
25 |
+
NewSubfileType = 0x00FE
|
26 |
+
SubfileType = 0x00FF
|
27 |
+
ImageWidth = 0x0100
|
28 |
+
ImageLength = 0x0101
|
29 |
+
BitsPerSample = 0x0102
|
30 |
+
Compression = 0x0103
|
31 |
+
PhotometricInterpretation = 0x0106
|
32 |
+
Thresholding = 0x0107
|
33 |
+
CellWidth = 0x0108
|
34 |
+
CellLength = 0x0109
|
35 |
+
FillOrder = 0x010A
|
36 |
+
DocumentName = 0x010D
|
37 |
+
ImageDescription = 0x010E
|
38 |
+
Make = 0x010F
|
39 |
+
Model = 0x0110
|
40 |
+
StripOffsets = 0x0111
|
41 |
+
Orientation = 0x0112
|
42 |
+
SamplesPerPixel = 0x0115
|
43 |
+
RowsPerStrip = 0x0116
|
44 |
+
StripByteCounts = 0x0117
|
45 |
+
MinSampleValue = 0x0118
|
46 |
+
MaxSampleValue = 0x0119
|
47 |
+
XResolution = 0x011A
|
48 |
+
YResolution = 0x011B
|
49 |
+
PlanarConfiguration = 0x011C
|
50 |
+
PageName = 0x011D
|
51 |
+
FreeOffsets = 0x0120
|
52 |
+
FreeByteCounts = 0x0121
|
53 |
+
GrayResponseUnit = 0x0122
|
54 |
+
GrayResponseCurve = 0x0123
|
55 |
+
T4Options = 0x0124
|
56 |
+
T6Options = 0x0125
|
57 |
+
ResolutionUnit = 0x0128
|
58 |
+
PageNumber = 0x0129
|
59 |
+
TransferFunction = 0x012D
|
60 |
+
Software = 0x0131
|
61 |
+
DateTime = 0x0132
|
62 |
+
Artist = 0x013B
|
63 |
+
HostComputer = 0x013C
|
64 |
+
Predictor = 0x013D
|
65 |
+
WhitePoint = 0x013E
|
66 |
+
PrimaryChromaticities = 0x013F
|
67 |
+
ColorMap = 0x0140
|
68 |
+
HalftoneHints = 0x0141
|
69 |
+
TileWidth = 0x0142
|
70 |
+
TileLength = 0x0143
|
71 |
+
TileOffsets = 0x0144
|
72 |
+
TileByteCounts = 0x0145
|
73 |
+
SubIFDs = 0x014A
|
74 |
+
InkSet = 0x014C
|
75 |
+
InkNames = 0x014D
|
76 |
+
NumberOfInks = 0x014E
|
77 |
+
DotRange = 0x0150
|
78 |
+
TargetPrinter = 0x0151
|
79 |
+
ExtraSamples = 0x0152
|
80 |
+
SampleFormat = 0x0153
|
81 |
+
SMinSampleValue = 0x0154
|
82 |
+
SMaxSampleValue = 0x0155
|
83 |
+
TransferRange = 0x0156
|
84 |
+
ClipPath = 0x0157
|
85 |
+
XClipPathUnits = 0x0158
|
86 |
+
YClipPathUnits = 0x0159
|
87 |
+
Indexed = 0x015A
|
88 |
+
JPEGTables = 0x015B
|
89 |
+
OPIProxy = 0x015F
|
90 |
+
JPEGProc = 0x0200
|
91 |
+
JpegIFOffset = 0x0201
|
92 |
+
JpegIFByteCount = 0x0202
|
93 |
+
JpegRestartInterval = 0x0203
|
94 |
+
JpegLosslessPredictors = 0x0205
|
95 |
+
JpegPointTransforms = 0x0206
|
96 |
+
JpegQTables = 0x0207
|
97 |
+
JpegDCTables = 0x0208
|
98 |
+
JpegACTables = 0x0209
|
99 |
+
YCbCrCoefficients = 0x0211
|
100 |
+
YCbCrSubSampling = 0x0212
|
101 |
+
YCbCrPositioning = 0x0213
|
102 |
+
ReferenceBlackWhite = 0x0214
|
103 |
+
XMLPacket = 0x02BC
|
104 |
+
RelatedImageFileFormat = 0x1000
|
105 |
+
RelatedImageWidth = 0x1001
|
106 |
+
RelatedImageLength = 0x1002
|
107 |
+
Rating = 0x4746
|
108 |
+
RatingPercent = 0x4749
|
109 |
+
ImageID = 0x800D
|
110 |
+
CFARepeatPatternDim = 0x828D
|
111 |
+
BatteryLevel = 0x828F
|
112 |
+
Copyright = 0x8298
|
113 |
+
ExposureTime = 0x829A
|
114 |
+
FNumber = 0x829D
|
115 |
+
IPTCNAA = 0x83BB
|
116 |
+
ImageResources = 0x8649
|
117 |
+
ExifOffset = 0x8769
|
118 |
+
InterColorProfile = 0x8773
|
119 |
+
ExposureProgram = 0x8822
|
120 |
+
SpectralSensitivity = 0x8824
|
121 |
+
GPSInfo = 0x8825
|
122 |
+
ISOSpeedRatings = 0x8827
|
123 |
+
OECF = 0x8828
|
124 |
+
Interlace = 0x8829
|
125 |
+
TimeZoneOffset = 0x882A
|
126 |
+
SelfTimerMode = 0x882B
|
127 |
+
SensitivityType = 0x8830
|
128 |
+
StandardOutputSensitivity = 0x8831
|
129 |
+
RecommendedExposureIndex = 0x8832
|
130 |
+
ISOSpeed = 0x8833
|
131 |
+
ISOSpeedLatitudeyyy = 0x8834
|
132 |
+
ISOSpeedLatitudezzz = 0x8835
|
133 |
+
ExifVersion = 0x9000
|
134 |
+
DateTimeOriginal = 0x9003
|
135 |
+
DateTimeDigitized = 0x9004
|
136 |
+
OffsetTime = 0x9010
|
137 |
+
OffsetTimeOriginal = 0x9011
|
138 |
+
OffsetTimeDigitized = 0x9012
|
139 |
+
ComponentsConfiguration = 0x9101
|
140 |
+
CompressedBitsPerPixel = 0x9102
|
141 |
+
ShutterSpeedValue = 0x9201
|
142 |
+
ApertureValue = 0x9202
|
143 |
+
BrightnessValue = 0x9203
|
144 |
+
ExposureBiasValue = 0x9204
|
145 |
+
MaxApertureValue = 0x9205
|
146 |
+
SubjectDistance = 0x9206
|
147 |
+
MeteringMode = 0x9207
|
148 |
+
LightSource = 0x9208
|
149 |
+
Flash = 0x9209
|
150 |
+
FocalLength = 0x920A
|
151 |
+
Noise = 0x920D
|
152 |
+
ImageNumber = 0x9211
|
153 |
+
SecurityClassification = 0x9212
|
154 |
+
ImageHistory = 0x9213
|
155 |
+
TIFFEPStandardID = 0x9216
|
156 |
+
MakerNote = 0x927C
|
157 |
+
UserComment = 0x9286
|
158 |
+
SubsecTime = 0x9290
|
159 |
+
SubsecTimeOriginal = 0x9291
|
160 |
+
SubsecTimeDigitized = 0x9292
|
161 |
+
AmbientTemperature = 0x9400
|
162 |
+
Humidity = 0x9401
|
163 |
+
Pressure = 0x9402
|
164 |
+
WaterDepth = 0x9403
|
165 |
+
Acceleration = 0x9404
|
166 |
+
CameraElevationAngle = 0x9405
|
167 |
+
XPTitle = 0x9C9B
|
168 |
+
XPComment = 0x9C9C
|
169 |
+
XPAuthor = 0x9C9D
|
170 |
+
XPKeywords = 0x9C9E
|
171 |
+
XPSubject = 0x9C9F
|
172 |
+
FlashPixVersion = 0xA000
|
173 |
+
ColorSpace = 0xA001
|
174 |
+
ExifImageWidth = 0xA002
|
175 |
+
ExifImageHeight = 0xA003
|
176 |
+
RelatedSoundFile = 0xA004
|
177 |
+
ExifInteroperabilityOffset = 0xA005
|
178 |
+
FlashEnergy = 0xA20B
|
179 |
+
SpatialFrequencyResponse = 0xA20C
|
180 |
+
FocalPlaneXResolution = 0xA20E
|
181 |
+
FocalPlaneYResolution = 0xA20F
|
182 |
+
FocalPlaneResolutionUnit = 0xA210
|
183 |
+
SubjectLocation = 0xA214
|
184 |
+
ExposureIndex = 0xA215
|
185 |
+
SensingMethod = 0xA217
|
186 |
+
FileSource = 0xA300
|
187 |
+
SceneType = 0xA301
|
188 |
+
CFAPattern = 0xA302
|
189 |
+
CustomRendered = 0xA401
|
190 |
+
ExposureMode = 0xA402
|
191 |
+
WhiteBalance = 0xA403
|
192 |
+
DigitalZoomRatio = 0xA404
|
193 |
+
FocalLengthIn35mmFilm = 0xA405
|
194 |
+
SceneCaptureType = 0xA406
|
195 |
+
GainControl = 0xA407
|
196 |
+
Contrast = 0xA408
|
197 |
+
Saturation = 0xA409
|
198 |
+
Sharpness = 0xA40A
|
199 |
+
DeviceSettingDescription = 0xA40B
|
200 |
+
SubjectDistanceRange = 0xA40C
|
201 |
+
ImageUniqueID = 0xA420
|
202 |
+
CameraOwnerName = 0xA430
|
203 |
+
BodySerialNumber = 0xA431
|
204 |
+
LensSpecification = 0xA432
|
205 |
+
LensMake = 0xA433
|
206 |
+
LensModel = 0xA434
|
207 |
+
LensSerialNumber = 0xA435
|
208 |
+
CompositeImage = 0xA460
|
209 |
+
CompositeImageCount = 0xA461
|
210 |
+
CompositeImageExposureTimes = 0xA462
|
211 |
+
Gamma = 0xA500
|
212 |
+
PrintImageMatching = 0xC4A5
|
213 |
+
DNGVersion = 0xC612
|
214 |
+
DNGBackwardVersion = 0xC613
|
215 |
+
UniqueCameraModel = 0xC614
|
216 |
+
LocalizedCameraModel = 0xC615
|
217 |
+
CFAPlaneColor = 0xC616
|
218 |
+
CFALayout = 0xC617
|
219 |
+
LinearizationTable = 0xC618
|
220 |
+
BlackLevelRepeatDim = 0xC619
|
221 |
+
BlackLevel = 0xC61A
|
222 |
+
BlackLevelDeltaH = 0xC61B
|
223 |
+
BlackLevelDeltaV = 0xC61C
|
224 |
+
WhiteLevel = 0xC61D
|
225 |
+
DefaultScale = 0xC61E
|
226 |
+
DefaultCropOrigin = 0xC61F
|
227 |
+
DefaultCropSize = 0xC620
|
228 |
+
ColorMatrix1 = 0xC621
|
229 |
+
ColorMatrix2 = 0xC622
|
230 |
+
CameraCalibration1 = 0xC623
|
231 |
+
CameraCalibration2 = 0xC624
|
232 |
+
ReductionMatrix1 = 0xC625
|
233 |
+
ReductionMatrix2 = 0xC626
|
234 |
+
AnalogBalance = 0xC627
|
235 |
+
AsShotNeutral = 0xC628
|
236 |
+
AsShotWhiteXY = 0xC629
|
237 |
+
BaselineExposure = 0xC62A
|
238 |
+
BaselineNoise = 0xC62B
|
239 |
+
BaselineSharpness = 0xC62C
|
240 |
+
BayerGreenSplit = 0xC62D
|
241 |
+
LinearResponseLimit = 0xC62E
|
242 |
+
CameraSerialNumber = 0xC62F
|
243 |
+
LensInfo = 0xC630
|
244 |
+
ChromaBlurRadius = 0xC631
|
245 |
+
AntiAliasStrength = 0xC632
|
246 |
+
ShadowScale = 0xC633
|
247 |
+
DNGPrivateData = 0xC634
|
248 |
+
MakerNoteSafety = 0xC635
|
249 |
+
CalibrationIlluminant1 = 0xC65A
|
250 |
+
CalibrationIlluminant2 = 0xC65B
|
251 |
+
BestQualityScale = 0xC65C
|
252 |
+
RawDataUniqueID = 0xC65D
|
253 |
+
OriginalRawFileName = 0xC68B
|
254 |
+
OriginalRawFileData = 0xC68C
|
255 |
+
ActiveArea = 0xC68D
|
256 |
+
MaskedAreas = 0xC68E
|
257 |
+
AsShotICCProfile = 0xC68F
|
258 |
+
AsShotPreProfileMatrix = 0xC690
|
259 |
+
CurrentICCProfile = 0xC691
|
260 |
+
CurrentPreProfileMatrix = 0xC692
|
261 |
+
ColorimetricReference = 0xC6BF
|
262 |
+
CameraCalibrationSignature = 0xC6F3
|
263 |
+
ProfileCalibrationSignature = 0xC6F4
|
264 |
+
AsShotProfileName = 0xC6F6
|
265 |
+
NoiseReductionApplied = 0xC6F7
|
266 |
+
ProfileName = 0xC6F8
|
267 |
+
ProfileHueSatMapDims = 0xC6F9
|
268 |
+
ProfileHueSatMapData1 = 0xC6FA
|
269 |
+
ProfileHueSatMapData2 = 0xC6FB
|
270 |
+
ProfileToneCurve = 0xC6FC
|
271 |
+
ProfileEmbedPolicy = 0xC6FD
|
272 |
+
ProfileCopyright = 0xC6FE
|
273 |
+
ForwardMatrix1 = 0xC714
|
274 |
+
ForwardMatrix2 = 0xC715
|
275 |
+
PreviewApplicationName = 0xC716
|
276 |
+
PreviewApplicationVersion = 0xC717
|
277 |
+
PreviewSettingsName = 0xC718
|
278 |
+
PreviewSettingsDigest = 0xC719
|
279 |
+
PreviewColorSpace = 0xC71A
|
280 |
+
PreviewDateTime = 0xC71B
|
281 |
+
RawImageDigest = 0xC71C
|
282 |
+
OriginalRawFileDigest = 0xC71D
|
283 |
+
SubTileBlockSize = 0xC71E
|
284 |
+
RowInterleaveFactor = 0xC71F
|
285 |
+
ProfileLookTableDims = 0xC725
|
286 |
+
ProfileLookTableData = 0xC726
|
287 |
+
OpcodeList1 = 0xC740
|
288 |
+
OpcodeList2 = 0xC741
|
289 |
+
OpcodeList3 = 0xC74E
|
290 |
+
NoiseProfile = 0xC761
|
291 |
+
|
292 |
+
|
293 |
+
"""Maps EXIF tags to tag names."""
|
294 |
+
TAGS = {
|
295 |
+
**{i.value: i.name for i in Base},
|
296 |
+
0x920C: "SpatialFrequencyResponse",
|
297 |
+
0x9214: "SubjectLocation",
|
298 |
+
0x9215: "ExposureIndex",
|
299 |
+
0x828E: "CFAPattern",
|
300 |
+
0x920B: "FlashEnergy",
|
301 |
+
0x9216: "TIFF/EPStandardID",
|
302 |
+
}
|
303 |
+
|
304 |
+
|
305 |
+
class GPS(IntEnum):
|
306 |
+
GPSVersionID = 0
|
307 |
+
GPSLatitudeRef = 1
|
308 |
+
GPSLatitude = 2
|
309 |
+
GPSLongitudeRef = 3
|
310 |
+
GPSLongitude = 4
|
311 |
+
GPSAltitudeRef = 5
|
312 |
+
GPSAltitude = 6
|
313 |
+
GPSTimeStamp = 7
|
314 |
+
GPSSatellites = 8
|
315 |
+
GPSStatus = 9
|
316 |
+
GPSMeasureMode = 10
|
317 |
+
GPSDOP = 11
|
318 |
+
GPSSpeedRef = 12
|
319 |
+
GPSSpeed = 13
|
320 |
+
GPSTrackRef = 14
|
321 |
+
GPSTrack = 15
|
322 |
+
GPSImgDirectionRef = 16
|
323 |
+
GPSImgDirection = 17
|
324 |
+
GPSMapDatum = 18
|
325 |
+
GPSDestLatitudeRef = 19
|
326 |
+
GPSDestLatitude = 20
|
327 |
+
GPSDestLongitudeRef = 21
|
328 |
+
GPSDestLongitude = 22
|
329 |
+
GPSDestBearingRef = 23
|
330 |
+
GPSDestBearing = 24
|
331 |
+
GPSDestDistanceRef = 25
|
332 |
+
GPSDestDistance = 26
|
333 |
+
GPSProcessingMethod = 27
|
334 |
+
GPSAreaInformation = 28
|
335 |
+
GPSDateStamp = 29
|
336 |
+
GPSDifferential = 30
|
337 |
+
GPSHPositioningError = 31
|
338 |
+
|
339 |
+
|
340 |
+
"""Maps EXIF GPS tags to tag names."""
|
341 |
+
GPSTAGS = {i.value: i.name for i in GPS}
|
342 |
+
|
343 |
+
|
344 |
+
class Interop(IntEnum):
|
345 |
+
InteropIndex = 1
|
346 |
+
InteropVersion = 2
|
347 |
+
RelatedImageFileFormat = 4096
|
348 |
+
RelatedImageWidth = 4097
|
349 |
+
RelatedImageHeight = 4098
|
350 |
+
|
351 |
+
|
352 |
+
class IFD(IntEnum):
|
353 |
+
Exif = 34665
|
354 |
+
GPSInfo = 34853
|
355 |
+
Makernote = 37500
|
356 |
+
Interop = 40965
|
357 |
+
IFD1 = -1
|
358 |
+
|
359 |
+
|
360 |
+
class LightSource(IntEnum):
|
361 |
+
Unknown = 0
|
362 |
+
Daylight = 1
|
363 |
+
Fluorescent = 2
|
364 |
+
Tungsten = 3
|
365 |
+
Flash = 4
|
366 |
+
Fine = 9
|
367 |
+
Cloudy = 10
|
368 |
+
Shade = 11
|
369 |
+
DaylightFluorescent = 12
|
370 |
+
DayWhiteFluorescent = 13
|
371 |
+
CoolWhiteFluorescent = 14
|
372 |
+
WhiteFluorescent = 15
|
373 |
+
StandardLightA = 17
|
374 |
+
StandardLightB = 18
|
375 |
+
StandardLightC = 19
|
376 |
+
D55 = 20
|
377 |
+
D65 = 21
|
378 |
+
D75 = 22
|
379 |
+
D50 = 23
|
380 |
+
ISO = 24
|
381 |
+
Other = 255
|
MLPY/Lib/site-packages/PIL/FitsImagePlugin.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# FITS file handling
|
6 |
+
#
|
7 |
+
# Copyright (c) 1998-2003 by Fredrik Lundh
|
8 |
+
#
|
9 |
+
# See the README file for information on usage and redistribution.
|
10 |
+
#
|
11 |
+
from __future__ import annotations
|
12 |
+
|
13 |
+
import gzip
|
14 |
+
import math
|
15 |
+
|
16 |
+
from . import Image, ImageFile
|
17 |
+
|
18 |
+
|
19 |
+
def _accept(prefix: bytes) -> bool:
|
20 |
+
return prefix[:6] == b"SIMPLE"
|
21 |
+
|
22 |
+
|
23 |
+
class FitsImageFile(ImageFile.ImageFile):
|
24 |
+
format = "FITS"
|
25 |
+
format_description = "FITS"
|
26 |
+
|
27 |
+
def _open(self) -> None:
|
28 |
+
assert self.fp is not None
|
29 |
+
|
30 |
+
headers: dict[bytes, bytes] = {}
|
31 |
+
header_in_progress = False
|
32 |
+
decoder_name = ""
|
33 |
+
while True:
|
34 |
+
header = self.fp.read(80)
|
35 |
+
if not header:
|
36 |
+
msg = "Truncated FITS file"
|
37 |
+
raise OSError(msg)
|
38 |
+
keyword = header[:8].strip()
|
39 |
+
if keyword in (b"SIMPLE", b"XTENSION"):
|
40 |
+
header_in_progress = True
|
41 |
+
elif headers and not header_in_progress:
|
42 |
+
# This is now a data unit
|
43 |
+
break
|
44 |
+
elif keyword == b"END":
|
45 |
+
# Seek to the end of the header unit
|
46 |
+
self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880)
|
47 |
+
if not decoder_name:
|
48 |
+
decoder_name, offset, args = self._parse_headers(headers)
|
49 |
+
|
50 |
+
header_in_progress = False
|
51 |
+
continue
|
52 |
+
|
53 |
+
if decoder_name:
|
54 |
+
# Keep going to read past the headers
|
55 |
+
continue
|
56 |
+
|
57 |
+
value = header[8:].split(b"/")[0].strip()
|
58 |
+
if value.startswith(b"="):
|
59 |
+
value = value[1:].strip()
|
60 |
+
if not headers and (not _accept(keyword) or value != b"T"):
|
61 |
+
msg = "Not a FITS file"
|
62 |
+
raise SyntaxError(msg)
|
63 |
+
headers[keyword] = value
|
64 |
+
|
65 |
+
if not decoder_name:
|
66 |
+
msg = "No image data"
|
67 |
+
raise ValueError(msg)
|
68 |
+
|
69 |
+
offset += self.fp.tell() - 80
|
70 |
+
self.tile = [(decoder_name, (0, 0) + self.size, offset, args)]
|
71 |
+
|
72 |
+
def _get_size(
|
73 |
+
self, headers: dict[bytes, bytes], prefix: bytes
|
74 |
+
) -> tuple[int, int] | None:
|
75 |
+
naxis = int(headers[prefix + b"NAXIS"])
|
76 |
+
if naxis == 0:
|
77 |
+
return None
|
78 |
+
|
79 |
+
if naxis == 1:
|
80 |
+
return 1, int(headers[prefix + b"NAXIS1"])
|
81 |
+
else:
|
82 |
+
return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"])
|
83 |
+
|
84 |
+
def _parse_headers(
|
85 |
+
self, headers: dict[bytes, bytes]
|
86 |
+
) -> tuple[str, int, tuple[str | int, ...]]:
|
87 |
+
prefix = b""
|
88 |
+
decoder_name = "raw"
|
89 |
+
offset = 0
|
90 |
+
if (
|
91 |
+
headers.get(b"XTENSION") == b"'BINTABLE'"
|
92 |
+
and headers.get(b"ZIMAGE") == b"T"
|
93 |
+
and headers[b"ZCMPTYPE"] == b"'GZIP_1 '"
|
94 |
+
):
|
95 |
+
no_prefix_size = self._get_size(headers, prefix) or (0, 0)
|
96 |
+
number_of_bits = int(headers[b"BITPIX"])
|
97 |
+
offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8)
|
98 |
+
|
99 |
+
prefix = b"Z"
|
100 |
+
decoder_name = "fits_gzip"
|
101 |
+
|
102 |
+
size = self._get_size(headers, prefix)
|
103 |
+
if not size:
|
104 |
+
return "", 0, ()
|
105 |
+
|
106 |
+
self._size = size
|
107 |
+
|
108 |
+
number_of_bits = int(headers[prefix + b"BITPIX"])
|
109 |
+
if number_of_bits == 8:
|
110 |
+
self._mode = "L"
|
111 |
+
elif number_of_bits == 16:
|
112 |
+
self._mode = "I;16"
|
113 |
+
elif number_of_bits == 32:
|
114 |
+
self._mode = "I"
|
115 |
+
elif number_of_bits in (-32, -64):
|
116 |
+
self._mode = "F"
|
117 |
+
|
118 |
+
args: tuple[str | int, ...]
|
119 |
+
if decoder_name == "raw":
|
120 |
+
args = (self.mode, 0, -1)
|
121 |
+
else:
|
122 |
+
args = (number_of_bits,)
|
123 |
+
return decoder_name, offset, args
|
124 |
+
|
125 |
+
|
126 |
+
class FitsGzipDecoder(ImageFile.PyDecoder):
|
127 |
+
_pulls_fd = True
|
128 |
+
|
129 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
130 |
+
assert self.fd is not None
|
131 |
+
value = gzip.decompress(self.fd.read())
|
132 |
+
|
133 |
+
rows = []
|
134 |
+
offset = 0
|
135 |
+
number_of_bits = min(self.args[0] // 8, 4)
|
136 |
+
for y in range(self.state.ysize):
|
137 |
+
row = bytearray()
|
138 |
+
for x in range(self.state.xsize):
|
139 |
+
row += value[offset + (4 - number_of_bits) : offset + 4]
|
140 |
+
offset += 4
|
141 |
+
rows.append(row)
|
142 |
+
self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row]))
|
143 |
+
return -1, 0
|
144 |
+
|
145 |
+
|
146 |
+
# --------------------------------------------------------------------
|
147 |
+
# Registry
|
148 |
+
|
149 |
+
Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
|
150 |
+
Image.register_decoder("fits_gzip", FitsGzipDecoder)
|
151 |
+
|
152 |
+
Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
|
MLPY/Lib/site-packages/PIL/FliImagePlugin.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# FLI/FLC file handling.
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 95-09-01 fl Created
|
9 |
+
# 97-01-03 fl Fixed parser, setup decoder tile
|
10 |
+
# 98-07-15 fl Renamed offset attribute to avoid name clash
|
11 |
+
#
|
12 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
13 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
import os
|
20 |
+
|
21 |
+
from . import Image, ImageFile, ImagePalette
|
22 |
+
from ._binary import i16le as i16
|
23 |
+
from ._binary import i32le as i32
|
24 |
+
from ._binary import o8
|
25 |
+
|
26 |
+
#
|
27 |
+
# decoder
|
28 |
+
|
29 |
+
|
30 |
+
def _accept(prefix: bytes) -> bool:
|
31 |
+
return (
|
32 |
+
len(prefix) >= 6
|
33 |
+
and i16(prefix, 4) in [0xAF11, 0xAF12]
|
34 |
+
and i16(prefix, 14) in [0, 3] # flags
|
35 |
+
)
|
36 |
+
|
37 |
+
|
38 |
+
##
|
39 |
+
# Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
|
40 |
+
# method to load individual frames.
|
41 |
+
|
42 |
+
|
43 |
+
class FliImageFile(ImageFile.ImageFile):
|
44 |
+
format = "FLI"
|
45 |
+
format_description = "Autodesk FLI/FLC Animation"
|
46 |
+
_close_exclusive_fp_after_loading = False
|
47 |
+
|
48 |
+
def _open(self):
|
49 |
+
# HEAD
|
50 |
+
s = self.fp.read(128)
|
51 |
+
if not (_accept(s) and s[20:22] == b"\x00\x00"):
|
52 |
+
msg = "not an FLI/FLC file"
|
53 |
+
raise SyntaxError(msg)
|
54 |
+
|
55 |
+
# frames
|
56 |
+
self.n_frames = i16(s, 6)
|
57 |
+
self.is_animated = self.n_frames > 1
|
58 |
+
|
59 |
+
# image characteristics
|
60 |
+
self._mode = "P"
|
61 |
+
self._size = i16(s, 8), i16(s, 10)
|
62 |
+
|
63 |
+
# animation speed
|
64 |
+
duration = i32(s, 16)
|
65 |
+
magic = i16(s, 4)
|
66 |
+
if magic == 0xAF11:
|
67 |
+
duration = (duration * 1000) // 70
|
68 |
+
self.info["duration"] = duration
|
69 |
+
|
70 |
+
# look for palette
|
71 |
+
palette = [(a, a, a) for a in range(256)]
|
72 |
+
|
73 |
+
s = self.fp.read(16)
|
74 |
+
|
75 |
+
self.__offset = 128
|
76 |
+
|
77 |
+
if i16(s, 4) == 0xF100:
|
78 |
+
# prefix chunk; ignore it
|
79 |
+
self.__offset = self.__offset + i32(s)
|
80 |
+
self.fp.seek(self.__offset)
|
81 |
+
s = self.fp.read(16)
|
82 |
+
|
83 |
+
if i16(s, 4) == 0xF1FA:
|
84 |
+
# look for palette chunk
|
85 |
+
number_of_subchunks = i16(s, 6)
|
86 |
+
chunk_size = None
|
87 |
+
for _ in range(number_of_subchunks):
|
88 |
+
if chunk_size is not None:
|
89 |
+
self.fp.seek(chunk_size - 6, os.SEEK_CUR)
|
90 |
+
s = self.fp.read(6)
|
91 |
+
chunk_type = i16(s, 4)
|
92 |
+
if chunk_type in (4, 11):
|
93 |
+
self._palette(palette, 2 if chunk_type == 11 else 0)
|
94 |
+
break
|
95 |
+
chunk_size = i32(s)
|
96 |
+
if not chunk_size:
|
97 |
+
break
|
98 |
+
|
99 |
+
palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette]
|
100 |
+
self.palette = ImagePalette.raw("RGB", b"".join(palette))
|
101 |
+
|
102 |
+
# set things up to decode first frame
|
103 |
+
self.__frame = -1
|
104 |
+
self._fp = self.fp
|
105 |
+
self.__rewind = self.fp.tell()
|
106 |
+
self.seek(0)
|
107 |
+
|
108 |
+
def _palette(self, palette, shift):
|
109 |
+
# load palette
|
110 |
+
|
111 |
+
i = 0
|
112 |
+
for e in range(i16(self.fp.read(2))):
|
113 |
+
s = self.fp.read(2)
|
114 |
+
i = i + s[0]
|
115 |
+
n = s[1]
|
116 |
+
if n == 0:
|
117 |
+
n = 256
|
118 |
+
s = self.fp.read(n * 3)
|
119 |
+
for n in range(0, len(s), 3):
|
120 |
+
r = s[n] << shift
|
121 |
+
g = s[n + 1] << shift
|
122 |
+
b = s[n + 2] << shift
|
123 |
+
palette[i] = (r, g, b)
|
124 |
+
i += 1
|
125 |
+
|
126 |
+
def seek(self, frame: int) -> None:
|
127 |
+
if not self._seek_check(frame):
|
128 |
+
return
|
129 |
+
if frame < self.__frame:
|
130 |
+
self._seek(0)
|
131 |
+
|
132 |
+
for f in range(self.__frame + 1, frame + 1):
|
133 |
+
self._seek(f)
|
134 |
+
|
135 |
+
def _seek(self, frame: int) -> None:
|
136 |
+
if frame == 0:
|
137 |
+
self.__frame = -1
|
138 |
+
self._fp.seek(self.__rewind)
|
139 |
+
self.__offset = 128
|
140 |
+
else:
|
141 |
+
# ensure that the previous frame was loaded
|
142 |
+
self.load()
|
143 |
+
|
144 |
+
if frame != self.__frame + 1:
|
145 |
+
msg = f"cannot seek to frame {frame}"
|
146 |
+
raise ValueError(msg)
|
147 |
+
self.__frame = frame
|
148 |
+
|
149 |
+
# move to next frame
|
150 |
+
self.fp = self._fp
|
151 |
+
self.fp.seek(self.__offset)
|
152 |
+
|
153 |
+
s = self.fp.read(4)
|
154 |
+
if not s:
|
155 |
+
msg = "missing frame size"
|
156 |
+
raise EOFError(msg)
|
157 |
+
|
158 |
+
framesize = i32(s)
|
159 |
+
|
160 |
+
self.decodermaxblock = framesize
|
161 |
+
self.tile = [("fli", (0, 0) + self.size, self.__offset, None)]
|
162 |
+
|
163 |
+
self.__offset += framesize
|
164 |
+
|
165 |
+
def tell(self) -> int:
|
166 |
+
return self.__frame
|
167 |
+
|
168 |
+
|
169 |
+
#
|
170 |
+
# registry
|
171 |
+
|
172 |
+
Image.register_open(FliImageFile.format, FliImageFile, _accept)
|
173 |
+
|
174 |
+
Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
|
MLPY/Lib/site-packages/PIL/FontFile.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# base class for raster font file parsers
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 1997-06-05 fl created
|
9 |
+
# 1997-08-19 fl restrict image width
|
10 |
+
#
|
11 |
+
# Copyright (c) 1997-1998 by Secret Labs AB
|
12 |
+
# Copyright (c) 1997-1998 by Fredrik Lundh
|
13 |
+
#
|
14 |
+
# See the README file for information on usage and redistribution.
|
15 |
+
#
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
import os
|
19 |
+
from typing import BinaryIO
|
20 |
+
|
21 |
+
from . import Image, _binary
|
22 |
+
|
23 |
+
WIDTH = 800
|
24 |
+
|
25 |
+
|
26 |
+
def puti16(
|
27 |
+
fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
|
28 |
+
) -> None:
|
29 |
+
"""Write network order (big-endian) 16-bit sequence"""
|
30 |
+
for v in values:
|
31 |
+
if v < 0:
|
32 |
+
v += 65536
|
33 |
+
fp.write(_binary.o16be(v))
|
34 |
+
|
35 |
+
|
36 |
+
class FontFile:
|
37 |
+
"""Base class for raster font file handlers."""
|
38 |
+
|
39 |
+
bitmap: Image.Image | None = None
|
40 |
+
|
41 |
+
def __init__(self) -> None:
|
42 |
+
self.info: dict[bytes, bytes | int] = {}
|
43 |
+
self.glyph: list[
|
44 |
+
tuple[
|
45 |
+
tuple[int, int],
|
46 |
+
tuple[int, int, int, int],
|
47 |
+
tuple[int, int, int, int],
|
48 |
+
Image.Image,
|
49 |
+
]
|
50 |
+
| None
|
51 |
+
] = [None] * 256
|
52 |
+
|
53 |
+
def __getitem__(self, ix: int) -> (
|
54 |
+
tuple[
|
55 |
+
tuple[int, int],
|
56 |
+
tuple[int, int, int, int],
|
57 |
+
tuple[int, int, int, int],
|
58 |
+
Image.Image,
|
59 |
+
]
|
60 |
+
| None
|
61 |
+
):
|
62 |
+
return self.glyph[ix]
|
63 |
+
|
64 |
+
def compile(self) -> None:
|
65 |
+
"""Create metrics and bitmap"""
|
66 |
+
|
67 |
+
if self.bitmap:
|
68 |
+
return
|
69 |
+
|
70 |
+
# create bitmap large enough to hold all data
|
71 |
+
h = w = maxwidth = 0
|
72 |
+
lines = 1
|
73 |
+
for glyph in self.glyph:
|
74 |
+
if glyph:
|
75 |
+
d, dst, src, im = glyph
|
76 |
+
h = max(h, src[3] - src[1])
|
77 |
+
w = w + (src[2] - src[0])
|
78 |
+
if w > WIDTH:
|
79 |
+
lines += 1
|
80 |
+
w = src[2] - src[0]
|
81 |
+
maxwidth = max(maxwidth, w)
|
82 |
+
|
83 |
+
xsize = maxwidth
|
84 |
+
ysize = lines * h
|
85 |
+
|
86 |
+
if xsize == 0 and ysize == 0:
|
87 |
+
return
|
88 |
+
|
89 |
+
self.ysize = h
|
90 |
+
|
91 |
+
# paste glyphs into bitmap
|
92 |
+
self.bitmap = Image.new("1", (xsize, ysize))
|
93 |
+
self.metrics: list[
|
94 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
|
95 |
+
| None
|
96 |
+
] = [None] * 256
|
97 |
+
x = y = 0
|
98 |
+
for i in range(256):
|
99 |
+
glyph = self[i]
|
100 |
+
if glyph:
|
101 |
+
d, dst, src, im = glyph
|
102 |
+
xx = src[2] - src[0]
|
103 |
+
x0, y0 = x, y
|
104 |
+
x = x + xx
|
105 |
+
if x > WIDTH:
|
106 |
+
x, y = 0, y + h
|
107 |
+
x0, y0 = x, y
|
108 |
+
x = xx
|
109 |
+
s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
|
110 |
+
self.bitmap.paste(im.crop(src), s)
|
111 |
+
self.metrics[i] = d, dst, s
|
112 |
+
|
113 |
+
def save(self, filename: str) -> None:
|
114 |
+
"""Save font"""
|
115 |
+
|
116 |
+
self.compile()
|
117 |
+
|
118 |
+
# font data
|
119 |
+
if not self.bitmap:
|
120 |
+
msg = "No bitmap created"
|
121 |
+
raise ValueError(msg)
|
122 |
+
self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
|
123 |
+
|
124 |
+
# font metrics
|
125 |
+
with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
|
126 |
+
fp.write(b"PILfont\n")
|
127 |
+
fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
|
128 |
+
fp.write(b"DATA\n")
|
129 |
+
for id in range(256):
|
130 |
+
m = self.metrics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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# THIS IS WORK IN PROGRESS
|
3 |
+
#
|
4 |
+
# The Python Imaging Library.
|
5 |
+
# $Id$
|
6 |
+
#
|
7 |
+
# FlashPix support for PIL
|
8 |
+
#
|
9 |
+
# History:
|
10 |
+
# 97-01-25 fl Created (reads uncompressed RGB images only)
|
11 |
+
#
|
12 |
+
# Copyright (c) Secret Labs AB 1997.
|
13 |
+
# Copyright (c) Fredrik Lundh 1997.
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
import olefile
|
20 |
+
|
21 |
+
from . import Image, ImageFile
|
22 |
+
from ._binary import i32le as i32
|
23 |
+
|
24 |
+
# we map from colour field tuples to (mode, rawmode) descriptors
|
25 |
+
MODES = {
|
26 |
+
# opacity
|
27 |
+
(0x00007FFE,): ("A", "L"),
|
28 |
+
# monochrome
|
29 |
+
(0x00010000,): ("L", "L"),
|
30 |
+
(0x00018000, 0x00017FFE): ("RGBA", "LA"),
|
31 |
+
# photo YCC
|
32 |
+
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
|
33 |
+
(0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
|
34 |
+
# standard RGB (NIFRGB)
|
35 |
+
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
|
36 |
+
(0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
|
37 |
+
}
|
38 |
+
|
39 |
+
|
40 |
+
#
|
41 |
+
# --------------------------------------------------------------------
|
42 |
+
|
43 |
+
|
44 |
+
def _accept(prefix: bytes) -> bool:
|
45 |
+
return prefix[:8] == olefile.MAGIC
|
46 |
+
|
47 |
+
|
48 |
+
##
|
49 |
+
# Image plugin for the FlashPix images.
|
50 |
+
|
51 |
+
|
52 |
+
class FpxImageFile(ImageFile.ImageFile):
|
53 |
+
format = "FPX"
|
54 |
+
format_description = "FlashPix"
|
55 |
+
|
56 |
+
def _open(self):
|
57 |
+
#
|
58 |
+
# read the OLE directory and see if this is a likely
|
59 |
+
# to be a FlashPix file
|
60 |
+
|
61 |
+
try:
|
62 |
+
self.ole = olefile.OleFileIO(self.fp)
|
63 |
+
except OSError as e:
|
64 |
+
msg = "not an FPX file; invalid OLE file"
|
65 |
+
raise SyntaxError(msg) from e
|
66 |
+
|
67 |
+
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
|
68 |
+
msg = "not an FPX file; bad root CLSID"
|
69 |
+
raise SyntaxError(msg)
|
70 |
+
|
71 |
+
self._open_index(1)
|
72 |
+
|
73 |
+
def _open_index(self, index: int = 1) -> None:
|
74 |
+
#
|
75 |
+
# get the Image Contents Property Set
|
76 |
+
|
77 |
+
prop = self.ole.getproperties(
|
78 |
+
[f"Data Object Store {index:06d}", "\005Image Contents"]
|
79 |
+
)
|
80 |
+
|
81 |
+
# size (highest resolution)
|
82 |
+
|
83 |
+
self._size = prop[0x1000002], prop[0x1000003]
|
84 |
+
|
85 |
+
size = max(self.size)
|
86 |
+
i = 1
|
87 |
+
while size > 64:
|
88 |
+
size = size // 2
|
89 |
+
i += 1
|
90 |
+
self.maxid = i - 1
|
91 |
+
|
92 |
+
# mode. instead of using a single field for this, flashpix
|
93 |
+
# requires you to specify the mode for each channel in each
|
94 |
+
# resolution subimage, and leaves it to the decoder to make
|
95 |
+
# sure that they all match. for now, we'll cheat and assume
|
96 |
+
# that this is always the case.
|
97 |
+
|
98 |
+
id = self.maxid << 16
|
99 |
+
|
100 |
+
s = prop[0x2000002 | id]
|
101 |
+
|
102 |
+
bands = i32(s, 4)
|
103 |
+
if bands > 4:
|
104 |
+
msg = "Invalid number of bands"
|
105 |
+
raise OSError(msg)
|
106 |
+
|
107 |
+
# note: for now, we ignore the "uncalibrated" flag
|
108 |
+
colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
|
109 |
+
|
110 |
+
self._mode, self.rawmode = MODES[colors]
|
111 |
+
|
112 |
+
# load JPEG tables, if any
|
113 |
+
self.jpeg = {}
|
114 |
+
for i in range(256):
|
115 |
+
id = 0x3000001 | (i << 16)
|
116 |
+
if id in prop:
|
117 |
+
self.jpeg[i] = prop[id]
|
118 |
+
|
119 |
+
self._open_subimage(1, self.maxid)
|
120 |
+
|
121 |
+
def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
|
122 |
+
#
|
123 |
+
# setup tile descriptors for a given subimage
|
124 |
+
|
125 |
+
stream = [
|
126 |
+
f"Data Object Store {index:06d}",
|
127 |
+
f"Resolution {subimage:04d}",
|
128 |
+
"Subimage 0000 Header",
|
129 |
+
]
|
130 |
+
|
131 |
+
fp = self.ole.openstream(stream)
|
132 |
+
|
133 |
+
# skip prefix
|
134 |
+
fp.read(28)
|
135 |
+
|
136 |
+
# header stream
|
137 |
+
s = fp.read(36)
|
138 |
+
|
139 |
+
size = i32(s, 4), i32(s, 8)
|
140 |
+
# tilecount = i32(s, 12)
|
141 |
+
tilesize = i32(s, 16), i32(s, 20)
|
142 |
+
# channels = i32(s, 24)
|
143 |
+
offset = i32(s, 28)
|
144 |
+
length = i32(s, 32)
|
145 |
+
|
146 |
+
if size != self.size:
|
147 |
+
msg = "subimage mismatch"
|
148 |
+
raise OSError(msg)
|
149 |
+
|
150 |
+
# get tile descriptors
|
151 |
+
fp.seek(28 + offset)
|
152 |
+
s = fp.read(i32(s, 12) * length)
|
153 |
+
|
154 |
+
x = y = 0
|
155 |
+
xsize, ysize = size
|
156 |
+
xtile, ytile = tilesize
|
157 |
+
self.tile = []
|
158 |
+
|
159 |
+
for i in range(0, len(s), length):
|
160 |
+
x1 = min(xsize, x + xtile)
|
161 |
+
y1 = min(ysize, y + ytile)
|
162 |
+
|
163 |
+
compression = i32(s, i + 8)
|
164 |
+
|
165 |
+
if compression == 0:
|
166 |
+
self.tile.append(
|
167 |
+
(
|
168 |
+
"raw",
|
169 |
+
(x, y, x1, y1),
|
170 |
+
i32(s, i) + 28,
|
171 |
+
(self.rawmode,),
|
172 |
+
)
|
173 |
+
)
|
174 |
+
|
175 |
+
elif compression == 1:
|
176 |
+
# FIXME: the fill decoder is not implemented
|
177 |
+
self.tile.append(
|
178 |
+
(
|
179 |
+
"fill",
|
180 |
+
(x, y, x1, y1),
|
181 |
+
i32(s, i) + 28,
|
182 |
+
(self.rawmode, s[12:16]),
|
183 |
+
)
|
184 |
+
)
|
185 |
+
|
186 |
+
elif compression == 2:
|
187 |
+
internal_color_conversion = s[14]
|
188 |
+
jpeg_tables = s[15]
|
189 |
+
rawmode = self.rawmode
|
190 |
+
|
191 |
+
if internal_color_conversion:
|
192 |
+
# The image is stored as usual (usually YCbCr).
|
193 |
+
if rawmode == "RGBA":
|
194 |
+
# For "RGBA", data is stored as YCbCrA based on
|
195 |
+
# negative RGB. The following trick works around
|
196 |
+
# this problem :
|
197 |
+
jpegmode, rawmode = "YCbCrK", "CMYK"
|
198 |
+
else:
|
199 |
+
jpegmode = None # let the decoder decide
|
200 |
+
|
201 |
+
else:
|
202 |
+
# The image is stored as defined by rawmode
|
203 |
+
jpegmode = rawmode
|
204 |
+
|
205 |
+
self.tile.append(
|
206 |
+
(
|
207 |
+
"jpeg",
|
208 |
+
(x, y, x1, y1),
|
209 |
+
i32(s, i) + 28,
|
210 |
+
(rawmode, jpegmode),
|
211 |
+
)
|
212 |
+
)
|
213 |
+
|
214 |
+
# FIXME: jpeg tables are tile dependent; the prefix
|
215 |
+
# data must be placed in the tile descriptor itself!
|
216 |
+
|
217 |
+
if jpeg_tables:
|
218 |
+
self.tile_prefix = self.jpeg[jpeg_tables]
|
219 |
+
|
220 |
+
else:
|
221 |
+
msg = "unknown/invalid compression"
|
222 |
+
raise OSError(msg)
|
223 |
+
|
224 |
+
x = x + xtile
|
225 |
+
if x >= xsize:
|
226 |
+
x, y = 0, y + ytile
|
227 |
+
if y >= ysize:
|
228 |
+
break # isn't really required
|
229 |
+
|
230 |
+
self.stream = stream
|
231 |
+
self._fp = self.fp
|
232 |
+
self.fp = None
|
233 |
+
|
234 |
+
def load(self):
|
235 |
+
if not self.fp:
|
236 |
+
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
|
237 |
+
|
238 |
+
return ImageFile.ImageFile.load(self)
|
239 |
+
|
240 |
+
def close(self) -> None:
|
241 |
+
self.ole.close()
|
242 |
+
super().close()
|
243 |
+
|
244 |
+
def __exit__(self, *args: object) -> None:
|
245 |
+
self.ole.close()
|
246 |
+
super().__exit__()
|
247 |
+
|
248 |
+
|
249 |
+
#
|
250 |
+
# --------------------------------------------------------------------
|
251 |
+
|
252 |
+
|
253 |
+
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
|
254 |
+
|
255 |
+
Image.register_extension(FpxImageFile.format, ".fpx")
|
MLPY/Lib/site-packages/PIL/FtexImagePlugin.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A Pillow loader for .ftc and .ftu files (FTEX)
|
3 |
+
Jerome Leclanche <[email protected]>
|
4 |
+
|
5 |
+
The contents of this file are hereby released in the public domain (CC0)
|
6 |
+
Full text of the CC0 license:
|
7 |
+
https://creativecommons.org/publicdomain/zero/1.0/
|
8 |
+
|
9 |
+
Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
|
10 |
+
|
11 |
+
The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
|
12 |
+
packed custom format called FTEX. This file format uses file extensions FTC
|
13 |
+
and FTU.
|
14 |
+
* FTC files are compressed textures (using standard texture compression).
|
15 |
+
* FTU files are not compressed.
|
16 |
+
Texture File Format
|
17 |
+
The FTC and FTU texture files both use the same format. This
|
18 |
+
has the following structure:
|
19 |
+
{header}
|
20 |
+
{format_directory}
|
21 |
+
{data}
|
22 |
+
Where:
|
23 |
+
{header} = {
|
24 |
+
u32:magic,
|
25 |
+
u32:version,
|
26 |
+
u32:width,
|
27 |
+
u32:height,
|
28 |
+
u32:mipmap_count,
|
29 |
+
u32:format_count
|
30 |
+
}
|
31 |
+
|
32 |
+
* The "magic" number is "FTEX".
|
33 |
+
* "width" and "height" are the dimensions of the texture.
|
34 |
+
* "mipmap_count" is the number of mipmaps in the texture.
|
35 |
+
* "format_count" is the number of texture formats (different versions of the
|
36 |
+
same texture) in this file.
|
37 |
+
|
38 |
+
{format_directory} = format_count * { u32:format, u32:where }
|
39 |
+
|
40 |
+
The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
|
41 |
+
uncompressed textures.
|
42 |
+
The texture data for a format starts at the position "where" in the file.
|
43 |
+
|
44 |
+
Each set of texture data in the file has the following structure:
|
45 |
+
{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
|
46 |
+
* "mipmap_size" is the number of bytes in that mip level. For compressed
|
47 |
+
textures this is the size of the texture data compressed with DXT1. For 24 bit
|
48 |
+
uncompressed textures, this is 3 * width * height. Following this are the image
|
49 |
+
bytes for that mipmap level.
|
50 |
+
|
51 |
+
Note: All data is stored in little-Endian (Intel) byte order.
|
52 |
+
"""
|
53 |
+
|
54 |
+
from __future__ import annotations
|
55 |
+
|
56 |
+
import struct
|
57 |
+
from enum import IntEnum
|
58 |
+
from io import BytesIO
|
59 |
+
|
60 |
+
from . import Image, ImageFile
|
61 |
+
|
62 |
+
MAGIC = b"FTEX"
|
63 |
+
|
64 |
+
|
65 |
+
class Format(IntEnum):
|
66 |
+
DXT1 = 0
|
67 |
+
UNCOMPRESSED = 1
|
68 |
+
|
69 |
+
|
70 |
+
class FtexImageFile(ImageFile.ImageFile):
|
71 |
+
format = "FTEX"
|
72 |
+
format_description = "Texture File Format (IW2:EOC)"
|
73 |
+
|
74 |
+
def _open(self) -> None:
|
75 |
+
if not _accept(self.fp.read(4)):
|
76 |
+
msg = "not an FTEX file"
|
77 |
+
raise SyntaxError(msg)
|
78 |
+
struct.unpack("<i", self.fp.read(4)) # version
|
79 |
+
self._size = struct.unpack("<2i", self.fp.read(8))
|
80 |
+
mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
|
81 |
+
|
82 |
+
self._mode = "RGB"
|
83 |
+
|
84 |
+
# Only support single-format files.
|
85 |
+
# I don't know of any multi-format file.
|
86 |
+
assert format_count == 1
|
87 |
+
|
88 |
+
format, where = struct.unpack("<2i", self.fp.read(8))
|
89 |
+
self.fp.seek(where)
|
90 |
+
(mipmap_size,) = struct.unpack("<i", self.fp.read(4))
|
91 |
+
|
92 |
+
data = self.fp.read(mipmap_size)
|
93 |
+
|
94 |
+
if format == Format.DXT1:
|
95 |
+
self._mode = "RGBA"
|
96 |
+
self.tile = [("bcn", (0, 0) + self.size, 0, 1)]
|
97 |
+
elif format == Format.UNCOMPRESSED:
|
98 |
+
self.tile = [("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))]
|
99 |
+
else:
|
100 |
+
msg = f"Invalid texture compression format: {repr(format)}"
|
101 |
+
raise ValueError(msg)
|
102 |
+
|
103 |
+
self.fp.close()
|
104 |
+
self.fp = BytesIO(data)
|
105 |
+
|
106 |
+
def load_seek(self, pos: int) -> None:
|
107 |
+
pass
|
108 |
+
|
109 |
+
|
110 |
+
def _accept(prefix: bytes) -> bool:
|
111 |
+
return prefix[:4] == MAGIC
|
112 |
+
|
113 |
+
|
114 |
+
Image.register_open(FtexImageFile.format, FtexImageFile, _accept)
|
115 |
+
Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
|
MLPY/Lib/site-packages/PIL/GbrImagePlugin.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
#
|
4 |
+
# load a GIMP brush file
|
5 |
+
#
|
6 |
+
# History:
|
7 |
+
# 96-03-14 fl Created
|
8 |
+
# 16-01-08 es Version 2
|
9 |
+
#
|
10 |
+
# Copyright (c) Secret Labs AB 1997.
|
11 |
+
# Copyright (c) Fredrik Lundh 1996.
|
12 |
+
# Copyright (c) Eric Soroos 2016.
|
13 |
+
#
|
14 |
+
# See the README file for information on usage and redistribution.
|
15 |
+
#
|
16 |
+
#
|
17 |
+
# See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for
|
18 |
+
# format documentation.
|
19 |
+
#
|
20 |
+
# This code Interprets version 1 and 2 .gbr files.
|
21 |
+
# Version 1 files are obsolete, and should not be used for new
|
22 |
+
# brushes.
|
23 |
+
# Version 2 files are saved by GIMP v2.8 (at least)
|
24 |
+
# Version 3 files have a format specifier of 18 for 16bit floats in
|
25 |
+
# the color depth field. This is currently unsupported by Pillow.
|
26 |
+
from __future__ import annotations
|
27 |
+
|
28 |
+
from . import Image, ImageFile
|
29 |
+
from ._binary import i32be as i32
|
30 |
+
|
31 |
+
|
32 |
+
def _accept(prefix: bytes) -> bool:
|
33 |
+
return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2)
|
34 |
+
|
35 |
+
|
36 |
+
##
|
37 |
+
# Image plugin for the GIMP brush format.
|
38 |
+
|
39 |
+
|
40 |
+
class GbrImageFile(ImageFile.ImageFile):
|
41 |
+
format = "GBR"
|
42 |
+
format_description = "GIMP brush file"
|
43 |
+
|
44 |
+
def _open(self) -> None:
|
45 |
+
header_size = i32(self.fp.read(4))
|
46 |
+
if header_size < 20:
|
47 |
+
msg = "not a GIMP brush"
|
48 |
+
raise SyntaxError(msg)
|
49 |
+
version = i32(self.fp.read(4))
|
50 |
+
if version not in (1, 2):
|
51 |
+
msg = f"Unsupported GIMP brush version: {version}"
|
52 |
+
raise SyntaxError(msg)
|
53 |
+
|
54 |
+
width = i32(self.fp.read(4))
|
55 |
+
height = i32(self.fp.read(4))
|
56 |
+
color_depth = i32(self.fp.read(4))
|
57 |
+
if width <= 0 or height <= 0:
|
58 |
+
msg = "not a GIMP brush"
|
59 |
+
raise SyntaxError(msg)
|
60 |
+
if color_depth not in (1, 4):
|
61 |
+
msg = f"Unsupported GIMP brush color depth: {color_depth}"
|
62 |
+
raise SyntaxError(msg)
|
63 |
+
|
64 |
+
if version == 1:
|
65 |
+
comment_length = header_size - 20
|
66 |
+
else:
|
67 |
+
comment_length = header_size - 28
|
68 |
+
magic_number = self.fp.read(4)
|
69 |
+
if magic_number != b"GIMP":
|
70 |
+
msg = "not a GIMP brush, bad magic number"
|
71 |
+
raise SyntaxError(msg)
|
72 |
+
self.info["spacing"] = i32(self.fp.read(4))
|
73 |
+
|
74 |
+
comment = self.fp.read(comment_length)[:-1]
|
75 |
+
|
76 |
+
if color_depth == 1:
|
77 |
+
self._mode = "L"
|
78 |
+
else:
|
79 |
+
self._mode = "RGBA"
|
80 |
+
|
81 |
+
self._size = width, height
|
82 |
+
|
83 |
+
self.info["comment"] = comment
|
84 |
+
|
85 |
+
# Image might not be small
|
86 |
+
Image._decompression_bomb_check(self.size)
|
87 |
+
|
88 |
+
# Data is an uncompressed block of w * h * bytes/pixel
|
89 |
+
self._data_size = width * height * color_depth
|
90 |
+
|
91 |
+
def load(self):
|
92 |
+
if not self.im:
|
93 |
+
self.im = Image.core.new(self.mode, self.size)
|
94 |
+
self.frombytes(self.fp.read(self._data_size))
|
95 |
+
return Image.Image.load(self)
|
96 |
+
|
97 |
+
|
98 |
+
#
|
99 |
+
# registry
|
100 |
+
|
101 |
+
|
102 |
+
Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
|
103 |
+
Image.register_extension(GbrImageFile.format, ".gbr")
|
MLPY/Lib/site-packages/PIL/GdImageFile.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# GD file handling
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-04-12 fl Created
|
9 |
+
#
|
10 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
11 |
+
# Copyright (c) 1996 by Fredrik Lundh.
|
12 |
+
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
|
16 |
+
|
17 |
+
"""
|
18 |
+
.. note::
|
19 |
+
This format cannot be automatically recognized, so the
|
20 |
+
class is not registered for use with :py:func:`PIL.Image.open()`. To open a
|
21 |
+
gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
|
22 |
+
|
23 |
+
.. warning::
|
24 |
+
THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
|
25 |
+
implementation is provided for convenience and demonstrational
|
26 |
+
purposes only.
|
27 |
+
"""
|
28 |
+
from __future__ import annotations
|
29 |
+
|
30 |
+
from typing import IO
|
31 |
+
|
32 |
+
from . import ImageFile, ImagePalette, UnidentifiedImageError
|
33 |
+
from ._binary import i16be as i16
|
34 |
+
from ._binary import i32be as i32
|
35 |
+
from ._typing import StrOrBytesPath
|
36 |
+
|
37 |
+
|
38 |
+
class GdImageFile(ImageFile.ImageFile):
|
39 |
+
"""
|
40 |
+
Image plugin for the GD uncompressed format. Note that this format
|
41 |
+
is not supported by the standard :py:func:`PIL.Image.open()` function. To use
|
42 |
+
this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
|
43 |
+
use the :py:func:`PIL.GdImageFile.open()` function.
|
44 |
+
"""
|
45 |
+
|
46 |
+
format = "GD"
|
47 |
+
format_description = "GD uncompressed images"
|
48 |
+
|
49 |
+
def _open(self) -> None:
|
50 |
+
# Header
|
51 |
+
assert self.fp is not None
|
52 |
+
|
53 |
+
s = self.fp.read(1037)
|
54 |
+
|
55 |
+
if i16(s) not in [65534, 65535]:
|
56 |
+
msg = "Not a valid GD 2.x .gd file"
|
57 |
+
raise SyntaxError(msg)
|
58 |
+
|
59 |
+
self._mode = "L" # FIXME: "P"
|
60 |
+
self._size = i16(s, 2), i16(s, 4)
|
61 |
+
|
62 |
+
true_color = s[6]
|
63 |
+
true_color_offset = 2 if true_color else 0
|
64 |
+
|
65 |
+
# transparency index
|
66 |
+
tindex = i32(s, 7 + true_color_offset)
|
67 |
+
if tindex < 256:
|
68 |
+
self.info["transparency"] = tindex
|
69 |
+
|
70 |
+
self.palette = ImagePalette.raw(
|
71 |
+
"XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
|
72 |
+
)
|
73 |
+
|
74 |
+
self.tile = [
|
75 |
+
(
|
76 |
+
"raw",
|
77 |
+
(0, 0) + self.size,
|
78 |
+
7 + true_color_offset + 4 + 256 * 4,
|
79 |
+
("L", 0, 1),
|
80 |
+
)
|
81 |
+
]
|
82 |
+
|
83 |
+
|
84 |
+
def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
|
85 |
+
"""
|
86 |
+
Load texture from a GD image file.
|
87 |
+
|
88 |
+
:param fp: GD file name, or an opened file handle.
|
89 |
+
:param mode: Optional mode. In this version, if the mode argument
|
90 |
+
is given, it must be "r".
|
91 |
+
:returns: An image instance.
|
92 |
+
:raises OSError: If the image could not be read.
|
93 |
+
"""
|
94 |
+
if mode != "r":
|
95 |
+
msg = "bad mode"
|
96 |
+
raise ValueError(msg)
|
97 |
+
|
98 |
+
try:
|
99 |
+
return GdImageFile(fp)
|
100 |
+
except SyntaxError as e:
|
101 |
+
msg = "cannot identify this image file"
|
102 |
+
raise UnidentifiedImageError(msg) from e
|
MLPY/Lib/site-packages/PIL/GifImagePlugin.py
ADDED
@@ -0,0 +1,1159 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# GIF file handling
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1995-09-01 fl Created
|
9 |
+
# 1996-12-14 fl Added interlace support
|
10 |
+
# 1996-12-30 fl Added animation support
|
11 |
+
# 1997-01-05 fl Added write support, fixed local colour map bug
|
12 |
+
# 1997-02-23 fl Make sure to load raster data in getdata()
|
13 |
+
# 1997-07-05 fl Support external decoder (0.4)
|
14 |
+
# 1998-07-09 fl Handle all modes when saving (0.5)
|
15 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
16 |
+
# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
|
17 |
+
# 2001-04-17 fl Added palette optimization (0.7)
|
18 |
+
# 2002-06-06 fl Added transparency support for save (0.8)
|
19 |
+
# 2004-02-24 fl Disable interlacing for small images
|
20 |
+
#
|
21 |
+
# Copyright (c) 1997-2004 by Secret Labs AB
|
22 |
+
# Copyright (c) 1995-2004 by Fredrik Lundh
|
23 |
+
#
|
24 |
+
# See the README file for information on usage and redistribution.
|
25 |
+
#
|
26 |
+
from __future__ import annotations
|
27 |
+
|
28 |
+
import itertools
|
29 |
+
import math
|
30 |
+
import os
|
31 |
+
import subprocess
|
32 |
+
import sys
|
33 |
+
from enum import IntEnum
|
34 |
+
from functools import cached_property
|
35 |
+
from typing import IO, TYPE_CHECKING, Any, List, Literal, NamedTuple, Union
|
36 |
+
|
37 |
+
from . import (
|
38 |
+
Image,
|
39 |
+
ImageChops,
|
40 |
+
ImageFile,
|
41 |
+
ImageMath,
|
42 |
+
ImageOps,
|
43 |
+
ImagePalette,
|
44 |
+
ImageSequence,
|
45 |
+
)
|
46 |
+
from ._binary import i16le as i16
|
47 |
+
from ._binary import o8
|
48 |
+
from ._binary import o16le as o16
|
49 |
+
|
50 |
+
if TYPE_CHECKING:
|
51 |
+
from . import _imaging
|
52 |
+
|
53 |
+
|
54 |
+
class LoadingStrategy(IntEnum):
|
55 |
+
""".. versionadded:: 9.1.0"""
|
56 |
+
|
57 |
+
RGB_AFTER_FIRST = 0
|
58 |
+
RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
|
59 |
+
RGB_ALWAYS = 2
|
60 |
+
|
61 |
+
|
62 |
+
#: .. versionadded:: 9.1.0
|
63 |
+
LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
|
64 |
+
|
65 |
+
# --------------------------------------------------------------------
|
66 |
+
# Identify/read GIF files
|
67 |
+
|
68 |
+
|
69 |
+
def _accept(prefix: bytes) -> bool:
|
70 |
+
return prefix[:6] in [b"GIF87a", b"GIF89a"]
|
71 |
+
|
72 |
+
|
73 |
+
##
|
74 |
+
# Image plugin for GIF images. This plugin supports both GIF87 and
|
75 |
+
# GIF89 images.
|
76 |
+
|
77 |
+
|
78 |
+
class GifImageFile(ImageFile.ImageFile):
|
79 |
+
format = "GIF"
|
80 |
+
format_description = "Compuserve GIF"
|
81 |
+
_close_exclusive_fp_after_loading = False
|
82 |
+
|
83 |
+
global_palette = None
|
84 |
+
|
85 |
+
def data(self) -> bytes | None:
|
86 |
+
s = self.fp.read(1)
|
87 |
+
if s and s[0]:
|
88 |
+
return self.fp.read(s[0])
|
89 |
+
return None
|
90 |
+
|
91 |
+
def _is_palette_needed(self, p: bytes) -> bool:
|
92 |
+
for i in range(0, len(p), 3):
|
93 |
+
if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
|
94 |
+
return True
|
95 |
+
return False
|
96 |
+
|
97 |
+
def _open(self) -> None:
|
98 |
+
# Screen
|
99 |
+
s = self.fp.read(13)
|
100 |
+
if not _accept(s):
|
101 |
+
msg = "not a GIF file"
|
102 |
+
raise SyntaxError(msg)
|
103 |
+
|
104 |
+
self.info["version"] = s[:6]
|
105 |
+
self._size = i16(s, 6), i16(s, 8)
|
106 |
+
self.tile = []
|
107 |
+
flags = s[10]
|
108 |
+
bits = (flags & 7) + 1
|
109 |
+
|
110 |
+
if flags & 128:
|
111 |
+
# get global palette
|
112 |
+
self.info["background"] = s[11]
|
113 |
+
# check if palette contains colour indices
|
114 |
+
p = self.fp.read(3 << bits)
|
115 |
+
if self._is_palette_needed(p):
|
116 |
+
p = ImagePalette.raw("RGB", p)
|
117 |
+
self.global_palette = self.palette = p
|
118 |
+
|
119 |
+
self._fp = self.fp # FIXME: hack
|
120 |
+
self.__rewind = self.fp.tell()
|
121 |
+
self._n_frames: int | None = None
|
122 |
+
self._seek(0) # get ready to read first frame
|
123 |
+
|
124 |
+
@property
|
125 |
+
def n_frames(self) -> int:
|
126 |
+
if self._n_frames is None:
|
127 |
+
current = self.tell()
|
128 |
+
try:
|
129 |
+
while True:
|
130 |
+
self._seek(self.tell() + 1, False)
|
131 |
+
except EOFError:
|
132 |
+
self._n_frames = self.tell() + 1
|
133 |
+
self.seek(current)
|
134 |
+
return self._n_frames
|
135 |
+
|
136 |
+
@cached_property
|
137 |
+
def is_animated(self) -> bool:
|
138 |
+
if self._n_frames is not None:
|
139 |
+
return self._n_frames != 1
|
140 |
+
|
141 |
+
current = self.tell()
|
142 |
+
if current:
|
143 |
+
return True
|
144 |
+
|
145 |
+
try:
|
146 |
+
self._seek(1, False)
|
147 |
+
is_animated = True
|
148 |
+
except EOFError:
|
149 |
+
is_animated = False
|
150 |
+
|
151 |
+
self.seek(current)
|
152 |
+
return is_animated
|
153 |
+
|
154 |
+
def seek(self, frame: int) -> None:
|
155 |
+
if not self._seek_check(frame):
|
156 |
+
return
|
157 |
+
if frame < self.__frame:
|
158 |
+
self.im = None
|
159 |
+
self._seek(0)
|
160 |
+
|
161 |
+
last_frame = self.__frame
|
162 |
+
for f in range(self.__frame + 1, frame + 1):
|
163 |
+
try:
|
164 |
+
self._seek(f)
|
165 |
+
except EOFError as e:
|
166 |
+
self.seek(last_frame)
|
167 |
+
msg = "no more images in GIF file"
|
168 |
+
raise EOFError(msg) from e
|
169 |
+
|
170 |
+
def _seek(self, frame: int, update_image: bool = True) -> None:
|
171 |
+
if frame == 0:
|
172 |
+
# rewind
|
173 |
+
self.__offset = 0
|
174 |
+
self.dispose: _imaging.ImagingCore | None = None
|
175 |
+
self.__frame = -1
|
176 |
+
self._fp.seek(self.__rewind)
|
177 |
+
self.disposal_method = 0
|
178 |
+
if "comment" in self.info:
|
179 |
+
del self.info["comment"]
|
180 |
+
else:
|
181 |
+
# ensure that the previous frame was loaded
|
182 |
+
if self.tile and update_image:
|
183 |
+
self.load()
|
184 |
+
|
185 |
+
if frame != self.__frame + 1:
|
186 |
+
msg = f"cannot seek to frame {frame}"
|
187 |
+
raise ValueError(msg)
|
188 |
+
|
189 |
+
self.fp = self._fp
|
190 |
+
if self.__offset:
|
191 |
+
# backup to last frame
|
192 |
+
self.fp.seek(self.__offset)
|
193 |
+
while self.data():
|
194 |
+
pass
|
195 |
+
self.__offset = 0
|
196 |
+
|
197 |
+
s = self.fp.read(1)
|
198 |
+
if not s or s == b";":
|
199 |
+
msg = "no more images in GIF file"
|
200 |
+
raise EOFError(msg)
|
201 |
+
|
202 |
+
palette: ImagePalette.ImagePalette | Literal[False] | None = None
|
203 |
+
|
204 |
+
info: dict[str, Any] = {}
|
205 |
+
frame_transparency = None
|
206 |
+
interlace = None
|
207 |
+
frame_dispose_extent = None
|
208 |
+
while True:
|
209 |
+
if not s:
|
210 |
+
s = self.fp.read(1)
|
211 |
+
if not s or s == b";":
|
212 |
+
break
|
213 |
+
|
214 |
+
elif s == b"!":
|
215 |
+
#
|
216 |
+
# extensions
|
217 |
+
#
|
218 |
+
s = self.fp.read(1)
|
219 |
+
block = self.data()
|
220 |
+
if s[0] == 249 and block is not None:
|
221 |
+
#
|
222 |
+
# graphic control extension
|
223 |
+
#
|
224 |
+
flags = block[0]
|
225 |
+
if flags & 1:
|
226 |
+
frame_transparency = block[3]
|
227 |
+
info["duration"] = i16(block, 1) * 10
|
228 |
+
|
229 |
+
# disposal method - find the value of bits 4 - 6
|
230 |
+
dispose_bits = 0b00011100 & flags
|
231 |
+
dispose_bits = dispose_bits >> 2
|
232 |
+
if dispose_bits:
|
233 |
+
# only set the dispose if it is not
|
234 |
+
# unspecified. I'm not sure if this is
|
235 |
+
# correct, but it seems to prevent the last
|
236 |
+
# frame from looking odd for some animations
|
237 |
+
self.disposal_method = dispose_bits
|
238 |
+
elif s[0] == 254:
|
239 |
+
#
|
240 |
+
# comment extension
|
241 |
+
#
|
242 |
+
comment = b""
|
243 |
+
|
244 |
+
# Read this comment block
|
245 |
+
while block:
|
246 |
+
comment += block
|
247 |
+
block = self.data()
|
248 |
+
|
249 |
+
if "comment" in info:
|
250 |
+
# If multiple comment blocks in frame, separate with \n
|
251 |
+
info["comment"] += b"\n" + comment
|
252 |
+
else:
|
253 |
+
info["comment"] = comment
|
254 |
+
s = None
|
255 |
+
continue
|
256 |
+
elif s[0] == 255 and frame == 0 and block is not None:
|
257 |
+
#
|
258 |
+
# application extension
|
259 |
+
#
|
260 |
+
info["extension"] = block, self.fp.tell()
|
261 |
+
if block[:11] == b"NETSCAPE2.0":
|
262 |
+
block = self.data()
|
263 |
+
if block and len(block) >= 3 and block[0] == 1:
|
264 |
+
self.info["loop"] = i16(block, 1)
|
265 |
+
while self.data():
|
266 |
+
pass
|
267 |
+
|
268 |
+
elif s == b",":
|
269 |
+
#
|
270 |
+
# local image
|
271 |
+
#
|
272 |
+
s = self.fp.read(9)
|
273 |
+
|
274 |
+
# extent
|
275 |
+
x0, y0 = i16(s, 0), i16(s, 2)
|
276 |
+
x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
|
277 |
+
if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
|
278 |
+
self._size = max(x1, self.size[0]), max(y1, self.size[1])
|
279 |
+
Image._decompression_bomb_check(self._size)
|
280 |
+
frame_dispose_extent = x0, y0, x1, y1
|
281 |
+
flags = s[8]
|
282 |
+
|
283 |
+
interlace = (flags & 64) != 0
|
284 |
+
|
285 |
+
if flags & 128:
|
286 |
+
bits = (flags & 7) + 1
|
287 |
+
p = self.fp.read(3 << bits)
|
288 |
+
if self._is_palette_needed(p):
|
289 |
+
palette = ImagePalette.raw("RGB", p)
|
290 |
+
else:
|
291 |
+
palette = False
|
292 |
+
|
293 |
+
# image data
|
294 |
+
bits = self.fp.read(1)[0]
|
295 |
+
self.__offset = self.fp.tell()
|
296 |
+
break
|
297 |
+
s = None
|
298 |
+
|
299 |
+
if interlace is None:
|
300 |
+
msg = "image not found in GIF frame"
|
301 |
+
raise EOFError(msg)
|
302 |
+
|
303 |
+
self.__frame = frame
|
304 |
+
if not update_image:
|
305 |
+
return
|
306 |
+
|
307 |
+
self.tile = []
|
308 |
+
|
309 |
+
if self.dispose:
|
310 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
311 |
+
|
312 |
+
self._frame_palette = palette if palette is not None else self.global_palette
|
313 |
+
self._frame_transparency = frame_transparency
|
314 |
+
if frame == 0:
|
315 |
+
if self._frame_palette:
|
316 |
+
if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
317 |
+
self._mode = "RGBA" if frame_transparency is not None else "RGB"
|
318 |
+
else:
|
319 |
+
self._mode = "P"
|
320 |
+
else:
|
321 |
+
self._mode = "L"
|
322 |
+
|
323 |
+
if not palette and self.global_palette:
|
324 |
+
from copy import copy
|
325 |
+
|
326 |
+
palette = copy(self.global_palette)
|
327 |
+
self.palette = palette
|
328 |
+
else:
|
329 |
+
if self.mode == "P":
|
330 |
+
if (
|
331 |
+
LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
|
332 |
+
or palette
|
333 |
+
):
|
334 |
+
self.pyaccess = None
|
335 |
+
if "transparency" in self.info:
|
336 |
+
self.im.putpalettealpha(self.info["transparency"], 0)
|
337 |
+
self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
|
338 |
+
self._mode = "RGBA"
|
339 |
+
del self.info["transparency"]
|
340 |
+
else:
|
341 |
+
self._mode = "RGB"
|
342 |
+
self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
|
343 |
+
|
344 |
+
def _rgb(color: int) -> tuple[int, int, int]:
|
345 |
+
if self._frame_palette:
|
346 |
+
if color * 3 + 3 > len(self._frame_palette.palette):
|
347 |
+
color = 0
|
348 |
+
return tuple(self._frame_palette.palette[color * 3 : color * 3 + 3])
|
349 |
+
else:
|
350 |
+
return (color, color, color)
|
351 |
+
|
352 |
+
self.dispose = None
|
353 |
+
self.dispose_extent = frame_dispose_extent
|
354 |
+
if self.dispose_extent and self.disposal_method >= 2:
|
355 |
+
try:
|
356 |
+
if self.disposal_method == 2:
|
357 |
+
# replace with background colour
|
358 |
+
|
359 |
+
# only dispose the extent in this frame
|
360 |
+
x0, y0, x1, y1 = self.dispose_extent
|
361 |
+
dispose_size = (x1 - x0, y1 - y0)
|
362 |
+
|
363 |
+
Image._decompression_bomb_check(dispose_size)
|
364 |
+
|
365 |
+
# by convention, attempt to use transparency first
|
366 |
+
dispose_mode = "P"
|
367 |
+
color = self.info.get("transparency", frame_transparency)
|
368 |
+
if color is not None:
|
369 |
+
if self.mode in ("RGB", "RGBA"):
|
370 |
+
dispose_mode = "RGBA"
|
371 |
+
color = _rgb(color) + (0,)
|
372 |
+
else:
|
373 |
+
color = self.info.get("background", 0)
|
374 |
+
if self.mode in ("RGB", "RGBA"):
|
375 |
+
dispose_mode = "RGB"
|
376 |
+
color = _rgb(color)
|
377 |
+
self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
|
378 |
+
else:
|
379 |
+
# replace with previous contents
|
380 |
+
if self.im is not None:
|
381 |
+
# only dispose the extent in this frame
|
382 |
+
self.dispose = self._crop(self.im, self.dispose_extent)
|
383 |
+
elif frame_transparency is not None:
|
384 |
+
x0, y0, x1, y1 = self.dispose_extent
|
385 |
+
dispose_size = (x1 - x0, y1 - y0)
|
386 |
+
|
387 |
+
Image._decompression_bomb_check(dispose_size)
|
388 |
+
dispose_mode = "P"
|
389 |
+
color = frame_transparency
|
390 |
+
if self.mode in ("RGB", "RGBA"):
|
391 |
+
dispose_mode = "RGBA"
|
392 |
+
color = _rgb(frame_transparency) + (0,)
|
393 |
+
self.dispose = Image.core.fill(
|
394 |
+
dispose_mode, dispose_size, color
|
395 |
+
)
|
396 |
+
except AttributeError:
|
397 |
+
pass
|
398 |
+
|
399 |
+
if interlace is not None:
|
400 |
+
transparency = -1
|
401 |
+
if frame_transparency is not None:
|
402 |
+
if frame == 0:
|
403 |
+
if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
|
404 |
+
self.info["transparency"] = frame_transparency
|
405 |
+
elif self.mode not in ("RGB", "RGBA"):
|
406 |
+
transparency = frame_transparency
|
407 |
+
self.tile = [
|
408 |
+
(
|
409 |
+
"gif",
|
410 |
+
(x0, y0, x1, y1),
|
411 |
+
self.__offset,
|
412 |
+
(bits, interlace, transparency),
|
413 |
+
)
|
414 |
+
]
|
415 |
+
|
416 |
+
if info.get("comment"):
|
417 |
+
self.info["comment"] = info["comment"]
|
418 |
+
for k in ["duration", "extension"]:
|
419 |
+
if k in info:
|
420 |
+
self.info[k] = info[k]
|
421 |
+
elif k in self.info:
|
422 |
+
del self.info[k]
|
423 |
+
|
424 |
+
def load_prepare(self) -> None:
|
425 |
+
temp_mode = "P" if self._frame_palette else "L"
|
426 |
+
self._prev_im = None
|
427 |
+
if self.__frame == 0:
|
428 |
+
if self._frame_transparency is not None:
|
429 |
+
self.im = Image.core.fill(
|
430 |
+
temp_mode, self.size, self._frame_transparency
|
431 |
+
)
|
432 |
+
elif self.mode in ("RGB", "RGBA"):
|
433 |
+
self._prev_im = self.im
|
434 |
+
if self._frame_palette:
|
435 |
+
self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
|
436 |
+
self.im.putpalette("RGB", *self._frame_palette.getdata())
|
437 |
+
else:
|
438 |
+
self.im = None
|
439 |
+
self._mode = temp_mode
|
440 |
+
self._frame_palette = None
|
441 |
+
|
442 |
+
super().load_prepare()
|
443 |
+
|
444 |
+
def load_end(self) -> None:
|
445 |
+
if self.__frame == 0:
|
446 |
+
if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
447 |
+
if self._frame_transparency is not None:
|
448 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
449 |
+
self._mode = "RGBA"
|
450 |
+
else:
|
451 |
+
self._mode = "RGB"
|
452 |
+
self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
|
453 |
+
return
|
454 |
+
if not self._prev_im:
|
455 |
+
return
|
456 |
+
if self._frame_transparency is not None:
|
457 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
458 |
+
frame_im = self.im.convert("RGBA")
|
459 |
+
else:
|
460 |
+
frame_im = self.im.convert("RGB")
|
461 |
+
|
462 |
+
assert self.dispose_extent is not None
|
463 |
+
frame_im = self._crop(frame_im, self.dispose_extent)
|
464 |
+
|
465 |
+
self.im = self._prev_im
|
466 |
+
self._mode = self.im.mode
|
467 |
+
if frame_im.mode == "RGBA":
|
468 |
+
self.im.paste(frame_im, self.dispose_extent, frame_im)
|
469 |
+
else:
|
470 |
+
self.im.paste(frame_im, self.dispose_extent)
|
471 |
+
|
472 |
+
def tell(self) -> int:
|
473 |
+
return self.__frame
|
474 |
+
|
475 |
+
|
476 |
+
# --------------------------------------------------------------------
|
477 |
+
# Write GIF files
|
478 |
+
|
479 |
+
|
480 |
+
RAWMODE = {"1": "L", "L": "L", "P": "P"}
|
481 |
+
|
482 |
+
|
483 |
+
def _normalize_mode(im: Image.Image) -> Image.Image:
|
484 |
+
"""
|
485 |
+
Takes an image (or frame), returns an image in a mode that is appropriate
|
486 |
+
for saving in a Gif.
|
487 |
+
|
488 |
+
It may return the original image, or it may return an image converted to
|
489 |
+
palette or 'L' mode.
|
490 |
+
|
491 |
+
:param im: Image object
|
492 |
+
:returns: Image object
|
493 |
+
"""
|
494 |
+
if im.mode in RAWMODE:
|
495 |
+
im.load()
|
496 |
+
return im
|
497 |
+
if Image.getmodebase(im.mode) == "RGB":
|
498 |
+
im = im.convert("P", palette=Image.Palette.ADAPTIVE)
|
499 |
+
if im.palette.mode == "RGBA":
|
500 |
+
for rgba in im.palette.colors:
|
501 |
+
if rgba[3] == 0:
|
502 |
+
im.info["transparency"] = im.palette.colors[rgba]
|
503 |
+
break
|
504 |
+
return im
|
505 |
+
return im.convert("L")
|
506 |
+
|
507 |
+
|
508 |
+
_Palette = Union[bytes, bytearray, List[int], ImagePalette.ImagePalette]
|
509 |
+
|
510 |
+
|
511 |
+
def _normalize_palette(
|
512 |
+
im: Image.Image, palette: _Palette | None, info: dict[str, Any]
|
513 |
+
) -> Image.Image:
|
514 |
+
"""
|
515 |
+
Normalizes the palette for image.
|
516 |
+
- Sets the palette to the incoming palette, if provided.
|
517 |
+
- Ensures that there's a palette for L mode images
|
518 |
+
- Optimizes the palette if necessary/desired.
|
519 |
+
|
520 |
+
:param im: Image object
|
521 |
+
:param palette: bytes object containing the source palette, or ....
|
522 |
+
:param info: encoderinfo
|
523 |
+
:returns: Image object
|
524 |
+
"""
|
525 |
+
source_palette = None
|
526 |
+
if palette:
|
527 |
+
# a bytes palette
|
528 |
+
if isinstance(palette, (bytes, bytearray, list)):
|
529 |
+
source_palette = bytearray(palette[:768])
|
530 |
+
if isinstance(palette, ImagePalette.ImagePalette):
|
531 |
+
source_palette = bytearray(palette.palette)
|
532 |
+
|
533 |
+
if im.mode == "P":
|
534 |
+
if not source_palette:
|
535 |
+
source_palette = im.im.getpalette("RGB")[:768]
|
536 |
+
else: # L-mode
|
537 |
+
if not source_palette:
|
538 |
+
source_palette = bytearray(i // 3 for i in range(768))
|
539 |
+
im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
|
540 |
+
|
541 |
+
used_palette_colors: list[int] | None
|
542 |
+
if palette:
|
543 |
+
used_palette_colors = []
|
544 |
+
assert source_palette is not None
|
545 |
+
for i in range(0, len(source_palette), 3):
|
546 |
+
source_color = tuple(source_palette[i : i + 3])
|
547 |
+
index = im.palette.colors.get(source_color)
|
548 |
+
if index in used_palette_colors:
|
549 |
+
index = None
|
550 |
+
used_palette_colors.append(index)
|
551 |
+
for i, index in enumerate(used_palette_colors):
|
552 |
+
if index is None:
|
553 |
+
for j in range(len(used_palette_colors)):
|
554 |
+
if j not in used_palette_colors:
|
555 |
+
used_palette_colors[i] = j
|
556 |
+
break
|
557 |
+
im = im.remap_palette(used_palette_colors)
|
558 |
+
else:
|
559 |
+
used_palette_colors = _get_optimize(im, info)
|
560 |
+
if used_palette_colors is not None:
|
561 |
+
im = im.remap_palette(used_palette_colors, source_palette)
|
562 |
+
if "transparency" in info:
|
563 |
+
try:
|
564 |
+
info["transparency"] = used_palette_colors.index(
|
565 |
+
info["transparency"]
|
566 |
+
)
|
567 |
+
except ValueError:
|
568 |
+
del info["transparency"]
|
569 |
+
return im
|
570 |
+
|
571 |
+
im.palette.palette = source_palette
|
572 |
+
return im
|
573 |
+
|
574 |
+
|
575 |
+
def _write_single_frame(
|
576 |
+
im: Image.Image,
|
577 |
+
fp: IO[bytes],
|
578 |
+
palette: _Palette | None,
|
579 |
+
) -> None:
|
580 |
+
im_out = _normalize_mode(im)
|
581 |
+
for k, v in im_out.info.items():
|
582 |
+
im.encoderinfo.setdefault(k, v)
|
583 |
+
im_out = _normalize_palette(im_out, palette, im.encoderinfo)
|
584 |
+
|
585 |
+
for s in _get_global_header(im_out, im.encoderinfo):
|
586 |
+
fp.write(s)
|
587 |
+
|
588 |
+
# local image header
|
589 |
+
flags = 0
|
590 |
+
if get_interlace(im):
|
591 |
+
flags = flags | 64
|
592 |
+
_write_local_header(fp, im, (0, 0), flags)
|
593 |
+
|
594 |
+
im_out.encoderconfig = (8, get_interlace(im))
|
595 |
+
ImageFile._save(im_out, fp, [("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])])
|
596 |
+
|
597 |
+
fp.write(b"\0") # end of image data
|
598 |
+
|
599 |
+
|
600 |
+
def _getbbox(
|
601 |
+
base_im: Image.Image, im_frame: Image.Image
|
602 |
+
) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
|
603 |
+
if _get_palette_bytes(im_frame) != _get_palette_bytes(base_im):
|
604 |
+
im_frame = im_frame.convert("RGBA")
|
605 |
+
base_im = base_im.convert("RGBA")
|
606 |
+
delta = ImageChops.subtract_modulo(im_frame, base_im)
|
607 |
+
return delta, delta.getbbox(alpha_only=False)
|
608 |
+
|
609 |
+
|
610 |
+
class _Frame(NamedTuple):
|
611 |
+
im: Image.Image
|
612 |
+
bbox: tuple[int, int, int, int] | None
|
613 |
+
encoderinfo: dict[str, Any]
|
614 |
+
|
615 |
+
|
616 |
+
def _write_multiple_frames(
|
617 |
+
im: Image.Image, fp: IO[bytes], palette: _Palette | None
|
618 |
+
) -> bool:
|
619 |
+
duration = im.encoderinfo.get("duration")
|
620 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
|
621 |
+
|
622 |
+
im_frames: list[_Frame] = []
|
623 |
+
previous_im: Image.Image | None = None
|
624 |
+
frame_count = 0
|
625 |
+
background_im = None
|
626 |
+
for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
|
627 |
+
for im_frame in ImageSequence.Iterator(imSequence):
|
628 |
+
# a copy is required here since seek can still mutate the image
|
629 |
+
im_frame = _normalize_mode(im_frame.copy())
|
630 |
+
if frame_count == 0:
|
631 |
+
for k, v in im_frame.info.items():
|
632 |
+
if k == "transparency":
|
633 |
+
continue
|
634 |
+
im.encoderinfo.setdefault(k, v)
|
635 |
+
|
636 |
+
encoderinfo = im.encoderinfo.copy()
|
637 |
+
if "transparency" in im_frame.info:
|
638 |
+
encoderinfo.setdefault("transparency", im_frame.info["transparency"])
|
639 |
+
im_frame = _normalize_palette(im_frame, palette, encoderinfo)
|
640 |
+
if isinstance(duration, (list, tuple)):
|
641 |
+
encoderinfo["duration"] = duration[frame_count]
|
642 |
+
elif duration is None and "duration" in im_frame.info:
|
643 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
644 |
+
if isinstance(disposal, (list, tuple)):
|
645 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
646 |
+
frame_count += 1
|
647 |
+
|
648 |
+
diff_frame = None
|
649 |
+
if im_frames and previous_im:
|
650 |
+
# delta frame
|
651 |
+
delta, bbox = _getbbox(previous_im, im_frame)
|
652 |
+
if not bbox:
|
653 |
+
# This frame is identical to the previous frame
|
654 |
+
if encoderinfo.get("duration"):
|
655 |
+
im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"]
|
656 |
+
continue
|
657 |
+
if im_frames[-1].encoderinfo.get("disposal") == 2:
|
658 |
+
if background_im is None:
|
659 |
+
color = im.encoderinfo.get(
|
660 |
+
"transparency", im.info.get("transparency", (0, 0, 0))
|
661 |
+
)
|
662 |
+
background = _get_background(im_frame, color)
|
663 |
+
background_im = Image.new("P", im_frame.size, background)
|
664 |
+
background_im.putpalette(im_frames[0].im.palette)
|
665 |
+
bbox = _getbbox(background_im, im_frame)[1]
|
666 |
+
elif encoderinfo.get("optimize") and im_frame.mode != "1":
|
667 |
+
if "transparency" not in encoderinfo:
|
668 |
+
try:
|
669 |
+
encoderinfo["transparency"] = (
|
670 |
+
im_frame.palette._new_color_index(im_frame)
|
671 |
+
)
|
672 |
+
except ValueError:
|
673 |
+
pass
|
674 |
+
if "transparency" in encoderinfo:
|
675 |
+
# When the delta is zero, fill the image with transparency
|
676 |
+
diff_frame = im_frame.copy()
|
677 |
+
fill = Image.new("P", delta.size, encoderinfo["transparency"])
|
678 |
+
if delta.mode == "RGBA":
|
679 |
+
r, g, b, a = delta.split()
|
680 |
+
mask = ImageMath.lambda_eval(
|
681 |
+
lambda args: args["convert"](
|
682 |
+
args["max"](
|
683 |
+
args["max"](
|
684 |
+
args["max"](args["r"], args["g"]), args["b"]
|
685 |
+
),
|
686 |
+
args["a"],
|
687 |
+
)
|
688 |
+
* 255,
|
689 |
+
"1",
|
690 |
+
),
|
691 |
+
r=r,
|
692 |
+
g=g,
|
693 |
+
b=b,
|
694 |
+
a=a,
|
695 |
+
)
|
696 |
+
else:
|
697 |
+
if delta.mode == "P":
|
698 |
+
# Convert to L without considering palette
|
699 |
+
delta_l = Image.new("L", delta.size)
|
700 |
+
delta_l.putdata(delta.getdata())
|
701 |
+
delta = delta_l
|
702 |
+
mask = ImageMath.lambda_eval(
|
703 |
+
lambda args: args["convert"](args["im"] * 255, "1"),
|
704 |
+
im=delta,
|
705 |
+
)
|
706 |
+
diff_frame.paste(fill, mask=ImageOps.invert(mask))
|
707 |
+
else:
|
708 |
+
bbox = None
|
709 |
+
previous_im = im_frame
|
710 |
+
im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
|
711 |
+
|
712 |
+
if len(im_frames) == 1:
|
713 |
+
if "duration" in im.encoderinfo:
|
714 |
+
# Since multiple frames will not be written, use the combined duration
|
715 |
+
im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
|
716 |
+
return False
|
717 |
+
|
718 |
+
for frame_data in im_frames:
|
719 |
+
im_frame = frame_data.im
|
720 |
+
if not frame_data.bbox:
|
721 |
+
# global header
|
722 |
+
for s in _get_global_header(im_frame, frame_data.encoderinfo):
|
723 |
+
fp.write(s)
|
724 |
+
offset = (0, 0)
|
725 |
+
else:
|
726 |
+
# compress difference
|
727 |
+
if not palette:
|
728 |
+
frame_data.encoderinfo["include_color_table"] = True
|
729 |
+
|
730 |
+
im_frame = im_frame.crop(frame_data.bbox)
|
731 |
+
offset = frame_data.bbox[:2]
|
732 |
+
_write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
|
733 |
+
return True
|
734 |
+
|
735 |
+
|
736 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
737 |
+
_save(im, fp, filename, save_all=True)
|
738 |
+
|
739 |
+
|
740 |
+
def _save(
|
741 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
|
742 |
+
) -> None:
|
743 |
+
# header
|
744 |
+
if "palette" in im.encoderinfo or "palette" in im.info:
|
745 |
+
palette = im.encoderinfo.get("palette", im.info.get("palette"))
|
746 |
+
else:
|
747 |
+
palette = None
|
748 |
+
im.encoderinfo.setdefault("optimize", True)
|
749 |
+
|
750 |
+
if not save_all or not _write_multiple_frames(im, fp, palette):
|
751 |
+
_write_single_frame(im, fp, palette)
|
752 |
+
|
753 |
+
fp.write(b";") # end of file
|
754 |
+
|
755 |
+
if hasattr(fp, "flush"):
|
756 |
+
fp.flush()
|
757 |
+
|
758 |
+
|
759 |
+
def get_interlace(im: Image.Image) -> int:
|
760 |
+
interlace = im.encoderinfo.get("interlace", 1)
|
761 |
+
|
762 |
+
# workaround for @PIL153
|
763 |
+
if min(im.size) < 16:
|
764 |
+
interlace = 0
|
765 |
+
|
766 |
+
return interlace
|
767 |
+
|
768 |
+
|
769 |
+
def _write_local_header(
|
770 |
+
fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
|
771 |
+
) -> None:
|
772 |
+
try:
|
773 |
+
transparency = im.encoderinfo["transparency"]
|
774 |
+
except KeyError:
|
775 |
+
transparency = None
|
776 |
+
|
777 |
+
if "duration" in im.encoderinfo:
|
778 |
+
duration = int(im.encoderinfo["duration"] / 10)
|
779 |
+
else:
|
780 |
+
duration = 0
|
781 |
+
|
782 |
+
disposal = int(im.encoderinfo.get("disposal", 0))
|
783 |
+
|
784 |
+
if transparency is not None or duration != 0 or disposal:
|
785 |
+
packed_flag = 1 if transparency is not None else 0
|
786 |
+
packed_flag |= disposal << 2
|
787 |
+
|
788 |
+
fp.write(
|
789 |
+
b"!"
|
790 |
+
+ o8(249) # extension intro
|
791 |
+
+ o8(4) # length
|
792 |
+
+ o8(packed_flag) # packed fields
|
793 |
+
+ o16(duration) # duration
|
794 |
+
+ o8(transparency or 0) # transparency index
|
795 |
+
+ o8(0)
|
796 |
+
)
|
797 |
+
|
798 |
+
include_color_table = im.encoderinfo.get("include_color_table")
|
799 |
+
if include_color_table:
|
800 |
+
palette_bytes = _get_palette_bytes(im)
|
801 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
802 |
+
if color_table_size:
|
803 |
+
flags = flags | 128 # local color table flag
|
804 |
+
flags = flags | color_table_size
|
805 |
+
|
806 |
+
fp.write(
|
807 |
+
b","
|
808 |
+
+ o16(offset[0]) # offset
|
809 |
+
+ o16(offset[1])
|
810 |
+
+ o16(im.size[0]) # size
|
811 |
+
+ o16(im.size[1])
|
812 |
+
+ o8(flags) # flags
|
813 |
+
)
|
814 |
+
if include_color_table and color_table_size:
|
815 |
+
fp.write(_get_header_palette(palette_bytes))
|
816 |
+
fp.write(o8(8)) # bits
|
817 |
+
|
818 |
+
|
819 |
+
def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
820 |
+
# Unused by default.
|
821 |
+
# To use, uncomment the register_save call at the end of the file.
|
822 |
+
#
|
823 |
+
# If you need real GIF compression and/or RGB quantization, you
|
824 |
+
# can use the external NETPBM/PBMPLUS utilities. See comments
|
825 |
+
# below for information on how to enable this.
|
826 |
+
tempfile = im._dump()
|
827 |
+
|
828 |
+
try:
|
829 |
+
with open(filename, "wb") as f:
|
830 |
+
if im.mode != "RGB":
|
831 |
+
subprocess.check_call(
|
832 |
+
["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
|
833 |
+
)
|
834 |
+
else:
|
835 |
+
# Pipe ppmquant output into ppmtogif
|
836 |
+
# "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
|
837 |
+
quant_cmd = ["ppmquant", "256", tempfile]
|
838 |
+
togif_cmd = ["ppmtogif"]
|
839 |
+
quant_proc = subprocess.Popen(
|
840 |
+
quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
841 |
+
)
|
842 |
+
togif_proc = subprocess.Popen(
|
843 |
+
togif_cmd,
|
844 |
+
stdin=quant_proc.stdout,
|
845 |
+
stdout=f,
|
846 |
+
stderr=subprocess.DEVNULL,
|
847 |
+
)
|
848 |
+
|
849 |
+
# Allow ppmquant to receive SIGPIPE if ppmtogif exits
|
850 |
+
assert quant_proc.stdout is not None
|
851 |
+
quant_proc.stdout.close()
|
852 |
+
|
853 |
+
retcode = quant_proc.wait()
|
854 |
+
if retcode:
|
855 |
+
raise subprocess.CalledProcessError(retcode, quant_cmd)
|
856 |
+
|
857 |
+
retcode = togif_proc.wait()
|
858 |
+
if retcode:
|
859 |
+
raise subprocess.CalledProcessError(retcode, togif_cmd)
|
860 |
+
finally:
|
861 |
+
try:
|
862 |
+
os.unlink(tempfile)
|
863 |
+
except OSError:
|
864 |
+
pass
|
865 |
+
|
866 |
+
|
867 |
+
# Force optimization so that we can test performance against
|
868 |
+
# cases where it took lots of memory and time previously.
|
869 |
+
_FORCE_OPTIMIZE = False
|
870 |
+
|
871 |
+
|
872 |
+
def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
|
873 |
+
"""
|
874 |
+
Palette optimization is a potentially expensive operation.
|
875 |
+
|
876 |
+
This function determines if the palette should be optimized using
|
877 |
+
some heuristics, then returns the list of palette entries in use.
|
878 |
+
|
879 |
+
:param im: Image object
|
880 |
+
:param info: encoderinfo
|
881 |
+
:returns: list of indexes of palette entries in use, or None
|
882 |
+
"""
|
883 |
+
if im.mode in ("P", "L") and info and info.get("optimize"):
|
884 |
+
# Potentially expensive operation.
|
885 |
+
|
886 |
+
# The palette saves 3 bytes per color not used, but palette
|
887 |
+
# lengths are restricted to 3*(2**N) bytes. Max saving would
|
888 |
+
# be 768 -> 6 bytes if we went all the way down to 2 colors.
|
889 |
+
# * If we're over 128 colors, we can't save any space.
|
890 |
+
# * If there aren't any holes, it's not worth collapsing.
|
891 |
+
# * If we have a 'large' image, the palette is in the noise.
|
892 |
+
|
893 |
+
# create the new palette if not every color is used
|
894 |
+
optimise = _FORCE_OPTIMIZE or im.mode == "L"
|
895 |
+
if optimise or im.width * im.height < 512 * 512:
|
896 |
+
# check which colors are used
|
897 |
+
used_palette_colors = []
|
898 |
+
for i, count in enumerate(im.histogram()):
|
899 |
+
if count:
|
900 |
+
used_palette_colors.append(i)
|
901 |
+
|
902 |
+
if optimise or max(used_palette_colors) >= len(used_palette_colors):
|
903 |
+
return used_palette_colors
|
904 |
+
|
905 |
+
num_palette_colors = len(im.palette.palette) // Image.getmodebands(
|
906 |
+
im.palette.mode
|
907 |
+
)
|
908 |
+
current_palette_size = 1 << (num_palette_colors - 1).bit_length()
|
909 |
+
if (
|
910 |
+
# check that the palette would become smaller when saved
|
911 |
+
len(used_palette_colors) <= current_palette_size // 2
|
912 |
+
# check that the palette is not already the smallest possible size
|
913 |
+
and current_palette_size > 2
|
914 |
+
):
|
915 |
+
return used_palette_colors
|
916 |
+
return None
|
917 |
+
|
918 |
+
|
919 |
+
def _get_color_table_size(palette_bytes: bytes) -> int:
|
920 |
+
# calculate the palette size for the header
|
921 |
+
if not palette_bytes:
|
922 |
+
return 0
|
923 |
+
elif len(palette_bytes) < 9:
|
924 |
+
return 1
|
925 |
+
else:
|
926 |
+
return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
|
927 |
+
|
928 |
+
|
929 |
+
def _get_header_palette(palette_bytes: bytes) -> bytes:
|
930 |
+
"""
|
931 |
+
Returns the palette, null padded to the next power of 2 (*3) bytes
|
932 |
+
suitable for direct inclusion in the GIF header
|
933 |
+
|
934 |
+
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
|
935 |
+
:returns: Null padded palette
|
936 |
+
"""
|
937 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
938 |
+
|
939 |
+
# add the missing amount of bytes
|
940 |
+
# the palette has to be 2<<n in size
|
941 |
+
actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
|
942 |
+
if actual_target_size_diff > 0:
|
943 |
+
palette_bytes += o8(0) * 3 * actual_target_size_diff
|
944 |
+
return palette_bytes
|
945 |
+
|
946 |
+
|
947 |
+
def _get_palette_bytes(im: Image.Image) -> bytes:
|
948 |
+
"""
|
949 |
+
Gets the palette for inclusion in the gif header
|
950 |
+
|
951 |
+
:param im: Image object
|
952 |
+
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
953 |
+
"""
|
954 |
+
return im.palette.palette if im.palette else b""
|
955 |
+
|
956 |
+
|
957 |
+
def _get_background(
|
958 |
+
im: Image.Image,
|
959 |
+
info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
|
960 |
+
) -> int:
|
961 |
+
background = 0
|
962 |
+
if info_background:
|
963 |
+
if isinstance(info_background, tuple):
|
964 |
+
# WebPImagePlugin stores an RGBA value in info["background"]
|
965 |
+
# So it must be converted to the same format as GifImagePlugin's
|
966 |
+
# info["background"] - a global color table index
|
967 |
+
try:
|
968 |
+
background = im.palette.getcolor(info_background, im)
|
969 |
+
except ValueError as e:
|
970 |
+
if str(e) not in (
|
971 |
+
# If all 256 colors are in use,
|
972 |
+
# then there is no need for the background color
|
973 |
+
"cannot allocate more than 256 colors",
|
974 |
+
# Ignore non-opaque WebP background
|
975 |
+
"cannot add non-opaque RGBA color to RGB palette",
|
976 |
+
):
|
977 |
+
raise
|
978 |
+
else:
|
979 |
+
background = info_background
|
980 |
+
return background
|
981 |
+
|
982 |
+
|
983 |
+
def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
|
984 |
+
"""Return a list of strings representing a GIF header"""
|
985 |
+
|
986 |
+
# Header Block
|
987 |
+
# https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
|
988 |
+
|
989 |
+
version = b"87a"
|
990 |
+
if im.info.get("version") == b"89a" or (
|
991 |
+
info
|
992 |
+
and (
|
993 |
+
"transparency" in info
|
994 |
+
or info.get("loop") is not None
|
995 |
+
or info.get("duration")
|
996 |
+
or info.get("comment")
|
997 |
+
)
|
998 |
+
):
|
999 |
+
version = b"89a"
|
1000 |
+
|
1001 |
+
background = _get_background(im, info.get("background"))
|
1002 |
+
|
1003 |
+
palette_bytes = _get_palette_bytes(im)
|
1004 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
1005 |
+
|
1006 |
+
header = [
|
1007 |
+
b"GIF" # signature
|
1008 |
+
+ version # version
|
1009 |
+
+ o16(im.size[0]) # canvas width
|
1010 |
+
+ o16(im.size[1]), # canvas height
|
1011 |
+
# Logical Screen Descriptor
|
1012 |
+
# size of global color table + global color table flag
|
1013 |
+
o8(color_table_size + 128), # packed fields
|
1014 |
+
# background + reserved/aspect
|
1015 |
+
o8(background) + o8(0),
|
1016 |
+
# Global Color Table
|
1017 |
+
_get_header_palette(palette_bytes),
|
1018 |
+
]
|
1019 |
+
if info.get("loop") is not None:
|
1020 |
+
header.append(
|
1021 |
+
b"!"
|
1022 |
+
+ o8(255) # extension intro
|
1023 |
+
+ o8(11)
|
1024 |
+
+ b"NETSCAPE2.0"
|
1025 |
+
+ o8(3)
|
1026 |
+
+ o8(1)
|
1027 |
+
+ o16(info["loop"]) # number of loops
|
1028 |
+
+ o8(0)
|
1029 |
+
)
|
1030 |
+
if info.get("comment"):
|
1031 |
+
comment_block = b"!" + o8(254) # extension intro
|
1032 |
+
|
1033 |
+
comment = info["comment"]
|
1034 |
+
if isinstance(comment, str):
|
1035 |
+
comment = comment.encode()
|
1036 |
+
for i in range(0, len(comment), 255):
|
1037 |
+
subblock = comment[i : i + 255]
|
1038 |
+
comment_block += o8(len(subblock)) + subblock
|
1039 |
+
|
1040 |
+
comment_block += o8(0)
|
1041 |
+
header.append(comment_block)
|
1042 |
+
return header
|
1043 |
+
|
1044 |
+
|
1045 |
+
def _write_frame_data(
|
1046 |
+
fp: IO[bytes],
|
1047 |
+
im_frame: Image.Image,
|
1048 |
+
offset: tuple[int, int],
|
1049 |
+
params: dict[str, Any],
|
1050 |
+
) -> None:
|
1051 |
+
try:
|
1052 |
+
im_frame.encoderinfo = params
|
1053 |
+
|
1054 |
+
# local image header
|
1055 |
+
_write_local_header(fp, im_frame, offset, 0)
|
1056 |
+
|
1057 |
+
ImageFile._save(
|
1058 |
+
im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])]
|
1059 |
+
)
|
1060 |
+
|
1061 |
+
fp.write(b"\0") # end of image data
|
1062 |
+
finally:
|
1063 |
+
del im_frame.encoderinfo
|
1064 |
+
|
1065 |
+
|
1066 |
+
# --------------------------------------------------------------------
|
1067 |
+
# Legacy GIF utilities
|
1068 |
+
|
1069 |
+
|
1070 |
+
def getheader(
|
1071 |
+
im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
|
1072 |
+
) -> tuple[list[bytes], list[int] | None]:
|
1073 |
+
"""
|
1074 |
+
Legacy Method to get Gif data from image.
|
1075 |
+
|
1076 |
+
Warning:: May modify image data.
|
1077 |
+
|
1078 |
+
:param im: Image object
|
1079 |
+
:param palette: bytes object containing the source palette, or ....
|
1080 |
+
:param info: encoderinfo
|
1081 |
+
:returns: tuple of(list of header items, optimized palette)
|
1082 |
+
|
1083 |
+
"""
|
1084 |
+
if info is None:
|
1085 |
+
info = {}
|
1086 |
+
|
1087 |
+
used_palette_colors = _get_optimize(im, info)
|
1088 |
+
|
1089 |
+
if "background" not in info and "background" in im.info:
|
1090 |
+
info["background"] = im.info["background"]
|
1091 |
+
|
1092 |
+
im_mod = _normalize_palette(im, palette, info)
|
1093 |
+
im.palette = im_mod.palette
|
1094 |
+
im.im = im_mod.im
|
1095 |
+
header = _get_global_header(im, info)
|
1096 |
+
|
1097 |
+
return header, used_palette_colors
|
1098 |
+
|
1099 |
+
|
1100 |
+
def getdata(
|
1101 |
+
im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
|
1102 |
+
) -> list[bytes]:
|
1103 |
+
"""
|
1104 |
+
Legacy Method
|
1105 |
+
|
1106 |
+
Return a list of strings representing this image.
|
1107 |
+
The first string is a local image header, the rest contains
|
1108 |
+
encoded image data.
|
1109 |
+
|
1110 |
+
To specify duration, add the time in milliseconds,
|
1111 |
+
e.g. ``getdata(im_frame, duration=1000)``
|
1112 |
+
|
1113 |
+
:param im: Image object
|
1114 |
+
:param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
|
1115 |
+
:param \\**params: e.g. duration or other encoder info parameters
|
1116 |
+
:returns: List of bytes containing GIF encoded frame data
|
1117 |
+
|
1118 |
+
"""
|
1119 |
+
from io import BytesIO
|
1120 |
+
|
1121 |
+
class Collector(BytesIO):
|
1122 |
+
data = []
|
1123 |
+
|
1124 |
+
if sys.version_info >= (3, 12):
|
1125 |
+
from collections.abc import Buffer
|
1126 |
+
|
1127 |
+
def write(self, data: Buffer) -> int:
|
1128 |
+
self.data.append(data)
|
1129 |
+
return len(data)
|
1130 |
+
|
1131 |
+
else:
|
1132 |
+
|
1133 |
+
def write(self, data: Any) -> int:
|
1134 |
+
self.data.append(data)
|
1135 |
+
return len(data)
|
1136 |
+
|
1137 |
+
im.load() # make sure raster data is available
|
1138 |
+
|
1139 |
+
fp = Collector()
|
1140 |
+
|
1141 |
+
_write_frame_data(fp, im, offset, params)
|
1142 |
+
|
1143 |
+
return fp.data
|
1144 |
+
|
1145 |
+
|
1146 |
+
# --------------------------------------------------------------------
|
1147 |
+
# Registry
|
1148 |
+
|
1149 |
+
Image.register_open(GifImageFile.format, GifImageFile, _accept)
|
1150 |
+
Image.register_save(GifImageFile.format, _save)
|
1151 |
+
Image.register_save_all(GifImageFile.format, _save_all)
|
1152 |
+
Image.register_extension(GifImageFile.format, ".gif")
|
1153 |
+
Image.register_mime(GifImageFile.format, "image/gif")
|
1154 |
+
|
1155 |
+
#
|
1156 |
+
# Uncomment the following line if you wish to use NETPBM/PBMPLUS
|
1157 |
+
# instead of the built-in "uncompressed" GIF encoder
|
1158 |
+
|
1159 |
+
# Image.register_save(GifImageFile.format, _save_netpbm)
|
MLPY/Lib/site-packages/PIL/GimpGradientFile.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# stuff to read (and render) GIMP gradient files
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 97-08-23 fl Created
|
9 |
+
#
|
10 |
+
# Copyright (c) Secret Labs AB 1997.
|
11 |
+
# Copyright (c) Fredrik Lundh 1997.
|
12 |
+
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
|
16 |
+
"""
|
17 |
+
Stuff to translate curve segments to palette values (derived from
|
18 |
+
the corresponding code in GIMP, written by Federico Mena Quintero.
|
19 |
+
See the GIMP distribution for more information.)
|
20 |
+
"""
|
21 |
+
from __future__ import annotations
|
22 |
+
|
23 |
+
from math import log, pi, sin, sqrt
|
24 |
+
from typing import IO, Callable
|
25 |
+
|
26 |
+
from ._binary import o8
|
27 |
+
|
28 |
+
EPSILON = 1e-10
|
29 |
+
"""""" # Enable auto-doc for data member
|
30 |
+
|
31 |
+
|
32 |
+
def linear(middle: float, pos: float) -> float:
|
33 |
+
if pos <= middle:
|
34 |
+
if middle < EPSILON:
|
35 |
+
return 0.0
|
36 |
+
else:
|
37 |
+
return 0.5 * pos / middle
|
38 |
+
else:
|
39 |
+
pos = pos - middle
|
40 |
+
middle = 1.0 - middle
|
41 |
+
if middle < EPSILON:
|
42 |
+
return 1.0
|
43 |
+
else:
|
44 |
+
return 0.5 + 0.5 * pos / middle
|
45 |
+
|
46 |
+
|
47 |
+
def curved(middle: float, pos: float) -> float:
|
48 |
+
return pos ** (log(0.5) / log(max(middle, EPSILON)))
|
49 |
+
|
50 |
+
|
51 |
+
def sine(middle: float, pos: float) -> float:
|
52 |
+
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
|
53 |
+
|
54 |
+
|
55 |
+
def sphere_increasing(middle: float, pos: float) -> float:
|
56 |
+
return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
|
57 |
+
|
58 |
+
|
59 |
+
def sphere_decreasing(middle: float, pos: float) -> float:
|
60 |
+
return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
|
61 |
+
|
62 |
+
|
63 |
+
SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
|
64 |
+
"""""" # Enable auto-doc for data member
|
65 |
+
|
66 |
+
|
67 |
+
class GradientFile:
|
68 |
+
gradient: (
|
69 |
+
list[
|
70 |
+
tuple[
|
71 |
+
float,
|
72 |
+
float,
|
73 |
+
float,
|
74 |
+
list[float],
|
75 |
+
list[float],
|
76 |
+
Callable[[float, float], float],
|
77 |
+
]
|
78 |
+
]
|
79 |
+
| None
|
80 |
+
) = None
|
81 |
+
|
82 |
+
def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
|
83 |
+
assert self.gradient is not None
|
84 |
+
palette = []
|
85 |
+
|
86 |
+
ix = 0
|
87 |
+
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
88 |
+
|
89 |
+
for i in range(entries):
|
90 |
+
x = i / (entries - 1)
|
91 |
+
|
92 |
+
while x1 < x:
|
93 |
+
ix += 1
|
94 |
+
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
95 |
+
|
96 |
+
w = x1 - x0
|
97 |
+
|
98 |
+
if w < EPSILON:
|
99 |
+
scale = segment(0.5, 0.5)
|
100 |
+
else:
|
101 |
+
scale = segment((xm - x0) / w, (x - x0) / w)
|
102 |
+
|
103 |
+
# expand to RGBA
|
104 |
+
r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
|
105 |
+
g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
|
106 |
+
b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
|
107 |
+
a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
|
108 |
+
|
109 |
+
# add to palette
|
110 |
+
palette.append(r + g + b + a)
|
111 |
+
|
112 |
+
return b"".join(palette), "RGBA"
|
113 |
+
|
114 |
+
|
115 |
+
class GimpGradientFile(GradientFile):
|
116 |
+
"""File handler for GIMP's gradient format."""
|
117 |
+
|
118 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
119 |
+
if fp.readline()[:13] != b"GIMP Gradient":
|
120 |
+
msg = "not a GIMP gradient file"
|
121 |
+
raise SyntaxError(msg)
|
122 |
+
|
123 |
+
line = fp.readline()
|
124 |
+
|
125 |
+
# GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
|
126 |
+
if line.startswith(b"Name: "):
|
127 |
+
line = fp.readline().strip()
|
128 |
+
|
129 |
+
count = int(line)
|
130 |
+
|
131 |
+
self.gradient = []
|
132 |
+
|
133 |
+
for i in range(count):
|
134 |
+
s = fp.readline().split()
|
135 |
+
w = [float(x) for x in s[:11]]
|
136 |
+
|
137 |
+
x0, x1 = w[0], w[2]
|
138 |
+
xm = w[1]
|
139 |
+
rgb0 = w[3:7]
|
140 |
+
rgb1 = w[7:11]
|
141 |
+
|
142 |
+
segment = SEGMENTS[int(s[11])]
|
143 |
+
cspace = int(s[12])
|
144 |
+
|
145 |
+
if cspace != 0:
|
146 |
+
msg = "cannot handle HSV colour space"
|
147 |
+
raise OSError(msg)
|
148 |
+
|
149 |
+
self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
|
MLPY/Lib/site-packages/PIL/GimpPaletteFile.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# stuff to read GIMP palette files
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1997-08-23 fl Created
|
9 |
+
# 2004-09-07 fl Support GIMP 2.0 palette files.
|
10 |
+
#
|
11 |
+
# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
|
12 |
+
# Copyright (c) Fredrik Lundh 1997-2004.
|
13 |
+
#
|
14 |
+
# See the README file for information on usage and redistribution.
|
15 |
+
#
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
import re
|
19 |
+
from typing import IO
|
20 |
+
|
21 |
+
from ._binary import o8
|
22 |
+
|
23 |
+
|
24 |
+
class GimpPaletteFile:
|
25 |
+
"""File handler for GIMP's palette format."""
|
26 |
+
|
27 |
+
rawmode = "RGB"
|
28 |
+
|
29 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
30 |
+
palette = [o8(i) * 3 for i in range(256)]
|
31 |
+
|
32 |
+
if fp.readline()[:12] != b"GIMP Palette":
|
33 |
+
msg = "not a GIMP palette file"
|
34 |
+
raise SyntaxError(msg)
|
35 |
+
|
36 |
+
for i in range(256):
|
37 |
+
s = fp.readline()
|
38 |
+
if not s:
|
39 |
+
break
|
40 |
+
|
41 |
+
# skip fields and comment lines
|
42 |
+
if re.match(rb"\w+:|#", s):
|
43 |
+
continue
|
44 |
+
if len(s) > 100:
|
45 |
+
msg = "bad palette file"
|
46 |
+
raise SyntaxError(msg)
|
47 |
+
|
48 |
+
v = tuple(map(int, s.split()[:3]))
|
49 |
+
if len(v) != 3:
|
50 |
+
msg = "bad palette entry"
|
51 |
+
raise ValueError(msg)
|
52 |
+
|
53 |
+
palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
|
54 |
+
|
55 |
+
self.palette = b"".join(palette)
|
56 |
+
|
57 |
+
def getpalette(self) -> tuple[bytes, str]:
|
58 |
+
return self.palette, self.rawmode
|
MLPY/Lib/site-packages/PIL/GribStubImagePlugin.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# GRIB stub adapter
|
6 |
+
#
|
7 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
8 |
+
#
|
9 |
+
# See the README file for information on usage and redistribution.
|
10 |
+
#
|
11 |
+
from __future__ import annotations
|
12 |
+
|
13 |
+
from typing import IO
|
14 |
+
|
15 |
+
from . import Image, ImageFile
|
16 |
+
|
17 |
+
_handler = None
|
18 |
+
|
19 |
+
|
20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
21 |
+
"""
|
22 |
+
Install application-specific GRIB image handler.
|
23 |
+
|
24 |
+
:param handler: Handler object.
|
25 |
+
"""
|
26 |
+
global _handler
|
27 |
+
_handler = handler
|
28 |
+
|
29 |
+
|
30 |
+
# --------------------------------------------------------------------
|
31 |
+
# Image adapter
|
32 |
+
|
33 |
+
|
34 |
+
def _accept(prefix: bytes) -> bool:
|
35 |
+
return prefix[:4] == b"GRIB" and prefix[7] == 1
|
36 |
+
|
37 |
+
|
38 |
+
class GribStubImageFile(ImageFile.StubImageFile):
|
39 |
+
format = "GRIB"
|
40 |
+
format_description = "GRIB"
|
41 |
+
|
42 |
+
def _open(self) -> None:
|
43 |
+
offset = self.fp.tell()
|
44 |
+
|
45 |
+
if not _accept(self.fp.read(8)):
|
46 |
+
msg = "Not a GRIB file"
|
47 |
+
raise SyntaxError(msg)
|
48 |
+
|
49 |
+
self.fp.seek(offset)
|
50 |
+
|
51 |
+
# make something up
|
52 |
+
self._mode = "F"
|
53 |
+
self._size = 1, 1
|
54 |
+
|
55 |
+
loader = self._load()
|
56 |
+
if loader:
|
57 |
+
loader.open(self)
|
58 |
+
|
59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
60 |
+
return _handler
|
61 |
+
|
62 |
+
|
63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
65 |
+
msg = "GRIB save handler not installed"
|
66 |
+
raise OSError(msg)
|
67 |
+
_handler.save(im, fp, filename)
|
68 |
+
|
69 |
+
|
70 |
+
# --------------------------------------------------------------------
|
71 |
+
# Registry
|
72 |
+
|
73 |
+
Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
|
74 |
+
Image.register_save(GribStubImageFile.format, _save)
|
75 |
+
|
76 |
+
Image.register_extension(GribStubImageFile.format, ".grib")
|
MLPY/Lib/site-packages/PIL/Hdf5StubImagePlugin.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# HDF5 stub adapter
|
6 |
+
#
|
7 |
+
# Copyright (c) 2000-2003 by Fredrik Lundh
|
8 |
+
#
|
9 |
+
# See the README file for information on usage and redistribution.
|
10 |
+
#
|
11 |
+
from __future__ import annotations
|
12 |
+
|
13 |
+
from typing import IO
|
14 |
+
|
15 |
+
from . import Image, ImageFile
|
16 |
+
|
17 |
+
_handler = None
|
18 |
+
|
19 |
+
|
20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
21 |
+
"""
|
22 |
+
Install application-specific HDF5 image handler.
|
23 |
+
|
24 |
+
:param handler: Handler object.
|
25 |
+
"""
|
26 |
+
global _handler
|
27 |
+
_handler = handler
|
28 |
+
|
29 |
+
|
30 |
+
# --------------------------------------------------------------------
|
31 |
+
# Image adapter
|
32 |
+
|
33 |
+
|
34 |
+
def _accept(prefix: bytes) -> bool:
|
35 |
+
return prefix[:8] == b"\x89HDF\r\n\x1a\n"
|
36 |
+
|
37 |
+
|
38 |
+
class HDF5StubImageFile(ImageFile.StubImageFile):
|
39 |
+
format = "HDF5"
|
40 |
+
format_description = "HDF5"
|
41 |
+
|
42 |
+
def _open(self) -> None:
|
43 |
+
offset = self.fp.tell()
|
44 |
+
|
45 |
+
if not _accept(self.fp.read(8)):
|
46 |
+
msg = "Not an HDF file"
|
47 |
+
raise SyntaxError(msg)
|
48 |
+
|
49 |
+
self.fp.seek(offset)
|
50 |
+
|
51 |
+
# make something up
|
52 |
+
self._mode = "F"
|
53 |
+
self._size = 1, 1
|
54 |
+
|
55 |
+
loader = self._load()
|
56 |
+
if loader:
|
57 |
+
loader.open(self)
|
58 |
+
|
59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
60 |
+
return _handler
|
61 |
+
|
62 |
+
|
63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
65 |
+
msg = "HDF5 save handler not installed"
|
66 |
+
raise OSError(msg)
|
67 |
+
_handler.save(im, fp, filename)
|
68 |
+
|
69 |
+
|
70 |
+
# --------------------------------------------------------------------
|
71 |
+
# Registry
|
72 |
+
|
73 |
+
Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
|
74 |
+
Image.register_save(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# macOS icns file decoder, based on icns.py by Bob Ippolito.
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
|
9 |
+
# 2020-04-04 Allow saving on all operating systems.
|
10 |
+
#
|
11 |
+
# Copyright (c) 2004 by Bob Ippolito.
|
12 |
+
# Copyright (c) 2004 by Secret Labs.
|
13 |
+
# Copyright (c) 2004 by Fredrik Lundh.
|
14 |
+
# Copyright (c) 2014 by Alastair Houghton.
|
15 |
+
# Copyright (c) 2020 by Pan Jing.
|
16 |
+
#
|
17 |
+
# See the README file for information on usage and redistribution.
|
18 |
+
#
|
19 |
+
from __future__ import annotations
|
20 |
+
|
21 |
+
import io
|
22 |
+
import os
|
23 |
+
import struct
|
24 |
+
import sys
|
25 |
+
from typing import IO
|
26 |
+
|
27 |
+
from . import Image, ImageFile, PngImagePlugin, features
|
28 |
+
|
29 |
+
enable_jpeg2k = features.check_codec("jpg_2000")
|
30 |
+
if enable_jpeg2k:
|
31 |
+
from . import Jpeg2KImagePlugin
|
32 |
+
|
33 |
+
MAGIC = b"icns"
|
34 |
+
HEADERSIZE = 8
|
35 |
+
|
36 |
+
|
37 |
+
def nextheader(fobj):
|
38 |
+
return struct.unpack(">4sI", fobj.read(HEADERSIZE))
|
39 |
+
|
40 |
+
|
41 |
+
def read_32t(fobj, start_length, size):
|
42 |
+
# The 128x128 icon seems to have an extra header for some reason.
|
43 |
+
(start, length) = start_length
|
44 |
+
fobj.seek(start)
|
45 |
+
sig = fobj.read(4)
|
46 |
+
if sig != b"\x00\x00\x00\x00":
|
47 |
+
msg = "Unknown signature, expecting 0x00000000"
|
48 |
+
raise SyntaxError(msg)
|
49 |
+
return read_32(fobj, (start + 4, length - 4), size)
|
50 |
+
|
51 |
+
|
52 |
+
def read_32(fobj, start_length, size):
|
53 |
+
"""
|
54 |
+
Read a 32bit RGB icon resource. Seems to be either uncompressed or
|
55 |
+
an RLE packbits-like scheme.
|
56 |
+
"""
|
57 |
+
(start, length) = start_length
|
58 |
+
fobj.seek(start)
|
59 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
60 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
61 |
+
if length == sizesq * 3:
|
62 |
+
# uncompressed ("RGBRGBGB")
|
63 |
+
indata = fobj.read(length)
|
64 |
+
im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
|
65 |
+
else:
|
66 |
+
# decode image
|
67 |
+
im = Image.new("RGB", pixel_size, None)
|
68 |
+
for band_ix in range(3):
|
69 |
+
data = []
|
70 |
+
bytesleft = sizesq
|
71 |
+
while bytesleft > 0:
|
72 |
+
byte = fobj.read(1)
|
73 |
+
if not byte:
|
74 |
+
break
|
75 |
+
byte = byte[0]
|
76 |
+
if byte & 0x80:
|
77 |
+
blocksize = byte - 125
|
78 |
+
byte = fobj.read(1)
|
79 |
+
for i in range(blocksize):
|
80 |
+
data.append(byte)
|
81 |
+
else:
|
82 |
+
blocksize = byte + 1
|
83 |
+
data.append(fobj.read(blocksize))
|
84 |
+
bytesleft -= blocksize
|
85 |
+
if bytesleft <= 0:
|
86 |
+
break
|
87 |
+
if bytesleft != 0:
|
88 |
+
msg = f"Error reading channel [{repr(bytesleft)} left]"
|
89 |
+
raise SyntaxError(msg)
|
90 |
+
band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
|
91 |
+
im.im.putband(band.im, band_ix)
|
92 |
+
return {"RGB": im}
|
93 |
+
|
94 |
+
|
95 |
+
def read_mk(fobj, start_length, size):
|
96 |
+
# Alpha masks seem to be uncompressed
|
97 |
+
start = start_length[0]
|
98 |
+
fobj.seek(start)
|
99 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
100 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
101 |
+
band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
|
102 |
+
return {"A": band}
|
103 |
+
|
104 |
+
|
105 |
+
def read_png_or_jpeg2000(fobj, start_length, size):
|
106 |
+
(start, length) = start_length
|
107 |
+
fobj.seek(start)
|
108 |
+
sig = fobj.read(12)
|
109 |
+
if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
|
110 |
+
fobj.seek(start)
|
111 |
+
im = PngImagePlugin.PngImageFile(fobj)
|
112 |
+
Image._decompression_bomb_check(im.size)
|
113 |
+
return {"RGBA": im}
|
114 |
+
elif (
|
115 |
+
sig[:4] == b"\xff\x4f\xff\x51"
|
116 |
+
or sig[:4] == b"\x0d\x0a\x87\x0a"
|
117 |
+
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
118 |
+
):
|
119 |
+
if not enable_jpeg2k:
|
120 |
+
msg = (
|
121 |
+
"Unsupported icon subimage format (rebuild PIL "
|
122 |
+
"with JPEG 2000 support to fix this)"
|
123 |
+
)
|
124 |
+
raise ValueError(msg)
|
125 |
+
# j2k, jpc or j2c
|
126 |
+
fobj.seek(start)
|
127 |
+
jp2kstream = fobj.read(length)
|
128 |
+
f = io.BytesIO(jp2kstream)
|
129 |
+
im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
|
130 |
+
Image._decompression_bomb_check(im.size)
|
131 |
+
if im.mode != "RGBA":
|
132 |
+
im = im.convert("RGBA")
|
133 |
+
return {"RGBA": im}
|
134 |
+
else:
|
135 |
+
msg = "Unsupported icon subimage format"
|
136 |
+
raise ValueError(msg)
|
137 |
+
|
138 |
+
|
139 |
+
class IcnsFile:
|
140 |
+
SIZES = {
|
141 |
+
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
|
142 |
+
(512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
|
143 |
+
(256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
|
144 |
+
(256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
|
145 |
+
(128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
|
146 |
+
(128, 128, 1): [
|
147 |
+
(b"ic07", read_png_or_jpeg2000),
|
148 |
+
(b"it32", read_32t),
|
149 |
+
(b"t8mk", read_mk),
|
150 |
+
],
|
151 |
+
(64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
|
152 |
+
(32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
|
153 |
+
(48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
|
154 |
+
(32, 32, 1): [
|
155 |
+
(b"icp5", read_png_or_jpeg2000),
|
156 |
+
(b"il32", read_32),
|
157 |
+
(b"l8mk", read_mk),
|
158 |
+
],
|
159 |
+
(16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
|
160 |
+
(16, 16, 1): [
|
161 |
+
(b"icp4", read_png_or_jpeg2000),
|
162 |
+
(b"is32", read_32),
|
163 |
+
(b"s8mk", read_mk),
|
164 |
+
],
|
165 |
+
}
|
166 |
+
|
167 |
+
def __init__(self, fobj):
|
168 |
+
"""
|
169 |
+
fobj is a file-like object as an icns resource
|
170 |
+
"""
|
171 |
+
# signature : (start, length)
|
172 |
+
self.dct = dct = {}
|
173 |
+
self.fobj = fobj
|
174 |
+
sig, filesize = nextheader(fobj)
|
175 |
+
if not _accept(sig):
|
176 |
+
msg = "not an icns file"
|
177 |
+
raise SyntaxError(msg)
|
178 |
+
i = HEADERSIZE
|
179 |
+
while i < filesize:
|
180 |
+
sig, blocksize = nextheader(fobj)
|
181 |
+
if blocksize <= 0:
|
182 |
+
msg = "invalid block header"
|
183 |
+
raise SyntaxError(msg)
|
184 |
+
i += HEADERSIZE
|
185 |
+
blocksize -= HEADERSIZE
|
186 |
+
dct[sig] = (i, blocksize)
|
187 |
+
fobj.seek(blocksize, io.SEEK_CUR)
|
188 |
+
i += blocksize
|
189 |
+
|
190 |
+
def itersizes(self):
|
191 |
+
sizes = []
|
192 |
+
for size, fmts in self.SIZES.items():
|
193 |
+
for fmt, reader in fmts:
|
194 |
+
if fmt in self.dct:
|
195 |
+
sizes.append(size)
|
196 |
+
break
|
197 |
+
return sizes
|
198 |
+
|
199 |
+
def bestsize(self):
|
200 |
+
sizes = self.itersizes()
|
201 |
+
if not sizes:
|
202 |
+
msg = "No 32bit icon resources found"
|
203 |
+
raise SyntaxError(msg)
|
204 |
+
return max(sizes)
|
205 |
+
|
206 |
+
def dataforsize(self, size):
|
207 |
+
"""
|
208 |
+
Get an icon resource as {channel: array}. Note that
|
209 |
+
the arrays are bottom-up like windows bitmaps and will likely
|
210 |
+
need to be flipped or transposed in some way.
|
211 |
+
"""
|
212 |
+
dct = {}
|
213 |
+
for code, reader in self.SIZES[size]:
|
214 |
+
desc = self.dct.get(code)
|
215 |
+
if desc is not None:
|
216 |
+
dct.update(reader(self.fobj, desc, size))
|
217 |
+
return dct
|
218 |
+
|
219 |
+
def getimage(self, size=None):
|
220 |
+
if size is None:
|
221 |
+
size = self.bestsize()
|
222 |
+
if len(size) == 2:
|
223 |
+
size = (size[0], size[1], 1)
|
224 |
+
channels = self.dataforsize(size)
|
225 |
+
|
226 |
+
im = channels.get("RGBA", None)
|
227 |
+
if im:
|
228 |
+
return im
|
229 |
+
|
230 |
+
im = channels.get("RGB").copy()
|
231 |
+
try:
|
232 |
+
im.putalpha(channels["A"])
|
233 |
+
except KeyError:
|
234 |
+
pass
|
235 |
+
return im
|
236 |
+
|
237 |
+
|
238 |
+
##
|
239 |
+
# Image plugin for Mac OS icons.
|
240 |
+
|
241 |
+
|
242 |
+
class IcnsImageFile(ImageFile.ImageFile):
|
243 |
+
"""
|
244 |
+
PIL image support for Mac OS .icns files.
|
245 |
+
Chooses the best resolution, but will possibly load
|
246 |
+
a different size image if you mutate the size attribute
|
247 |
+
before calling 'load'.
|
248 |
+
|
249 |
+
The info dictionary has a key 'sizes' that is a list
|
250 |
+
of sizes that the icns file has.
|
251 |
+
"""
|
252 |
+
|
253 |
+
format = "ICNS"
|
254 |
+
format_description = "Mac OS icns resource"
|
255 |
+
|
256 |
+
def _open(self) -> None:
|
257 |
+
self.icns = IcnsFile(self.fp)
|
258 |
+
self._mode = "RGBA"
|
259 |
+
self.info["sizes"] = self.icns.itersizes()
|
260 |
+
self.best_size = self.icns.bestsize()
|
261 |
+
self.size = (
|
262 |
+
self.best_size[0] * self.best_size[2],
|
263 |
+
self.best_size[1] * self.best_size[2],
|
264 |
+
)
|
265 |
+
|
266 |
+
@property
|
267 |
+
def size(self):
|
268 |
+
return self._size
|
269 |
+
|
270 |
+
@size.setter
|
271 |
+
def size(self, value):
|
272 |
+
info_size = value
|
273 |
+
if info_size not in self.info["sizes"] and len(info_size) == 2:
|
274 |
+
info_size = (info_size[0], info_size[1], 1)
|
275 |
+
if (
|
276 |
+
info_size not in self.info["sizes"]
|
277 |
+
and len(info_size) == 3
|
278 |
+
and info_size[2] == 1
|
279 |
+
):
|
280 |
+
simple_sizes = [
|
281 |
+
(size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
|
282 |
+
]
|
283 |
+
if value in simple_sizes:
|
284 |
+
info_size = self.info["sizes"][simple_sizes.index(value)]
|
285 |
+
if info_size not in self.info["sizes"]:
|
286 |
+
msg = "This is not one of the allowed sizes of this image"
|
287 |
+
raise ValueError(msg)
|
288 |
+
self._size = value
|
289 |
+
|
290 |
+
def load(self):
|
291 |
+
if len(self.size) == 3:
|
292 |
+
self.best_size = self.size
|
293 |
+
self.size = (
|
294 |
+
self.best_size[0] * self.best_size[2],
|
295 |
+
self.best_size[1] * self.best_size[2],
|
296 |
+
)
|
297 |
+
|
298 |
+
px = Image.Image.load(self)
|
299 |
+
if self.im is not None and self.im.size == self.size:
|
300 |
+
# Already loaded
|
301 |
+
return px
|
302 |
+
self.load_prepare()
|
303 |
+
# This is likely NOT the best way to do it, but whatever.
|
304 |
+
im = self.icns.getimage(self.best_size)
|
305 |
+
|
306 |
+
# If this is a PNG or JPEG 2000, it won't be loaded yet
|
307 |
+
px = im.load()
|
308 |
+
|
309 |
+
self.im = im.im
|
310 |
+
self._mode = im.mode
|
311 |
+
self.size = im.size
|
312 |
+
|
313 |
+
return px
|
314 |
+
|
315 |
+
|
316 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
317 |
+
"""
|
318 |
+
Saves the image as a series of PNG files,
|
319 |
+
that are then combined into a .icns file.
|
320 |
+
"""
|
321 |
+
if hasattr(fp, "flush"):
|
322 |
+
fp.flush()
|
323 |
+
|
324 |
+
sizes = {
|
325 |
+
b"ic07": 128,
|
326 |
+
b"ic08": 256,
|
327 |
+
b"ic09": 512,
|
328 |
+
b"ic10": 1024,
|
329 |
+
b"ic11": 32,
|
330 |
+
b"ic12": 64,
|
331 |
+
b"ic13": 256,
|
332 |
+
b"ic14": 512,
|
333 |
+
}
|
334 |
+
provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
|
335 |
+
size_streams = {}
|
336 |
+
for size in set(sizes.values()):
|
337 |
+
image = (
|
338 |
+
provided_images[size]
|
339 |
+
if size in provided_images
|
340 |
+
else im.resize((size, size))
|
341 |
+
)
|
342 |
+
|
343 |
+
temp = io.BytesIO()
|
344 |
+
image.save(temp, "png")
|
345 |
+
size_streams[size] = temp.getvalue()
|
346 |
+
|
347 |
+
entries = []
|
348 |
+
for type, size in sizes.items():
|
349 |
+
stream = size_streams[size]
|
350 |
+
entries.append((type, HEADERSIZE + len(stream), stream))
|
351 |
+
|
352 |
+
# Header
|
353 |
+
fp.write(MAGIC)
|
354 |
+
file_length = HEADERSIZE # Header
|
355 |
+
file_length += HEADERSIZE + 8 * len(entries) # TOC
|
356 |
+
file_length += sum(entry[1] for entry in entries)
|
357 |
+
fp.write(struct.pack(">i", file_length))
|
358 |
+
|
359 |
+
# TOC
|
360 |
+
fp.write(b"TOC ")
|
361 |
+
fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
|
362 |
+
for entry in entries:
|
363 |
+
fp.write(entry[0])
|
364 |
+
fp.write(struct.pack(">i", entry[1]))
|
365 |
+
|
366 |
+
# Data
|
367 |
+
for entry in entries:
|
368 |
+
fp.write(entry[0])
|
369 |
+
fp.write(struct.pack(">i", entry[1]))
|
370 |
+
fp.write(entry[2])
|
371 |
+
|
372 |
+
if hasattr(fp, "flush"):
|
373 |
+
fp.flush()
|
374 |
+
|
375 |
+
|
376 |
+
def _accept(prefix: bytes) -> bool:
|
377 |
+
return prefix[:4] == MAGIC
|
378 |
+
|
379 |
+
|
380 |
+
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
|
381 |
+
Image.register_extension(IcnsImageFile.format, ".icns")
|
382 |
+
|
383 |
+
Image.register_save(IcnsImageFile.format, _save)
|
384 |
+
Image.register_mime(IcnsImageFile.format, "image/icns")
|
385 |
+
|
386 |
+
if __name__ == "__main__":
|
387 |
+
if len(sys.argv) < 2:
|
388 |
+
print("Syntax: python3 IcnsImagePlugin.py [file]")
|
389 |
+
sys.exit()
|
390 |
+
|
391 |
+
with open(sys.argv[1], "rb") as fp:
|
392 |
+
imf = IcnsImageFile(fp)
|
393 |
+
for size in imf.info["sizes"]:
|
394 |
+
width, height, scale = imf.size = size
|
395 |
+
imf.save(f"out-{width}-{height}-{scale}.png")
|
396 |
+
with Image.open(sys.argv[1]) as im:
|
397 |
+
im.save("out.png")
|
398 |
+
if sys.platform == "windows":
|
399 |
+
os.startfile("out.png")
|
MLPY/Lib/site-packages/PIL/IcoImagePlugin.py
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
|
16 |
+
# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
17 |
+
# <[email protected]>.
|
18 |
+
# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
19 |
+
#
|
20 |
+
# Icon format references:
|
21 |
+
# * https://en.wikipedia.org/wiki/ICO_(file_format)
|
22 |
+
# * https://msdn.microsoft.com/en-us/library/ms997538.aspx
|
23 |
+
from __future__ import annotations
|
24 |
+
|
25 |
+
import warnings
|
26 |
+
from io import BytesIO
|
27 |
+
from math import ceil, log
|
28 |
+
from typing import IO
|
29 |
+
|
30 |
+
from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
|
31 |
+
from ._binary import i16le as i16
|
32 |
+
from ._binary import i32le as i32
|
33 |
+
from ._binary import o8
|
34 |
+
from ._binary import o16le as o16
|
35 |
+
from ._binary import o32le as o32
|
36 |
+
|
37 |
+
#
|
38 |
+
# --------------------------------------------------------------------
|
39 |
+
|
40 |
+
_MAGIC = b"\0\0\1\0"
|
41 |
+
|
42 |
+
|
43 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
44 |
+
fp.write(_MAGIC) # (2+2)
|
45 |
+
bmp = im.encoderinfo.get("bitmap_format") == "bmp"
|
46 |
+
sizes = im.encoderinfo.get(
|
47 |
+
"sizes",
|
48 |
+
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
|
49 |
+
)
|
50 |
+
frames = []
|
51 |
+
provided_ims = [im] + im.encoderinfo.get("append_images", [])
|
52 |
+
width, height = im.size
|
53 |
+
for size in sorted(set(sizes)):
|
54 |
+
if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
|
55 |
+
continue
|
56 |
+
|
57 |
+
for provided_im in provided_ims:
|
58 |
+
if provided_im.size != size:
|
59 |
+
continue
|
60 |
+
frames.append(provided_im)
|
61 |
+
if bmp:
|
62 |
+
bits = BmpImagePlugin.SAVE[provided_im.mode][1]
|
63 |
+
bits_used = [bits]
|
64 |
+
for other_im in provided_ims:
|
65 |
+
if other_im.size != size:
|
66 |
+
continue
|
67 |
+
bits = BmpImagePlugin.SAVE[other_im.mode][1]
|
68 |
+
if bits not in bits_used:
|
69 |
+
# Another image has been supplied for this size
|
70 |
+
# with a different bit depth
|
71 |
+
frames.append(other_im)
|
72 |
+
bits_used.append(bits)
|
73 |
+
break
|
74 |
+
else:
|
75 |
+
# TODO: invent a more convenient method for proportional scalings
|
76 |
+
frame = provided_im.copy()
|
77 |
+
frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
|
78 |
+
frames.append(frame)
|
79 |
+
fp.write(o16(len(frames))) # idCount(2)
|
80 |
+
offset = fp.tell() + len(frames) * 16
|
81 |
+
for frame in frames:
|
82 |
+
width, height = frame.size
|
83 |
+
# 0 means 256
|
84 |
+
fp.write(o8(width if width < 256 else 0)) # bWidth(1)
|
85 |
+
fp.write(o8(height if height < 256 else 0)) # bHeight(1)
|
86 |
+
|
87 |
+
bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
|
88 |
+
fp.write(o8(colors)) # bColorCount(1)
|
89 |
+
fp.write(b"\0") # bReserved(1)
|
90 |
+
fp.write(b"\0\0") # wPlanes(2)
|
91 |
+
fp.write(o16(bits)) # wBitCount(2)
|
92 |
+
|
93 |
+
image_io = BytesIO()
|
94 |
+
if bmp:
|
95 |
+
frame.save(image_io, "dib")
|
96 |
+
|
97 |
+
if bits != 32:
|
98 |
+
and_mask = Image.new("1", size)
|
99 |
+
ImageFile._save(
|
100 |
+
and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
|
101 |
+
)
|
102 |
+
else:
|
103 |
+
frame.save(image_io, "png")
|
104 |
+
image_io.seek(0)
|
105 |
+
image_bytes = image_io.read()
|
106 |
+
if bmp:
|
107 |
+
image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
|
108 |
+
bytes_len = len(image_bytes)
|
109 |
+
fp.write(o32(bytes_len)) # dwBytesInRes(4)
|
110 |
+
fp.write(o32(offset)) # dwImageOffset(4)
|
111 |
+
current = fp.tell()
|
112 |
+
fp.seek(offset)
|
113 |
+
fp.write(image_bytes)
|
114 |
+
offset = offset + bytes_len
|
115 |
+
fp.seek(current)
|
116 |
+
|
117 |
+
|
118 |
+
def _accept(prefix: bytes) -> bool:
|
119 |
+
return prefix[:4] == _MAGIC
|
120 |
+
|
121 |
+
|
122 |
+
class IcoFile:
|
123 |
+
def __init__(self, buf):
|
124 |
+
"""
|
125 |
+
Parse image from file-like object containing ico file data
|
126 |
+
"""
|
127 |
+
|
128 |
+
# check magic
|
129 |
+
s = buf.read(6)
|
130 |
+
if not _accept(s):
|
131 |
+
msg = "not an ICO file"
|
132 |
+
raise SyntaxError(msg)
|
133 |
+
|
134 |
+
self.buf = buf
|
135 |
+
self.entry = []
|
136 |
+
|
137 |
+
# Number of items in file
|
138 |
+
self.nb_items = i16(s, 4)
|
139 |
+
|
140 |
+
# Get headers for each item
|
141 |
+
for i in range(self.nb_items):
|
142 |
+
s = buf.read(16)
|
143 |
+
|
144 |
+
icon_header = {
|
145 |
+
"width": s[0],
|
146 |
+
"height": s[1],
|
147 |
+
"nb_color": s[2], # No. of colors in image (0 if >=8bpp)
|
148 |
+
"reserved": s[3],
|
149 |
+
"planes": i16(s, 4),
|
150 |
+
"bpp": i16(s, 6),
|
151 |
+
"size": i32(s, 8),
|
152 |
+
"offset": i32(s, 12),
|
153 |
+
}
|
154 |
+
|
155 |
+
# See Wikipedia
|
156 |
+
for j in ("width", "height"):
|
157 |
+
if not icon_header[j]:
|
158 |
+
icon_header[j] = 256
|
159 |
+
|
160 |
+
# See Wikipedia notes about color depth.
|
161 |
+
# We need this just to differ images with equal sizes
|
162 |
+
icon_header["color_depth"] = (
|
163 |
+
icon_header["bpp"]
|
164 |
+
or (
|
165 |
+
icon_header["nb_color"] != 0
|
166 |
+
and ceil(log(icon_header["nb_color"], 2))
|
167 |
+
)
|
168 |
+
or 256
|
169 |
+
)
|
170 |
+
|
171 |
+
icon_header["dim"] = (icon_header["width"], icon_header["height"])
|
172 |
+
icon_header["square"] = icon_header["width"] * icon_header["height"]
|
173 |
+
|
174 |
+
self.entry.append(icon_header)
|
175 |
+
|
176 |
+
self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
|
177 |
+
# ICO images are usually squares
|
178 |
+
self.entry = sorted(self.entry, key=lambda x: x["square"], reverse=True)
|
179 |
+
|
180 |
+
def sizes(self):
|
181 |
+
"""
|
182 |
+
Get a list of all available icon sizes and color depths.
|
183 |
+
"""
|
184 |
+
return {(h["width"], h["height"]) for h in self.entry}
|
185 |
+
|
186 |
+
def getentryindex(self, size, bpp=False):
|
187 |
+
for i, h in enumerate(self.entry):
|
188 |
+
if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
|
189 |
+
return i
|
190 |
+
return 0
|
191 |
+
|
192 |
+
def getimage(self, size, bpp=False):
|
193 |
+
"""
|
194 |
+
Get an image from the icon
|
195 |
+
"""
|
196 |
+
return self.frame(self.getentryindex(size, bpp))
|
197 |
+
|
198 |
+
def frame(self, idx: int) -> Image.Image:
|
199 |
+
"""
|
200 |
+
Get an image from frame idx
|
201 |
+
"""
|
202 |
+
|
203 |
+
header = self.entry[idx]
|
204 |
+
|
205 |
+
self.buf.seek(header["offset"])
|
206 |
+
data = self.buf.read(8)
|
207 |
+
self.buf.seek(header["offset"])
|
208 |
+
|
209 |
+
im: Image.Image
|
210 |
+
if data[:8] == PngImagePlugin._MAGIC:
|
211 |
+
# png frame
|
212 |
+
im = PngImagePlugin.PngImageFile(self.buf)
|
213 |
+
Image._decompression_bomb_check(im.size)
|
214 |
+
else:
|
215 |
+
# XOR + AND mask bmp frame
|
216 |
+
im = BmpImagePlugin.DibImageFile(self.buf)
|
217 |
+
Image._decompression_bomb_check(im.size)
|
218 |
+
|
219 |
+
# change tile dimension to only encompass XOR image
|
220 |
+
im._size = (im.size[0], int(im.size[1] / 2))
|
221 |
+
d, e, o, a = im.tile[0]
|
222 |
+
im.tile[0] = d, (0, 0) + im.size, o, a
|
223 |
+
|
224 |
+
# figure out where AND mask image starts
|
225 |
+
bpp = header["bpp"]
|
226 |
+
if 32 == bpp:
|
227 |
+
# 32-bit color depth icon image allows semitransparent areas
|
228 |
+
# PIL's DIB format ignores transparency bits, recover them.
|
229 |
+
# The DIB is packed in BGRX byte order where X is the alpha
|
230 |
+
# channel.
|
231 |
+
|
232 |
+
# Back up to start of bmp data
|
233 |
+
self.buf.seek(o)
|
234 |
+
# extract every 4th byte (eg. 3,7,11,15,...)
|
235 |
+
alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
|
236 |
+
|
237 |
+
# convert to an 8bpp grayscale image
|
238 |
+
mask = Image.frombuffer(
|
239 |
+
"L", # 8bpp
|
240 |
+
im.size, # (w, h)
|
241 |
+
alpha_bytes, # source chars
|
242 |
+
"raw", # raw decoder
|
243 |
+
("L", 0, -1), # 8bpp inverted, unpadded, reversed
|
244 |
+
)
|
245 |
+
else:
|
246 |
+
# get AND image from end of bitmap
|
247 |
+
w = im.size[0]
|
248 |
+
if (w % 32) > 0:
|
249 |
+
# bitmap row data is aligned to word boundaries
|
250 |
+
w += 32 - (im.size[0] % 32)
|
251 |
+
|
252 |
+
# the total mask data is
|
253 |
+
# padded row size * height / bits per char
|
254 |
+
|
255 |
+
total_bytes = int((w * im.size[1]) / 8)
|
256 |
+
and_mask_offset = header["offset"] + header["size"] - total_bytes
|
257 |
+
|
258 |
+
self.buf.seek(and_mask_offset)
|
259 |
+
mask_data = self.buf.read(total_bytes)
|
260 |
+
|
261 |
+
# convert raw data to image
|
262 |
+
mask = Image.frombuffer(
|
263 |
+
"1", # 1 bpp
|
264 |
+
im.size, # (w, h)
|
265 |
+
mask_data, # source chars
|
266 |
+
"raw", # raw decoder
|
267 |
+
("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
|
268 |
+
)
|
269 |
+
|
270 |
+
# now we have two images, im is XOR image and mask is AND image
|
271 |
+
|
272 |
+
# apply mask image as alpha channel
|
273 |
+
im = im.convert("RGBA")
|
274 |
+
im.putalpha(mask)
|
275 |
+
|
276 |
+
return im
|
277 |
+
|
278 |
+
|
279 |
+
##
|
280 |
+
# Image plugin for Windows Icon files.
|
281 |
+
|
282 |
+
|
283 |
+
class IcoImageFile(ImageFile.ImageFile):
|
284 |
+
"""
|
285 |
+
PIL read-only image support for Microsoft Windows .ico files.
|
286 |
+
|
287 |
+
By default the largest resolution image in the file will be loaded. This
|
288 |
+
can be changed by altering the 'size' attribute before calling 'load'.
|
289 |
+
|
290 |
+
The info dictionary has a key 'sizes' that is a list of the sizes available
|
291 |
+
in the icon file.
|
292 |
+
|
293 |
+
Handles classic, XP and Vista icon formats.
|
294 |
+
|
295 |
+
When saving, PNG compression is used. Support for this was only added in
|
296 |
+
Windows Vista. If you are unable to view the icon in Windows, convert the
|
297 |
+
image to "RGBA" mode before saving.
|
298 |
+
|
299 |
+
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
300 |
+
<[email protected]>.
|
301 |
+
https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
302 |
+
"""
|
303 |
+
|
304 |
+
format = "ICO"
|
305 |
+
format_description = "Windows Icon"
|
306 |
+
|
307 |
+
def _open(self) -> None:
|
308 |
+
self.ico = IcoFile(self.fp)
|
309 |
+
self.info["sizes"] = self.ico.sizes()
|
310 |
+
self.size = self.ico.entry[0]["dim"]
|
311 |
+
self.load()
|
312 |
+
|
313 |
+
@property
|
314 |
+
def size(self):
|
315 |
+
return self._size
|
316 |
+
|
317 |
+
@size.setter
|
318 |
+
def size(self, value):
|
319 |
+
if value not in self.info["sizes"]:
|
320 |
+
msg = "This is not one of the allowed sizes of this image"
|
321 |
+
raise ValueError(msg)
|
322 |
+
self._size = value
|
323 |
+
|
324 |
+
def load(self):
|
325 |
+
if self.im is not None and self.im.size == self.size:
|
326 |
+
# Already loaded
|
327 |
+
return Image.Image.load(self)
|
328 |
+
im = self.ico.getimage(self.size)
|
329 |
+
# if tile is PNG, it won't really be loaded yet
|
330 |
+
im.load()
|
331 |
+
self.im = im.im
|
332 |
+
self.pyaccess = None
|
333 |
+
self._mode = im.mode
|
334 |
+
if im.palette:
|
335 |
+
self.palette = im.palette
|
336 |
+
if im.size != self.size:
|
337 |
+
warnings.warn("Image was not the expected size")
|
338 |
+
|
339 |
+
index = self.ico.getentryindex(self.size)
|
340 |
+
sizes = list(self.info["sizes"])
|
341 |
+
sizes[index] = im.size
|
342 |
+
self.info["sizes"] = set(sizes)
|
343 |
+
|
344 |
+
self.size = im.size
|
345 |
+
|
346 |
+
def load_seek(self, pos: int) -> None:
|
347 |
+
# Flag the ImageFile.Parser so that it
|
348 |
+
# just does all the decode at the end.
|
349 |
+
pass
|
350 |
+
|
351 |
+
|
352 |
+
#
|
353 |
+
# --------------------------------------------------------------------
|
354 |
+
|
355 |
+
|
356 |
+
Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
|
357 |
+
Image.register_save(IcoImageFile.format, _save)
|
358 |
+
Image.register_extension(IcoImageFile.format, ".ico")
|
359 |
+
|
360 |
+
Image.register_mime(IcoImageFile.format, "image/x-icon")
|
MLPY/Lib/site-packages/PIL/ImImagePlugin.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# IFUNC IM file handling for PIL
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 1995-09-01 fl Created.
|
9 |
+
# 1997-01-03 fl Save palette images
|
10 |
+
# 1997-01-08 fl Added sequence support
|
11 |
+
# 1997-01-23 fl Added P and RGB save support
|
12 |
+
# 1997-05-31 fl Read floating point images
|
13 |
+
# 1997-06-22 fl Save floating point images
|
14 |
+
# 1997-08-27 fl Read and save 1-bit images
|
15 |
+
# 1998-06-25 fl Added support for RGB+LUT images
|
16 |
+
# 1998-07-02 fl Added support for YCC images
|
17 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
18 |
+
# 1998-12-29 fl Added I;16 support
|
19 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
|
20 |
+
# 2003-09-26 fl Added LA/PA support
|
21 |
+
#
|
22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
23 |
+
# Copyright (c) 1995-2001 by Fredrik Lundh.
|
24 |
+
#
|
25 |
+
# See the README file for information on usage and redistribution.
|
26 |
+
#
|
27 |
+
from __future__ import annotations
|
28 |
+
|
29 |
+
import os
|
30 |
+
import re
|
31 |
+
from typing import IO, Any
|
32 |
+
|
33 |
+
from . import Image, ImageFile, ImagePalette
|
34 |
+
|
35 |
+
# --------------------------------------------------------------------
|
36 |
+
# Standard tags
|
37 |
+
|
38 |
+
COMMENT = "Comment"
|
39 |
+
DATE = "Date"
|
40 |
+
EQUIPMENT = "Digitalization equipment"
|
41 |
+
FRAMES = "File size (no of images)"
|
42 |
+
LUT = "Lut"
|
43 |
+
NAME = "Name"
|
44 |
+
SCALE = "Scale (x,y)"
|
45 |
+
SIZE = "Image size (x*y)"
|
46 |
+
MODE = "Image type"
|
47 |
+
|
48 |
+
TAGS = {
|
49 |
+
COMMENT: 0,
|
50 |
+
DATE: 0,
|
51 |
+
EQUIPMENT: 0,
|
52 |
+
FRAMES: 0,
|
53 |
+
LUT: 0,
|
54 |
+
NAME: 0,
|
55 |
+
SCALE: 0,
|
56 |
+
SIZE: 0,
|
57 |
+
MODE: 0,
|
58 |
+
}
|
59 |
+
|
60 |
+
OPEN = {
|
61 |
+
# ifunc93/p3cfunc formats
|
62 |
+
"0 1 image": ("1", "1"),
|
63 |
+
"L 1 image": ("1", "1"),
|
64 |
+
"Greyscale image": ("L", "L"),
|
65 |
+
"Grayscale image": ("L", "L"),
|
66 |
+
"RGB image": ("RGB", "RGB;L"),
|
67 |
+
"RLB image": ("RGB", "RLB"),
|
68 |
+
"RYB image": ("RGB", "RLB"),
|
69 |
+
"B1 image": ("1", "1"),
|
70 |
+
"B2 image": ("P", "P;2"),
|
71 |
+
"B4 image": ("P", "P;4"),
|
72 |
+
"X 24 image": ("RGB", "RGB"),
|
73 |
+
"L 32 S image": ("I", "I;32"),
|
74 |
+
"L 32 F image": ("F", "F;32"),
|
75 |
+
# old p3cfunc formats
|
76 |
+
"RGB3 image": ("RGB", "RGB;T"),
|
77 |
+
"RYB3 image": ("RGB", "RYB;T"),
|
78 |
+
# extensions
|
79 |
+
"LA image": ("LA", "LA;L"),
|
80 |
+
"PA image": ("LA", "PA;L"),
|
81 |
+
"RGBA image": ("RGBA", "RGBA;L"),
|
82 |
+
"RGBX image": ("RGB", "RGBX;L"),
|
83 |
+
"CMYK image": ("CMYK", "CMYK;L"),
|
84 |
+
"YCC image": ("YCbCr", "YCbCr;L"),
|
85 |
+
}
|
86 |
+
|
87 |
+
# ifunc95 extensions
|
88 |
+
for i in ["8", "8S", "16", "16S", "32", "32F"]:
|
89 |
+
OPEN[f"L {i} image"] = ("F", f"F;{i}")
|
90 |
+
OPEN[f"L*{i} image"] = ("F", f"F;{i}")
|
91 |
+
for i in ["16", "16L", "16B"]:
|
92 |
+
OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
|
93 |
+
OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
|
94 |
+
for i in ["32S"]:
|
95 |
+
OPEN[f"L {i} image"] = ("I", f"I;{i}")
|
96 |
+
OPEN[f"L*{i} image"] = ("I", f"I;{i}")
|
97 |
+
for j in range(2, 33):
|
98 |
+
OPEN[f"L*{j} image"] = ("F", f"F;{j}")
|
99 |
+
|
100 |
+
|
101 |
+
# --------------------------------------------------------------------
|
102 |
+
# Read IM directory
|
103 |
+
|
104 |
+
split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
|
105 |
+
|
106 |
+
|
107 |
+
def number(s: Any) -> float:
|
108 |
+
try:
|
109 |
+
return int(s)
|
110 |
+
except ValueError:
|
111 |
+
return float(s)
|
112 |
+
|
113 |
+
|
114 |
+
##
|
115 |
+
# Image plugin for the IFUNC IM file format.
|
116 |
+
|
117 |
+
|
118 |
+
class ImImageFile(ImageFile.ImageFile):
|
119 |
+
format = "IM"
|
120 |
+
format_description = "IFUNC Image Memory"
|
121 |
+
_close_exclusive_fp_after_loading = False
|
122 |
+
|
123 |
+
def _open(self) -> None:
|
124 |
+
# Quick rejection: if there's not an LF among the first
|
125 |
+
# 100 bytes, this is (probably) not a text header.
|
126 |
+
|
127 |
+
if b"\n" not in self.fp.read(100):
|
128 |
+
msg = "not an IM file"
|
129 |
+
raise SyntaxError(msg)
|
130 |
+
self.fp.seek(0)
|
131 |
+
|
132 |
+
n = 0
|
133 |
+
|
134 |
+
# Default values
|
135 |
+
self.info[MODE] = "L"
|
136 |
+
self.info[SIZE] = (512, 512)
|
137 |
+
self.info[FRAMES] = 1
|
138 |
+
|
139 |
+
self.rawmode = "L"
|
140 |
+
|
141 |
+
while True:
|
142 |
+
s = self.fp.read(1)
|
143 |
+
|
144 |
+
# Some versions of IFUNC uses \n\r instead of \r\n...
|
145 |
+
if s == b"\r":
|
146 |
+
continue
|
147 |
+
|
148 |
+
if not s or s == b"\0" or s == b"\x1A":
|
149 |
+
break
|
150 |
+
|
151 |
+
# FIXME: this may read whole file if not a text file
|
152 |
+
s = s + self.fp.readline()
|
153 |
+
|
154 |
+
if len(s) > 100:
|
155 |
+
msg = "not an IM file"
|
156 |
+
raise SyntaxError(msg)
|
157 |
+
|
158 |
+
if s[-2:] == b"\r\n":
|
159 |
+
s = s[:-2]
|
160 |
+
elif s[-1:] == b"\n":
|
161 |
+
s = s[:-1]
|
162 |
+
|
163 |
+
try:
|
164 |
+
m = split.match(s)
|
165 |
+
except re.error as e:
|
166 |
+
msg = "not an IM file"
|
167 |
+
raise SyntaxError(msg) from e
|
168 |
+
|
169 |
+
if m:
|
170 |
+
k, v = m.group(1, 2)
|
171 |
+
|
172 |
+
# Don't know if this is the correct encoding,
|
173 |
+
# but a decent guess (I guess)
|
174 |
+
k = k.decode("latin-1", "replace")
|
175 |
+
v = v.decode("latin-1", "replace")
|
176 |
+
|
177 |
+
# Convert value as appropriate
|
178 |
+
if k in [FRAMES, SCALE, SIZE]:
|
179 |
+
v = v.replace("*", ",")
|
180 |
+
v = tuple(map(number, v.split(",")))
|
181 |
+
if len(v) == 1:
|
182 |
+
v = v[0]
|
183 |
+
elif k == MODE and v in OPEN:
|
184 |
+
v, self.rawmode = OPEN[v]
|
185 |
+
|
186 |
+
# Add to dictionary. Note that COMMENT tags are
|
187 |
+
# combined into a list of strings.
|
188 |
+
if k == COMMENT:
|
189 |
+
if k in self.info:
|
190 |
+
self.info[k].append(v)
|
191 |
+
else:
|
192 |
+
self.info[k] = [v]
|
193 |
+
else:
|
194 |
+
self.info[k] = v
|
195 |
+
|
196 |
+
if k in TAGS:
|
197 |
+
n += 1
|
198 |
+
|
199 |
+
else:
|
200 |
+
msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
|
201 |
+
raise SyntaxError(msg)
|
202 |
+
|
203 |
+
if not n:
|
204 |
+
msg = "Not an IM file"
|
205 |
+
raise SyntaxError(msg)
|
206 |
+
|
207 |
+
# Basic attributes
|
208 |
+
self._size = self.info[SIZE]
|
209 |
+
self._mode = self.info[MODE]
|
210 |
+
|
211 |
+
# Skip forward to start of image data
|
212 |
+
while s and s[:1] != b"\x1A":
|
213 |
+
s = self.fp.read(1)
|
214 |
+
if not s:
|
215 |
+
msg = "File truncated"
|
216 |
+
raise SyntaxError(msg)
|
217 |
+
|
218 |
+
if LUT in self.info:
|
219 |
+
# convert lookup table to palette or lut attribute
|
220 |
+
palette = self.fp.read(768)
|
221 |
+
greyscale = 1 # greyscale palette
|
222 |
+
linear = 1 # linear greyscale palette
|
223 |
+
for i in range(256):
|
224 |
+
if palette[i] == palette[i + 256] == palette[i + 512]:
|
225 |
+
if palette[i] != i:
|
226 |
+
linear = 0
|
227 |
+
else:
|
228 |
+
greyscale = 0
|
229 |
+
if self.mode in ["L", "LA", "P", "PA"]:
|
230 |
+
if greyscale:
|
231 |
+
if not linear:
|
232 |
+
self.lut = list(palette[:256])
|
233 |
+
else:
|
234 |
+
if self.mode in ["L", "P"]:
|
235 |
+
self._mode = self.rawmode = "P"
|
236 |
+
elif self.mode in ["LA", "PA"]:
|
237 |
+
self._mode = "PA"
|
238 |
+
self.rawmode = "PA;L"
|
239 |
+
self.palette = ImagePalette.raw("RGB;L", palette)
|
240 |
+
elif self.mode == "RGB":
|
241 |
+
if not greyscale or not linear:
|
242 |
+
self.lut = list(palette)
|
243 |
+
|
244 |
+
self.frame = 0
|
245 |
+
|
246 |
+
self.__offset = offs = self.fp.tell()
|
247 |
+
|
248 |
+
self._fp = self.fp # FIXME: hack
|
249 |
+
|
250 |
+
if self.rawmode[:2] == "F;":
|
251 |
+
# ifunc95 formats
|
252 |
+
try:
|
253 |
+
# use bit decoder (if necessary)
|
254 |
+
bits = int(self.rawmode[2:])
|
255 |
+
if bits not in [8, 16, 32]:
|
256 |
+
self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
|
257 |
+
return
|
258 |
+
except ValueError:
|
259 |
+
pass
|
260 |
+
|
261 |
+
if self.rawmode in ["RGB;T", "RYB;T"]:
|
262 |
+
# Old LabEye/3PC files. Would be very surprised if anyone
|
263 |
+
# ever stumbled upon such a file ;-)
|
264 |
+
size = self.size[0] * self.size[1]
|
265 |
+
self.tile = [
|
266 |
+
("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
|
267 |
+
("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
|
268 |
+
("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
|
269 |
+
]
|
270 |
+
else:
|
271 |
+
# LabEye/IFUNC files
|
272 |
+
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
273 |
+
|
274 |
+
@property
|
275 |
+
def n_frames(self) -> int:
|
276 |
+
return self.info[FRAMES]
|
277 |
+
|
278 |
+
@property
|
279 |
+
def is_animated(self) -> bool:
|
280 |
+
return self.info[FRAMES] > 1
|
281 |
+
|
282 |
+
def seek(self, frame: int) -> None:
|
283 |
+
if not self._seek_check(frame):
|
284 |
+
return
|
285 |
+
|
286 |
+
self.frame = frame
|
287 |
+
|
288 |
+
if self.mode == "1":
|
289 |
+
bits = 1
|
290 |
+
else:
|
291 |
+
bits = 8 * len(self.mode)
|
292 |
+
|
293 |
+
size = ((self.size[0] * bits + 7) // 8) * self.size[1]
|
294 |
+
offs = self.__offset + frame * size
|
295 |
+
|
296 |
+
self.fp = self._fp
|
297 |
+
|
298 |
+
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
299 |
+
|
300 |
+
def tell(self) -> int:
|
301 |
+
return self.frame
|
302 |
+
|
303 |
+
|
304 |
+
#
|
305 |
+
# --------------------------------------------------------------------
|
306 |
+
# Save IM files
|
307 |
+
|
308 |
+
|
309 |
+
SAVE = {
|
310 |
+
# mode: (im type, raw mode)
|
311 |
+
"1": ("0 1", "1"),
|
312 |
+
"L": ("Greyscale", "L"),
|
313 |
+
"LA": ("LA", "LA;L"),
|
314 |
+
"P": ("Greyscale", "P"),
|
315 |
+
"PA": ("LA", "PA;L"),
|
316 |
+
"I": ("L 32S", "I;32S"),
|
317 |
+
"I;16": ("L 16", "I;16"),
|
318 |
+
"I;16L": ("L 16L", "I;16L"),
|
319 |
+
"I;16B": ("L 16B", "I;16B"),
|
320 |
+
"F": ("L 32F", "F;32F"),
|
321 |
+
"RGB": ("RGB", "RGB;L"),
|
322 |
+
"RGBA": ("RGBA", "RGBA;L"),
|
323 |
+
"RGBX": ("RGBX", "RGBX;L"),
|
324 |
+
"CMYK": ("CMYK", "CMYK;L"),
|
325 |
+
"YCbCr": ("YCC", "YCbCr;L"),
|
326 |
+
}
|
327 |
+
|
328 |
+
|
329 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
330 |
+
try:
|
331 |
+
image_type, rawmode = SAVE[im.mode]
|
332 |
+
except KeyError as e:
|
333 |
+
msg = f"Cannot save {im.mode} images as IM"
|
334 |
+
raise ValueError(msg) from e
|
335 |
+
|
336 |
+
frames = im.encoderinfo.get("frames", 1)
|
337 |
+
|
338 |
+
fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
|
339 |
+
if filename:
|
340 |
+
# Each line must be 100 characters or less,
|
341 |
+
# or: SyntaxError("not an IM file")
|
342 |
+
# 8 characters are used for "Name: " and "\r\n"
|
343 |
+
# Keep just the filename, ditch the potentially overlong path
|
344 |
+
if isinstance(filename, bytes):
|
345 |
+
filename = filename.decode("ascii")
|
346 |
+
name, ext = os.path.splitext(os.path.basename(filename))
|
347 |
+
name = "".join([name[: 92 - len(ext)], ext])
|
348 |
+
|
349 |
+
fp.write(f"Name: {name}\r\n".encode("ascii"))
|
350 |
+
fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
|
351 |
+
fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
|
352 |
+
if im.mode in ["P", "PA"]:
|
353 |
+
fp.write(b"Lut: 1\r\n")
|
354 |
+
fp.write(b"\000" * (511 - fp.tell()) + b"\032")
|
355 |
+
if im.mode in ["P", "PA"]:
|
356 |
+
im_palette = im.im.getpalette("RGB", "RGB;L")
|
357 |
+
colors = len(im_palette) // 3
|
358 |
+
palette = b""
|
359 |
+
for i in range(3):
|
360 |
+
palette += im_palette[colors * i : colors * (i + 1)]
|
361 |
+
palette += b"\x00" * (256 - colors)
|
362 |
+
fp.write(palette) # 768 bytes
|
363 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
|
364 |
+
|
365 |
+
|
366 |
+
#
|
367 |
+
# --------------------------------------------------------------------
|
368 |
+
# Registry
|
369 |
+
|
370 |
+
|
371 |
+
Image.register_open(ImImageFile.format, ImImageFile)
|
372 |
+
Image.register_save(ImImageFile.format, _save)
|
373 |
+
|
374 |
+
Image.register_extension(ImImageFile.format, ".im")
|
MLPY/Lib/site-packages/PIL/Image.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
MLPY/Lib/site-packages/PIL/ImageChops.py
ADDED
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# standard channel operations
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-03-24 fl Created
|
9 |
+
# 1996-08-13 fl Added logical operations (for "1" images)
|
10 |
+
# 2000-10-12 fl Added offset method (from Image.py)
|
11 |
+
#
|
12 |
+
# Copyright (c) 1997-2000 by Secret Labs AB
|
13 |
+
# Copyright (c) 1996-2000 by Fredrik Lundh
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
from . import Image
|
21 |
+
|
22 |
+
|
23 |
+
def constant(image: Image.Image, value: int) -> Image.Image:
|
24 |
+
"""Fill a channel with a given gray level.
|
25 |
+
|
26 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
27 |
+
"""
|
28 |
+
|
29 |
+
return Image.new("L", image.size, value)
|
30 |
+
|
31 |
+
|
32 |
+
def duplicate(image: Image.Image) -> Image.Image:
|
33 |
+
"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
|
34 |
+
|
35 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
36 |
+
"""
|
37 |
+
|
38 |
+
return image.copy()
|
39 |
+
|
40 |
+
|
41 |
+
def invert(image: Image.Image) -> Image.Image:
|
42 |
+
"""
|
43 |
+
Invert an image (channel). ::
|
44 |
+
|
45 |
+
out = MAX - image
|
46 |
+
|
47 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
48 |
+
"""
|
49 |
+
|
50 |
+
image.load()
|
51 |
+
return image._new(image.im.chop_invert())
|
52 |
+
|
53 |
+
|
54 |
+
def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
55 |
+
"""
|
56 |
+
Compares the two images, pixel by pixel, and returns a new image containing
|
57 |
+
the lighter values. ::
|
58 |
+
|
59 |
+
out = max(image1, image2)
|
60 |
+
|
61 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
62 |
+
"""
|
63 |
+
|
64 |
+
image1.load()
|
65 |
+
image2.load()
|
66 |
+
return image1._new(image1.im.chop_lighter(image2.im))
|
67 |
+
|
68 |
+
|
69 |
+
def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
70 |
+
"""
|
71 |
+
Compares the two images, pixel by pixel, and returns a new image containing
|
72 |
+
the darker values. ::
|
73 |
+
|
74 |
+
out = min(image1, image2)
|
75 |
+
|
76 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
77 |
+
"""
|
78 |
+
|
79 |
+
image1.load()
|
80 |
+
image2.load()
|
81 |
+
return image1._new(image1.im.chop_darker(image2.im))
|
82 |
+
|
83 |
+
|
84 |
+
def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
85 |
+
"""
|
86 |
+
Returns the absolute value of the pixel-by-pixel difference between the two
|
87 |
+
images. ::
|
88 |
+
|
89 |
+
out = abs(image1 - image2)
|
90 |
+
|
91 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
92 |
+
"""
|
93 |
+
|
94 |
+
image1.load()
|
95 |
+
image2.load()
|
96 |
+
return image1._new(image1.im.chop_difference(image2.im))
|
97 |
+
|
98 |
+
|
99 |
+
def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
100 |
+
"""
|
101 |
+
Superimposes two images on top of each other.
|
102 |
+
|
103 |
+
If you multiply an image with a solid black image, the result is black. If
|
104 |
+
you multiply with a solid white image, the image is unaffected. ::
|
105 |
+
|
106 |
+
out = image1 * image2 / MAX
|
107 |
+
|
108 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
109 |
+
"""
|
110 |
+
|
111 |
+
image1.load()
|
112 |
+
image2.load()
|
113 |
+
return image1._new(image1.im.chop_multiply(image2.im))
|
114 |
+
|
115 |
+
|
116 |
+
def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
117 |
+
"""
|
118 |
+
Superimposes two inverted images on top of each other. ::
|
119 |
+
|
120 |
+
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
|
121 |
+
|
122 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
123 |
+
"""
|
124 |
+
|
125 |
+
image1.load()
|
126 |
+
image2.load()
|
127 |
+
return image1._new(image1.im.chop_screen(image2.im))
|
128 |
+
|
129 |
+
|
130 |
+
def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
131 |
+
"""
|
132 |
+
Superimposes two images on top of each other using the Soft Light algorithm
|
133 |
+
|
134 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
135 |
+
"""
|
136 |
+
|
137 |
+
image1.load()
|
138 |
+
image2.load()
|
139 |
+
return image1._new(image1.im.chop_soft_light(image2.im))
|
140 |
+
|
141 |
+
|
142 |
+
def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
143 |
+
"""
|
144 |
+
Superimposes two images on top of each other using the Hard Light algorithm
|
145 |
+
|
146 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
147 |
+
"""
|
148 |
+
|
149 |
+
image1.load()
|
150 |
+
image2.load()
|
151 |
+
return image1._new(image1.im.chop_hard_light(image2.im))
|
152 |
+
|
153 |
+
|
154 |
+
def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
155 |
+
"""
|
156 |
+
Superimposes two images on top of each other using the Overlay algorithm
|
157 |
+
|
158 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
159 |
+
"""
|
160 |
+
|
161 |
+
image1.load()
|
162 |
+
image2.load()
|
163 |
+
return image1._new(image1.im.chop_overlay(image2.im))
|
164 |
+
|
165 |
+
|
166 |
+
def add(
|
167 |
+
image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
|
168 |
+
) -> Image.Image:
|
169 |
+
"""
|
170 |
+
Adds two images, dividing the result by scale and adding the
|
171 |
+
offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
|
172 |
+
|
173 |
+
out = ((image1 + image2) / scale + offset)
|
174 |
+
|
175 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
176 |
+
"""
|
177 |
+
|
178 |
+
image1.load()
|
179 |
+
image2.load()
|
180 |
+
return image1._new(image1.im.chop_add(image2.im, scale, offset))
|
181 |
+
|
182 |
+
|
183 |
+
def subtract(
|
184 |
+
image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
|
185 |
+
) -> Image.Image:
|
186 |
+
"""
|
187 |
+
Subtracts two images, dividing the result by scale and adding the offset.
|
188 |
+
If omitted, scale defaults to 1.0, and offset to 0.0. ::
|
189 |
+
|
190 |
+
out = ((image1 - image2) / scale + offset)
|
191 |
+
|
192 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
193 |
+
"""
|
194 |
+
|
195 |
+
image1.load()
|
196 |
+
image2.load()
|
197 |
+
return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
|
198 |
+
|
199 |
+
|
200 |
+
def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
201 |
+
"""Add two images, without clipping the result. ::
|
202 |
+
|
203 |
+
out = ((image1 + image2) % MAX)
|
204 |
+
|
205 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
206 |
+
"""
|
207 |
+
|
208 |
+
image1.load()
|
209 |
+
image2.load()
|
210 |
+
return image1._new(image1.im.chop_add_modulo(image2.im))
|
211 |
+
|
212 |
+
|
213 |
+
def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
214 |
+
"""Subtract two images, without clipping the result. ::
|
215 |
+
|
216 |
+
out = ((image1 - image2) % MAX)
|
217 |
+
|
218 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
219 |
+
"""
|
220 |
+
|
221 |
+
image1.load()
|
222 |
+
image2.load()
|
223 |
+
return image1._new(image1.im.chop_subtract_modulo(image2.im))
|
224 |
+
|
225 |
+
|
226 |
+
def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
227 |
+
"""Logical AND between two images.
|
228 |
+
|
229 |
+
Both of the images must have mode "1". If you would like to perform a
|
230 |
+
logical AND on an image with a mode other than "1", try
|
231 |
+
:py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
|
232 |
+
as the second image. ::
|
233 |
+
|
234 |
+
out = ((image1 and image2) % MAX)
|
235 |
+
|
236 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
237 |
+
"""
|
238 |
+
|
239 |
+
image1.load()
|
240 |
+
image2.load()
|
241 |
+
return image1._new(image1.im.chop_and(image2.im))
|
242 |
+
|
243 |
+
|
244 |
+
def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
245 |
+
"""Logical OR between two images.
|
246 |
+
|
247 |
+
Both of the images must have mode "1". ::
|
248 |
+
|
249 |
+
out = ((image1 or image2) % MAX)
|
250 |
+
|
251 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
252 |
+
"""
|
253 |
+
|
254 |
+
image1.load()
|
255 |
+
image2.load()
|
256 |
+
return image1._new(image1.im.chop_or(image2.im))
|
257 |
+
|
258 |
+
|
259 |
+
def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
260 |
+
"""Logical XOR between two images.
|
261 |
+
|
262 |
+
Both of the images must have mode "1". ::
|
263 |
+
|
264 |
+
out = ((bool(image1) != bool(image2)) % MAX)
|
265 |
+
|
266 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
267 |
+
"""
|
268 |
+
|
269 |
+
image1.load()
|
270 |
+
image2.load()
|
271 |
+
return image1._new(image1.im.chop_xor(image2.im))
|
272 |
+
|
273 |
+
|
274 |
+
def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
|
275 |
+
"""Blend images using constant transparency weight. Alias for
|
276 |
+
:py:func:`PIL.Image.blend`.
|
277 |
+
|
278 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
279 |
+
"""
|
280 |
+
|
281 |
+
return Image.blend(image1, image2, alpha)
|
282 |
+
|
283 |
+
|
284 |
+
def composite(
|
285 |
+
image1: Image.Image, image2: Image.Image, mask: Image.Image
|
286 |
+
) -> Image.Image:
|
287 |
+
"""Create composite using transparency mask. Alias for
|
288 |
+
:py:func:`PIL.Image.composite`.
|
289 |
+
|
290 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
291 |
+
"""
|
292 |
+
|
293 |
+
return Image.composite(image1, image2, mask)
|
294 |
+
|
295 |
+
|
296 |
+
def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
|
297 |
+
"""Returns a copy of the image where data has been offset by the given
|
298 |
+
distances. Data wraps around the edges. If ``yoffset`` is omitted, it
|
299 |
+
is assumed to be equal to ``xoffset``.
|
300 |
+
|
301 |
+
:param image: Input image.
|
302 |
+
:param xoffset: The horizontal distance.
|
303 |
+
:param yoffset: The vertical distance. If omitted, both
|
304 |
+
distances are set to the same value.
|
305 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
306 |
+
"""
|
307 |
+
|
308 |
+
if yoffset is None:
|
309 |
+
yoffset = xoffset
|
310 |
+
image.load()
|
311 |
+
return image._new(image.im.offset(xoffset, yoffset))
|
MLPY/Lib/site-packages/PIL/ImageCms.py
ADDED
@@ -0,0 +1,1127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# The Python Imaging Library.
|
2 |
+
# $Id$
|
3 |
+
|
4 |
+
# Optional color management support, based on Kevin Cazabon's PyCMS
|
5 |
+
# library.
|
6 |
+
|
7 |
+
# Originally released under LGPL. Graciously donated to PIL in
|
8 |
+
# March 2009, for distribution under the standard PIL license
|
9 |
+
|
10 |
+
# History:
|
11 |
+
|
12 |
+
# 2009-03-08 fl Added to PIL.
|
13 |
+
|
14 |
+
# Copyright (C) 2002-2003 Kevin Cazabon
|
15 |
+
# Copyright (c) 2009 by Fredrik Lundh
|
16 |
+
# Copyright (c) 2013 by Eric Soroos
|
17 |
+
|
18 |
+
# See the README file for information on usage and redistribution. See
|
19 |
+
# below for the original description.
|
20 |
+
from __future__ import annotations
|
21 |
+
|
22 |
+
import operator
|
23 |
+
import sys
|
24 |
+
from enum import IntEnum, IntFlag
|
25 |
+
from functools import reduce
|
26 |
+
from typing import Any, Literal, SupportsFloat, SupportsInt, Union
|
27 |
+
|
28 |
+
from . import Image, __version__
|
29 |
+
from ._deprecate import deprecate
|
30 |
+
from ._typing import SupportsRead
|
31 |
+
|
32 |
+
try:
|
33 |
+
from . import _imagingcms as core
|
34 |
+
except ImportError as ex:
|
35 |
+
# Allow error import for doc purposes, but error out when accessing
|
36 |
+
# anything in core.
|
37 |
+
from ._util import DeferredError
|
38 |
+
|
39 |
+
core = DeferredError.new(ex)
|
40 |
+
|
41 |
+
_DESCRIPTION = """
|
42 |
+
pyCMS
|
43 |
+
|
44 |
+
a Python / PIL interface to the littleCMS ICC Color Management System
|
45 |
+
Copyright (C) 2002-2003 Kevin Cazabon
|
46 | |
47 |
+
https://www.cazabon.com
|
48 |
+
|
49 |
+
pyCMS home page: https://www.cazabon.com/pyCMS
|
50 |
+
littleCMS home page: https://www.littlecms.com
|
51 |
+
(littleCMS is Copyright (C) 1998-2001 Marti Maria)
|
52 |
+
|
53 |
+
Originally released under LGPL. Graciously donated to PIL in
|
54 |
+
March 2009, for distribution under the standard PIL license
|
55 |
+
|
56 |
+
The pyCMS.py module provides a "clean" interface between Python/PIL and
|
57 |
+
pyCMSdll, taking care of some of the more complex handling of the direct
|
58 |
+
pyCMSdll functions, as well as error-checking and making sure that all
|
59 |
+
relevant data is kept together.
|
60 |
+
|
61 |
+
While it is possible to call pyCMSdll functions directly, it's not highly
|
62 |
+
recommended.
|
63 |
+
|
64 |
+
Version History:
|
65 |
+
|
66 |
+
1.0.0 pil Oct 2013 Port to LCMS 2.
|
67 |
+
|
68 |
+
0.1.0 pil mod March 10, 2009
|
69 |
+
|
70 |
+
Renamed display profile to proof profile. The proof
|
71 |
+
profile is the profile of the device that is being
|
72 |
+
simulated, not the profile of the device which is
|
73 |
+
actually used to display/print the final simulation
|
74 |
+
(that'd be the output profile) - also see LCMSAPI.txt
|
75 |
+
input colorspace -> using 'renderingIntent' -> proof
|
76 |
+
colorspace -> using 'proofRenderingIntent' -> output
|
77 |
+
colorspace
|
78 |
+
|
79 |
+
Added LCMS FLAGS support.
|
80 |
+
Added FLAGS["SOFTPROOFING"] as default flag for
|
81 |
+
buildProofTransform (otherwise the proof profile/intent
|
82 |
+
would be ignored).
|
83 |
+
|
84 |
+
0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
|
85 |
+
|
86 |
+
0.0.2 alpha Jan 6, 2002
|
87 |
+
|
88 |
+
Added try/except statements around type() checks of
|
89 |
+
potential CObjects... Python won't let you use type()
|
90 |
+
on them, and raises a TypeError (stupid, if you ask
|
91 |
+
me!)
|
92 |
+
|
93 |
+
Added buildProofTransformFromOpenProfiles() function.
|
94 |
+
Additional fixes in DLL, see DLL code for details.
|
95 |
+
|
96 |
+
0.0.1 alpha first public release, Dec. 26, 2002
|
97 |
+
|
98 |
+
Known to-do list with current version (of Python interface, not pyCMSdll):
|
99 |
+
|
100 |
+
none
|
101 |
+
|
102 |
+
"""
|
103 |
+
|
104 |
+
_VERSION = "1.0.0 pil"
|
105 |
+
|
106 |
+
|
107 |
+
def __getattr__(name: str) -> Any:
|
108 |
+
if name == "DESCRIPTION":
|
109 |
+
deprecate("PIL.ImageCms.DESCRIPTION", 12)
|
110 |
+
return _DESCRIPTION
|
111 |
+
elif name == "VERSION":
|
112 |
+
deprecate("PIL.ImageCms.VERSION", 12)
|
113 |
+
return _VERSION
|
114 |
+
elif name == "FLAGS":
|
115 |
+
deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
|
116 |
+
return _FLAGS
|
117 |
+
msg = f"module '{__name__}' has no attribute '{name}'"
|
118 |
+
raise AttributeError(msg)
|
119 |
+
|
120 |
+
|
121 |
+
# --------------------------------------------------------------------.
|
122 |
+
|
123 |
+
|
124 |
+
#
|
125 |
+
# intent/direction values
|
126 |
+
|
127 |
+
|
128 |
+
class Intent(IntEnum):
|
129 |
+
PERCEPTUAL = 0
|
130 |
+
RELATIVE_COLORIMETRIC = 1
|
131 |
+
SATURATION = 2
|
132 |
+
ABSOLUTE_COLORIMETRIC = 3
|
133 |
+
|
134 |
+
|
135 |
+
class Direction(IntEnum):
|
136 |
+
INPUT = 0
|
137 |
+
OUTPUT = 1
|
138 |
+
PROOF = 2
|
139 |
+
|
140 |
+
|
141 |
+
#
|
142 |
+
# flags
|
143 |
+
|
144 |
+
|
145 |
+
class Flags(IntFlag):
|
146 |
+
"""Flags and documentation are taken from ``lcms2.h``."""
|
147 |
+
|
148 |
+
NONE = 0
|
149 |
+
NOCACHE = 0x0040
|
150 |
+
"""Inhibit 1-pixel cache"""
|
151 |
+
NOOPTIMIZE = 0x0100
|
152 |
+
"""Inhibit optimizations"""
|
153 |
+
NULLTRANSFORM = 0x0200
|
154 |
+
"""Don't transform anyway"""
|
155 |
+
GAMUTCHECK = 0x1000
|
156 |
+
"""Out of Gamut alarm"""
|
157 |
+
SOFTPROOFING = 0x4000
|
158 |
+
"""Do softproofing"""
|
159 |
+
BLACKPOINTCOMPENSATION = 0x2000
|
160 |
+
NOWHITEONWHITEFIXUP = 0x0004
|
161 |
+
"""Don't fix scum dot"""
|
162 |
+
HIGHRESPRECALC = 0x0400
|
163 |
+
"""Use more memory to give better accuracy"""
|
164 |
+
LOWRESPRECALC = 0x0800
|
165 |
+
"""Use less memory to minimize resources"""
|
166 |
+
# this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
|
167 |
+
USE_8BITS_DEVICELINK = 0x0008
|
168 |
+
"""Create 8 bits devicelinks"""
|
169 |
+
GUESSDEVICECLASS = 0x0020
|
170 |
+
"""Guess device class (for ``transform2devicelink``)"""
|
171 |
+
KEEP_SEQUENCE = 0x0080
|
172 |
+
"""Keep profile sequence for devicelink creation"""
|
173 |
+
FORCE_CLUT = 0x0002
|
174 |
+
"""Force CLUT optimization"""
|
175 |
+
CLUT_POST_LINEARIZATION = 0x0001
|
176 |
+
"""create postlinearization tables if possible"""
|
177 |
+
CLUT_PRE_LINEARIZATION = 0x0010
|
178 |
+
"""create prelinearization tables if possible"""
|
179 |
+
NONEGATIVES = 0x8000
|
180 |
+
"""Prevent negative numbers in floating point transforms"""
|
181 |
+
COPY_ALPHA = 0x04000000
|
182 |
+
"""Alpha channels are copied on ``cmsDoTransform()``"""
|
183 |
+
NODEFAULTRESOURCEDEF = 0x01000000
|
184 |
+
|
185 |
+
_GRIDPOINTS_1 = 1 << 16
|
186 |
+
_GRIDPOINTS_2 = 2 << 16
|
187 |
+
_GRIDPOINTS_4 = 4 << 16
|
188 |
+
_GRIDPOINTS_8 = 8 << 16
|
189 |
+
_GRIDPOINTS_16 = 16 << 16
|
190 |
+
_GRIDPOINTS_32 = 32 << 16
|
191 |
+
_GRIDPOINTS_64 = 64 << 16
|
192 |
+
_GRIDPOINTS_128 = 128 << 16
|
193 |
+
|
194 |
+
@staticmethod
|
195 |
+
def GRIDPOINTS(n: int) -> Flags:
|
196 |
+
"""
|
197 |
+
Fine-tune control over number of gridpoints
|
198 |
+
|
199 |
+
:param n: :py:class:`int` in range ``0 <= n <= 255``
|
200 |
+
"""
|
201 |
+
return Flags.NONE | ((n & 0xFF) << 16)
|
202 |
+
|
203 |
+
|
204 |
+
_MAX_FLAG = reduce(operator.or_, Flags)
|
205 |
+
|
206 |
+
|
207 |
+
_FLAGS = {
|
208 |
+
"MATRIXINPUT": 1,
|
209 |
+
"MATRIXOUTPUT": 2,
|
210 |
+
"MATRIXONLY": (1 | 2),
|
211 |
+
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
|
212 |
+
# Don't create prelinearization tables on precalculated transforms
|
213 |
+
# (internal use):
|
214 |
+
"NOPRELINEARIZATION": 16,
|
215 |
+
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
|
216 |
+
"NOTCACHE": 64, # Inhibit 1-pixel cache
|
217 |
+
"NOTPRECALC": 256,
|
218 |
+
"NULLTRANSFORM": 512, # Don't transform anyway
|
219 |
+
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
|
220 |
+
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
|
221 |
+
"WHITEBLACKCOMPENSATION": 8192,
|
222 |
+
"BLACKPOINTCOMPENSATION": 8192,
|
223 |
+
"GAMUTCHECK": 4096, # Out of Gamut alarm
|
224 |
+
"SOFTPROOFING": 16384, # Do softproofing
|
225 |
+
"PRESERVEBLACK": 32768, # Black preservation
|
226 |
+
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
|
227 |
+
"GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
|
228 |
+
}
|
229 |
+
|
230 |
+
|
231 |
+
# --------------------------------------------------------------------.
|
232 |
+
# Experimental PIL-level API
|
233 |
+
# --------------------------------------------------------------------.
|
234 |
+
|
235 |
+
##
|
236 |
+
# Profile.
|
237 |
+
|
238 |
+
|
239 |
+
class ImageCmsProfile:
|
240 |
+
def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
|
241 |
+
"""
|
242 |
+
:param profile: Either a string representing a filename,
|
243 |
+
a file like object containing a profile or a
|
244 |
+
low-level profile object
|
245 |
+
|
246 |
+
"""
|
247 |
+
|
248 |
+
if isinstance(profile, str):
|
249 |
+
if sys.platform == "win32":
|
250 |
+
profile_bytes_path = profile.encode()
|
251 |
+
try:
|
252 |
+
profile_bytes_path.decode("ascii")
|
253 |
+
except UnicodeDecodeError:
|
254 |
+
with open(profile, "rb") as f:
|
255 |
+
self._set(core.profile_frombytes(f.read()))
|
256 |
+
return
|
257 |
+
self._set(core.profile_open(profile), profile)
|
258 |
+
elif hasattr(profile, "read"):
|
259 |
+
self._set(core.profile_frombytes(profile.read()))
|
260 |
+
elif isinstance(profile, core.CmsProfile):
|
261 |
+
self._set(profile)
|
262 |
+
else:
|
263 |
+
msg = "Invalid type for Profile" # type: ignore[unreachable]
|
264 |
+
raise TypeError(msg)
|
265 |
+
|
266 |
+
def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
|
267 |
+
self.profile = profile
|
268 |
+
self.filename = filename
|
269 |
+
self.product_name = None # profile.product_name
|
270 |
+
self.product_info = None # profile.product_info
|
271 |
+
|
272 |
+
def tobytes(self) -> bytes:
|
273 |
+
"""
|
274 |
+
Returns the profile in a format suitable for embedding in
|
275 |
+
saved images.
|
276 |
+
|
277 |
+
:returns: a bytes object containing the ICC profile.
|
278 |
+
"""
|
279 |
+
|
280 |
+
return core.profile_tobytes(self.profile)
|
281 |
+
|
282 |
+
|
283 |
+
class ImageCmsTransform(Image.ImagePointHandler):
|
284 |
+
"""
|
285 |
+
Transform. This can be used with the procedural API, or with the standard
|
286 |
+
:py:func:`~PIL.Image.Image.point` method.
|
287 |
+
|
288 |
+
Will return the output profile in the ``output.info['icc_profile']``.
|
289 |
+
"""
|
290 |
+
|
291 |
+
def __init__(
|
292 |
+
self,
|
293 |
+
input: ImageCmsProfile,
|
294 |
+
output: ImageCmsProfile,
|
295 |
+
input_mode: str,
|
296 |
+
output_mode: str,
|
297 |
+
intent: Intent = Intent.PERCEPTUAL,
|
298 |
+
proof: ImageCmsProfile | None = None,
|
299 |
+
proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
300 |
+
flags: Flags = Flags.NONE,
|
301 |
+
):
|
302 |
+
supported_modes = (
|
303 |
+
"RGB",
|
304 |
+
"RGBA",
|
305 |
+
"RGBX",
|
306 |
+
"CMYK",
|
307 |
+
"I;16",
|
308 |
+
"I;16L",
|
309 |
+
"I;16B",
|
310 |
+
"YCbCr",
|
311 |
+
"LAB",
|
312 |
+
"L",
|
313 |
+
"1",
|
314 |
+
)
|
315 |
+
for mode in (input_mode, output_mode):
|
316 |
+
if mode not in supported_modes:
|
317 |
+
deprecate(
|
318 |
+
mode,
|
319 |
+
12,
|
320 |
+
{
|
321 |
+
"L;16": "I;16 or I;16L",
|
322 |
+
"L:16B": "I;16B",
|
323 |
+
"YCCA": "YCbCr",
|
324 |
+
"YCC": "YCbCr",
|
325 |
+
}.get(mode),
|
326 |
+
)
|
327 |
+
if proof is None:
|
328 |
+
self.transform = core.buildTransform(
|
329 |
+
input.profile, output.profile, input_mode, output_mode, intent, flags
|
330 |
+
)
|
331 |
+
else:
|
332 |
+
self.transform = core.buildProofTransform(
|
333 |
+
input.profile,
|
334 |
+
output.profile,
|
335 |
+
proof.profile,
|
336 |
+
input_mode,
|
337 |
+
output_mode,
|
338 |
+
intent,
|
339 |
+
proof_intent,
|
340 |
+
flags,
|
341 |
+
)
|
342 |
+
# Note: inputMode and outputMode are for pyCMS compatibility only
|
343 |
+
self.input_mode = self.inputMode = input_mode
|
344 |
+
self.output_mode = self.outputMode = output_mode
|
345 |
+
|
346 |
+
self.output_profile = output
|
347 |
+
|
348 |
+
def point(self, im: Image.Image) -> Image.Image:
|
349 |
+
return self.apply(im)
|
350 |
+
|
351 |
+
def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
|
352 |
+
im.load()
|
353 |
+
if imOut is None:
|
354 |
+
imOut = Image.new(self.output_mode, im.size, None)
|
355 |
+
self.transform.apply(im.im.id, imOut.im.id)
|
356 |
+
imOut.info["icc_profile"] = self.output_profile.tobytes()
|
357 |
+
return imOut
|
358 |
+
|
359 |
+
def apply_in_place(self, im: Image.Image) -> Image.Image:
|
360 |
+
im.load()
|
361 |
+
if im.mode != self.output_mode:
|
362 |
+
msg = "mode mismatch"
|
363 |
+
raise ValueError(msg) # wrong output mode
|
364 |
+
self.transform.apply(im.im.id, im.im.id)
|
365 |
+
im.info["icc_profile"] = self.output_profile.tobytes()
|
366 |
+
return im
|
367 |
+
|
368 |
+
|
369 |
+
def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
|
370 |
+
"""
|
371 |
+
(experimental) Fetches the profile for the current display device.
|
372 |
+
|
373 |
+
:returns: ``None`` if the profile is not known.
|
374 |
+
"""
|
375 |
+
|
376 |
+
if sys.platform != "win32":
|
377 |
+
return None
|
378 |
+
|
379 |
+
from . import ImageWin # type: ignore[unused-ignore, unreachable]
|
380 |
+
|
381 |
+
if isinstance(handle, ImageWin.HDC):
|
382 |
+
profile = core.get_display_profile_win32(int(handle), 1)
|
383 |
+
else:
|
384 |
+
profile = core.get_display_profile_win32(int(handle or 0))
|
385 |
+
if profile is None:
|
386 |
+
return None
|
387 |
+
return ImageCmsProfile(profile)
|
388 |
+
|
389 |
+
|
390 |
+
# --------------------------------------------------------------------.
|
391 |
+
# pyCMS compatible layer
|
392 |
+
# --------------------------------------------------------------------.
|
393 |
+
|
394 |
+
_CmsProfileCompatible = Union[
|
395 |
+
str, SupportsRead[bytes], core.CmsProfile, ImageCmsProfile
|
396 |
+
]
|
397 |
+
|
398 |
+
|
399 |
+
class PyCMSError(Exception):
|
400 |
+
"""(pyCMS) Exception class.
|
401 |
+
This is used for all errors in the pyCMS API."""
|
402 |
+
|
403 |
+
pass
|
404 |
+
|
405 |
+
|
406 |
+
def profileToProfile(
|
407 |
+
im: Image.Image,
|
408 |
+
inputProfile: _CmsProfileCompatible,
|
409 |
+
outputProfile: _CmsProfileCompatible,
|
410 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
411 |
+
outputMode: str | None = None,
|
412 |
+
inPlace: bool = False,
|
413 |
+
flags: Flags = Flags.NONE,
|
414 |
+
) -> Image.Image | None:
|
415 |
+
"""
|
416 |
+
(pyCMS) Applies an ICC transformation to a given image, mapping from
|
417 |
+
``inputProfile`` to ``outputProfile``.
|
418 |
+
|
419 |
+
If the input or output profiles specified are not valid filenames, a
|
420 |
+
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
|
421 |
+
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
|
422 |
+
If an error occurs during application of the profiles,
|
423 |
+
a :exc:`PyCMSError` will be raised.
|
424 |
+
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
|
425 |
+
a :exc:`PyCMSError` will be raised.
|
426 |
+
|
427 |
+
This function applies an ICC transformation to im from ``inputProfile``'s
|
428 |
+
color space to ``outputProfile``'s color space using the specified rendering
|
429 |
+
intent to decide how to handle out-of-gamut colors.
|
430 |
+
|
431 |
+
``outputMode`` can be used to specify that a color mode conversion is to
|
432 |
+
be done using these profiles, but the specified profiles must be able
|
433 |
+
to handle that mode. I.e., if converting im from RGB to CMYK using
|
434 |
+
profiles, the input profile must handle RGB data, and the output
|
435 |
+
profile must handle CMYK data.
|
436 |
+
|
437 |
+
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
|
438 |
+
or Image.open(...), etc.)
|
439 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
440 |
+
profile you wish to use for this image, or a profile object
|
441 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
442 |
+
profile you wish to use for this image, or a profile object
|
443 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
444 |
+
wish to use for the transform
|
445 |
+
|
446 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
447 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
448 |
+
ImageCms.Intent.SATURATION = 2
|
449 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
450 |
+
|
451 |
+
see the pyCMS documentation for details on rendering intents and what
|
452 |
+
they do.
|
453 |
+
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
|
454 |
+
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
|
455 |
+
MUST be the same mode as the input, or omitted completely. If
|
456 |
+
omitted, the outputMode will be the same as the mode of the input
|
457 |
+
image (im.mode)
|
458 |
+
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
|
459 |
+
and ``None`` is returned. If ``False`` (default), a new
|
460 |
+
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
|
461 |
+
:param flags: Integer (0-...) specifying additional flags
|
462 |
+
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
|
463 |
+
the value of ``inPlace``
|
464 |
+
:exception PyCMSError:
|
465 |
+
"""
|
466 |
+
|
467 |
+
if outputMode is None:
|
468 |
+
outputMode = im.mode
|
469 |
+
|
470 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
471 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
472 |
+
raise PyCMSError(msg)
|
473 |
+
|
474 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
475 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
476 |
+
raise PyCMSError(msg)
|
477 |
+
|
478 |
+
try:
|
479 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
480 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
481 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
482 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
483 |
+
transform = ImageCmsTransform(
|
484 |
+
inputProfile,
|
485 |
+
outputProfile,
|
486 |
+
im.mode,
|
487 |
+
outputMode,
|
488 |
+
renderingIntent,
|
489 |
+
flags=flags,
|
490 |
+
)
|
491 |
+
if inPlace:
|
492 |
+
transform.apply_in_place(im)
|
493 |
+
imOut = None
|
494 |
+
else:
|
495 |
+
imOut = transform.apply(im)
|
496 |
+
except (OSError, TypeError, ValueError) as v:
|
497 |
+
raise PyCMSError(v) from v
|
498 |
+
|
499 |
+
return imOut
|
500 |
+
|
501 |
+
|
502 |
+
def getOpenProfile(
|
503 |
+
profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
|
504 |
+
) -> ImageCmsProfile:
|
505 |
+
"""
|
506 |
+
(pyCMS) Opens an ICC profile file.
|
507 |
+
|
508 |
+
The PyCMSProfile object can be passed back into pyCMS for use in creating
|
509 |
+
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
|
510 |
+
|
511 |
+
If ``profileFilename`` is not a valid filename for an ICC profile,
|
512 |
+
a :exc:`PyCMSError` will be raised.
|
513 |
+
|
514 |
+
:param profileFilename: String, as a valid filename path to the ICC profile
|
515 |
+
you wish to open, or a file-like object.
|
516 |
+
:returns: A CmsProfile class object.
|
517 |
+
:exception PyCMSError:
|
518 |
+
"""
|
519 |
+
|
520 |
+
try:
|
521 |
+
return ImageCmsProfile(profileFilename)
|
522 |
+
except (OSError, TypeError, ValueError) as v:
|
523 |
+
raise PyCMSError(v) from v
|
524 |
+
|
525 |
+
|
526 |
+
def buildTransform(
|
527 |
+
inputProfile: _CmsProfileCompatible,
|
528 |
+
outputProfile: _CmsProfileCompatible,
|
529 |
+
inMode: str,
|
530 |
+
outMode: str,
|
531 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
532 |
+
flags: Flags = Flags.NONE,
|
533 |
+
) -> ImageCmsTransform:
|
534 |
+
"""
|
535 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
536 |
+
``outputProfile``. Use applyTransform to apply the transform to a given
|
537 |
+
image.
|
538 |
+
|
539 |
+
If the input or output profiles specified are not valid filenames, a
|
540 |
+
:exc:`PyCMSError` will be raised. If an error occurs during creation
|
541 |
+
of the transform, a :exc:`PyCMSError` will be raised.
|
542 |
+
|
543 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
544 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
545 |
+
|
546 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
547 |
+
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
|
548 |
+
with out-of-gamut colors. It will ONLY work for converting images that
|
549 |
+
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
|
550 |
+
i.e. "RGB", "RGBA", "CMYK", etc.).
|
551 |
+
|
552 |
+
Building the transform is a fair part of the overhead in
|
553 |
+
ImageCms.profileToProfile(), so if you're planning on converting multiple
|
554 |
+
images using the same input/output settings, this can save you time.
|
555 |
+
Once you have a transform object, it can be used with
|
556 |
+
ImageCms.applyProfile() to convert images without the need to re-compute
|
557 |
+
the lookup table for the transform.
|
558 |
+
|
559 |
+
The reason pyCMS returns a class object rather than a handle directly
|
560 |
+
to the transform is that it needs to keep track of the PIL input/output
|
561 |
+
modes that the transform is meant for. These attributes are stored in
|
562 |
+
the ``inMode`` and ``outMode`` attributes of the object (which can be
|
563 |
+
manually overridden if you really want to, but I don't know of any
|
564 |
+
time that would be of use, or would even work).
|
565 |
+
|
566 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
567 |
+
profile you wish to use for this transform, or a profile object
|
568 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
569 |
+
profile you wish to use for this transform, or a profile object
|
570 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
571 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
572 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
573 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
574 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
575 |
+
wish to use for the transform
|
576 |
+
|
577 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
578 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
579 |
+
ImageCms.Intent.SATURATION = 2
|
580 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
581 |
+
|
582 |
+
see the pyCMS documentation for details on rendering intents and what
|
583 |
+
they do.
|
584 |
+
:param flags: Integer (0-...) specifying additional flags
|
585 |
+
:returns: A CmsTransform class object.
|
586 |
+
:exception PyCMSError:
|
587 |
+
"""
|
588 |
+
|
589 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
590 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
591 |
+
raise PyCMSError(msg)
|
592 |
+
|
593 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
594 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
595 |
+
raise PyCMSError(msg)
|
596 |
+
|
597 |
+
try:
|
598 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
599 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
600 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
601 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
602 |
+
return ImageCmsTransform(
|
603 |
+
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
|
604 |
+
)
|
605 |
+
except (OSError, TypeError, ValueError) as v:
|
606 |
+
raise PyCMSError(v) from v
|
607 |
+
|
608 |
+
|
609 |
+
def buildProofTransform(
|
610 |
+
inputProfile: _CmsProfileCompatible,
|
611 |
+
outputProfile: _CmsProfileCompatible,
|
612 |
+
proofProfile: _CmsProfileCompatible,
|
613 |
+
inMode: str,
|
614 |
+
outMode: str,
|
615 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
616 |
+
proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
617 |
+
flags: Flags = Flags.SOFTPROOFING,
|
618 |
+
) -> ImageCmsTransform:
|
619 |
+
"""
|
620 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
621 |
+
``outputProfile``, but tries to simulate the result that would be
|
622 |
+
obtained on the ``proofProfile`` device.
|
623 |
+
|
624 |
+
If the input, output, or proof profiles specified are not valid
|
625 |
+
filenames, a :exc:`PyCMSError` will be raised.
|
626 |
+
|
627 |
+
If an error occurs during creation of the transform,
|
628 |
+
a :exc:`PyCMSError` will be raised.
|
629 |
+
|
630 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
631 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
632 |
+
|
633 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
634 |
+
to the ``outputProfile``, but tries to simulate the result that would be
|
635 |
+
obtained on the ``proofProfile`` device using ``renderingIntent`` and
|
636 |
+
``proofRenderingIntent`` to determine what to do with out-of-gamut
|
637 |
+
colors. This is known as "soft-proofing". It will ONLY work for
|
638 |
+
converting images that are in ``inMode`` to images that are in outMode
|
639 |
+
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
|
640 |
+
|
641 |
+
Usage of the resulting transform object is exactly the same as with
|
642 |
+
ImageCms.buildTransform().
|
643 |
+
|
644 |
+
Proof profiling is generally used when using an output device to get a
|
645 |
+
good idea of what the final printed/displayed image would look like on
|
646 |
+
the ``proofProfile`` device when it's quicker and easier to use the
|
647 |
+
output device for judging color. Generally, this means that the
|
648 |
+
output device is a monitor, or a dye-sub printer (etc.), and the simulated
|
649 |
+
device is something more expensive, complicated, or time consuming
|
650 |
+
(making it difficult to make a real print for color judgement purposes).
|
651 |
+
|
652 |
+
Soft-proofing basically functions by adjusting the colors on the
|
653 |
+
output device to match the colors of the device being simulated. However,
|
654 |
+
when the simulated device has a much wider gamut than the output
|
655 |
+
device, you may obtain marginal results.
|
656 |
+
|
657 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
658 |
+
profile you wish to use for this transform, or a profile object
|
659 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
660 |
+
(monitor, usually) profile you wish to use for this transform, or a
|
661 |
+
profile object
|
662 |
+
:param proofProfile: String, as a valid filename path to the ICC proof
|
663 |
+
profile you wish to use for this transform, or a profile object
|
664 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
665 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
666 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
667 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
668 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
669 |
+
wish to use for the input->proof (simulated) transform
|
670 |
+
|
671 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
672 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
673 |
+
ImageCms.Intent.SATURATION = 2
|
674 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
675 |
+
|
676 |
+
see the pyCMS documentation for details on rendering intents and what
|
677 |
+
they do.
|
678 |
+
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
|
679 |
+
you wish to use for proof->output transform
|
680 |
+
|
681 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
682 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
683 |
+
ImageCms.Intent.SATURATION = 2
|
684 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
685 |
+
|
686 |
+
see the pyCMS documentation for details on rendering intents and what
|
687 |
+
they do.
|
688 |
+
:param flags: Integer (0-...) specifying additional flags
|
689 |
+
:returns: A CmsTransform class object.
|
690 |
+
:exception PyCMSError:
|
691 |
+
"""
|
692 |
+
|
693 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
694 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
695 |
+
raise PyCMSError(msg)
|
696 |
+
|
697 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
698 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
699 |
+
raise PyCMSError(msg)
|
700 |
+
|
701 |
+
try:
|
702 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
703 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
704 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
705 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
706 |
+
if not isinstance(proofProfile, ImageCmsProfile):
|
707 |
+
proofProfile = ImageCmsProfile(proofProfile)
|
708 |
+
return ImageCmsTransform(
|
709 |
+
inputProfile,
|
710 |
+
outputProfile,
|
711 |
+
inMode,
|
712 |
+
outMode,
|
713 |
+
renderingIntent,
|
714 |
+
proofProfile,
|
715 |
+
proofRenderingIntent,
|
716 |
+
flags,
|
717 |
+
)
|
718 |
+
except (OSError, TypeError, ValueError) as v:
|
719 |
+
raise PyCMSError(v) from v
|
720 |
+
|
721 |
+
|
722 |
+
buildTransformFromOpenProfiles = buildTransform
|
723 |
+
buildProofTransformFromOpenProfiles = buildProofTransform
|
724 |
+
|
725 |
+
|
726 |
+
def applyTransform(
|
727 |
+
im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
|
728 |
+
) -> Image.Image | None:
|
729 |
+
"""
|
730 |
+
(pyCMS) Applies a transform to a given image.
|
731 |
+
|
732 |
+
If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
|
733 |
+
|
734 |
+
If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
|
735 |
+
:exc:`PyCMSError` is raised.
|
736 |
+
|
737 |
+
If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
|
738 |
+
supported by pyCMSdll or the profiles you used for the transform, a
|
739 |
+
:exc:`PyCMSError` is raised.
|
740 |
+
|
741 |
+
If an error occurs while the transform is being applied,
|
742 |
+
a :exc:`PyCMSError` is raised.
|
743 |
+
|
744 |
+
This function applies a pre-calculated transform (from
|
745 |
+
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
|
746 |
+
to an image. The transform can be used for multiple images, saving
|
747 |
+
considerable calculation time if doing the same conversion multiple times.
|
748 |
+
|
749 |
+
If you want to modify im in-place instead of receiving a new image as
|
750 |
+
the return value, set ``inPlace`` to ``True``. This can only be done if
|
751 |
+
``transform.input_mode`` and ``transform.output_mode`` are the same, because we
|
752 |
+
can't change the mode in-place (the buffer sizes for some modes are
|
753 |
+
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
|
754 |
+
object of the same dimensions in mode ``transform.output_mode``.
|
755 |
+
|
756 |
+
:param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
|
757 |
+
as the ``input_mode`` supported by the transform.
|
758 |
+
:param transform: A valid CmsTransform class object
|
759 |
+
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
|
760 |
+
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
|
761 |
+
transform applied is returned (and ``im`` is not changed). The default is
|
762 |
+
``False``.
|
763 |
+
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
|
764 |
+
depending on the value of ``inPlace``. The profile will be returned in
|
765 |
+
the image's ``info['icc_profile']``.
|
766 |
+
:exception PyCMSError:
|
767 |
+
"""
|
768 |
+
|
769 |
+
try:
|
770 |
+
if inPlace:
|
771 |
+
transform.apply_in_place(im)
|
772 |
+
imOut = None
|
773 |
+
else:
|
774 |
+
imOut = transform.apply(im)
|
775 |
+
except (TypeError, ValueError) as v:
|
776 |
+
raise PyCMSError(v) from v
|
777 |
+
|
778 |
+
return imOut
|
779 |
+
|
780 |
+
|
781 |
+
def createProfile(
|
782 |
+
colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
|
783 |
+
) -> core.CmsProfile:
|
784 |
+
"""
|
785 |
+
(pyCMS) Creates a profile.
|
786 |
+
|
787 |
+
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
|
788 |
+
a :exc:`PyCMSError` is raised.
|
789 |
+
|
790 |
+
If using LAB and ``colorTemp`` is not a positive integer,
|
791 |
+
a :exc:`PyCMSError` is raised.
|
792 |
+
|
793 |
+
If an error occurs while creating the profile,
|
794 |
+
a :exc:`PyCMSError` is raised.
|
795 |
+
|
796 |
+
Use this function to create common profiles on-the-fly instead of
|
797 |
+
having to supply a profile on disk and knowing the path to it. It
|
798 |
+
returns a normal CmsProfile object that can be passed to
|
799 |
+
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
|
800 |
+
to images.
|
801 |
+
|
802 |
+
:param colorSpace: String, the color space of the profile you wish to
|
803 |
+
create.
|
804 |
+
Currently only "LAB", "XYZ", and "sRGB" are supported.
|
805 |
+
:param colorTemp: Positive number for the white point for the profile, in
|
806 |
+
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
|
807 |
+
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
|
808 |
+
profiles, and is ignored for XYZ and sRGB.
|
809 |
+
:returns: A CmsProfile class object
|
810 |
+
:exception PyCMSError:
|
811 |
+
"""
|
812 |
+
|
813 |
+
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
|
814 |
+
msg = (
|
815 |
+
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
|
816 |
+
)
|
817 |
+
raise PyCMSError(msg)
|
818 |
+
|
819 |
+
if colorSpace == "LAB":
|
820 |
+
try:
|
821 |
+
colorTemp = float(colorTemp)
|
822 |
+
except (TypeError, ValueError) as e:
|
823 |
+
msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
|
824 |
+
raise PyCMSError(msg) from e
|
825 |
+
|
826 |
+
try:
|
827 |
+
return core.createProfile(colorSpace, colorTemp)
|
828 |
+
except (TypeError, ValueError) as v:
|
829 |
+
raise PyCMSError(v) from v
|
830 |
+
|
831 |
+
|
832 |
+
def getProfileName(profile: _CmsProfileCompatible) -> str:
|
833 |
+
"""
|
834 |
+
|
835 |
+
(pyCMS) Gets the internal product name for the given profile.
|
836 |
+
|
837 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
838 |
+
a :exc:`PyCMSError` is raised If an error occurs while trying
|
839 |
+
to obtain the name tag, a :exc:`PyCMSError` is raised.
|
840 |
+
|
841 |
+
Use this function to obtain the INTERNAL name of the profile (stored
|
842 |
+
in an ICC tag in the profile itself), usually the one used when the
|
843 |
+
profile was originally created. Sometimes this tag also contains
|
844 |
+
additional information supplied by the creator.
|
845 |
+
|
846 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
847 |
+
filename of an ICC profile.
|
848 |
+
:returns: A string containing the internal name of the profile as stored
|
849 |
+
in an ICC tag.
|
850 |
+
:exception PyCMSError:
|
851 |
+
"""
|
852 |
+
|
853 |
+
try:
|
854 |
+
# add an extra newline to preserve pyCMS compatibility
|
855 |
+
if not isinstance(profile, ImageCmsProfile):
|
856 |
+
profile = ImageCmsProfile(profile)
|
857 |
+
# do it in python, not c.
|
858 |
+
# // name was "%s - %s" (model, manufacturer) || Description ,
|
859 |
+
# // but if the Model and Manufacturer were the same or the model
|
860 |
+
# // was long, Just the model, in 1.x
|
861 |
+
model = profile.profile.model
|
862 |
+
manufacturer = profile.profile.manufacturer
|
863 |
+
|
864 |
+
if not (model or manufacturer):
|
865 |
+
return (profile.profile.profile_description or "") + "\n"
|
866 |
+
if not manufacturer or (model and len(model) > 30):
|
867 |
+
return f"{model}\n"
|
868 |
+
return f"{model} - {manufacturer}\n"
|
869 |
+
|
870 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
871 |
+
raise PyCMSError(v) from v
|
872 |
+
|
873 |
+
|
874 |
+
def getProfileInfo(profile: _CmsProfileCompatible) -> str:
|
875 |
+
"""
|
876 |
+
(pyCMS) Gets the internal product information for the given profile.
|
877 |
+
|
878 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
879 |
+
a :exc:`PyCMSError` is raised.
|
880 |
+
|
881 |
+
If an error occurs while trying to obtain the info tag,
|
882 |
+
a :exc:`PyCMSError` is raised.
|
883 |
+
|
884 |
+
Use this function to obtain the information stored in the profile's
|
885 |
+
info tag. This often contains details about the profile, and how it
|
886 |
+
was created, as supplied by the creator.
|
887 |
+
|
888 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
889 |
+
filename of an ICC profile.
|
890 |
+
:returns: A string containing the internal profile information stored in
|
891 |
+
an ICC tag.
|
892 |
+
:exception PyCMSError:
|
893 |
+
"""
|
894 |
+
|
895 |
+
try:
|
896 |
+
if not isinstance(profile, ImageCmsProfile):
|
897 |
+
profile = ImageCmsProfile(profile)
|
898 |
+
# add an extra newline to preserve pyCMS compatibility
|
899 |
+
# Python, not C. the white point bits weren't working well,
|
900 |
+
# so skipping.
|
901 |
+
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
|
902 |
+
description = profile.profile.profile_description
|
903 |
+
cpright = profile.profile.copyright
|
904 |
+
elements = [element for element in (description, cpright) if element]
|
905 |
+
return "\r\n\r\n".join(elements) + "\r\n\r\n"
|
906 |
+
|
907 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
908 |
+
raise PyCMSError(v) from v
|
909 |
+
|
910 |
+
|
911 |
+
def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
|
912 |
+
"""
|
913 |
+
(pyCMS) Gets the copyright for the given profile.
|
914 |
+
|
915 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
916 |
+
:exc:`PyCMSError` is raised.
|
917 |
+
|
918 |
+
If an error occurs while trying to obtain the copyright tag,
|
919 |
+
a :exc:`PyCMSError` is raised.
|
920 |
+
|
921 |
+
Use this function to obtain the information stored in the profile's
|
922 |
+
copyright tag.
|
923 |
+
|
924 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
925 |
+
filename of an ICC profile.
|
926 |
+
:returns: A string containing the internal profile information stored in
|
927 |
+
an ICC tag.
|
928 |
+
:exception PyCMSError:
|
929 |
+
"""
|
930 |
+
try:
|
931 |
+
# add an extra newline to preserve pyCMS compatibility
|
932 |
+
if not isinstance(profile, ImageCmsProfile):
|
933 |
+
profile = ImageCmsProfile(profile)
|
934 |
+
return (profile.profile.copyright or "") + "\n"
|
935 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
936 |
+
raise PyCMSError(v) from v
|
937 |
+
|
938 |
+
|
939 |
+
def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
|
940 |
+
"""
|
941 |
+
(pyCMS) Gets the manufacturer for the given profile.
|
942 |
+
|
943 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
944 |
+
:exc:`PyCMSError` is raised.
|
945 |
+
|
946 |
+
If an error occurs while trying to obtain the manufacturer tag, a
|
947 |
+
:exc:`PyCMSError` is raised.
|
948 |
+
|
949 |
+
Use this function to obtain the information stored in the profile's
|
950 |
+
manufacturer tag.
|
951 |
+
|
952 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
953 |
+
filename of an ICC profile.
|
954 |
+
:returns: A string containing the internal profile information stored in
|
955 |
+
an ICC tag.
|
956 |
+
:exception PyCMSError:
|
957 |
+
"""
|
958 |
+
try:
|
959 |
+
# add an extra newline to preserve pyCMS compatibility
|
960 |
+
if not isinstance(profile, ImageCmsProfile):
|
961 |
+
profile = ImageCmsProfile(profile)
|
962 |
+
return (profile.profile.manufacturer or "") + "\n"
|
963 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
964 |
+
raise PyCMSError(v) from v
|
965 |
+
|
966 |
+
|
967 |
+
def getProfileModel(profile: _CmsProfileCompatible) -> str:
|
968 |
+
"""
|
969 |
+
(pyCMS) Gets the model for the given profile.
|
970 |
+
|
971 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
972 |
+
:exc:`PyCMSError` is raised.
|
973 |
+
|
974 |
+
If an error occurs while trying to obtain the model tag,
|
975 |
+
a :exc:`PyCMSError` is raised.
|
976 |
+
|
977 |
+
Use this function to obtain the information stored in the profile's
|
978 |
+
model tag.
|
979 |
+
|
980 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
981 |
+
filename of an ICC profile.
|
982 |
+
:returns: A string containing the internal profile information stored in
|
983 |
+
an ICC tag.
|
984 |
+
:exception PyCMSError:
|
985 |
+
"""
|
986 |
+
|
987 |
+
try:
|
988 |
+
# add an extra newline to preserve pyCMS compatibility
|
989 |
+
if not isinstance(profile, ImageCmsProfile):
|
990 |
+
profile = ImageCmsProfile(profile)
|
991 |
+
return (profile.profile.model or "") + "\n"
|
992 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
993 |
+
raise PyCMSError(v) from v
|
994 |
+
|
995 |
+
|
996 |
+
def getProfileDescription(profile: _CmsProfileCompatible) -> str:
|
997 |
+
"""
|
998 |
+
(pyCMS) Gets the description for the given profile.
|
999 |
+
|
1000 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
1001 |
+
:exc:`PyCMSError` is raised.
|
1002 |
+
|
1003 |
+
If an error occurs while trying to obtain the description tag,
|
1004 |
+
a :exc:`PyCMSError` is raised.
|
1005 |
+
|
1006 |
+
Use this function to obtain the information stored in the profile's
|
1007 |
+
description tag.
|
1008 |
+
|
1009 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
1010 |
+
filename of an ICC profile.
|
1011 |
+
:returns: A string containing the internal profile information stored in an
|
1012 |
+
ICC tag.
|
1013 |
+
:exception PyCMSError:
|
1014 |
+
"""
|
1015 |
+
|
1016 |
+
try:
|
1017 |
+
# add an extra newline to preserve pyCMS compatibility
|
1018 |
+
if not isinstance(profile, ImageCmsProfile):
|
1019 |
+
profile = ImageCmsProfile(profile)
|
1020 |
+
return (profile.profile.profile_description or "") + "\n"
|
1021 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
1022 |
+
raise PyCMSError(v) from v
|
1023 |
+
|
1024 |
+
|
1025 |
+
def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
|
1026 |
+
"""
|
1027 |
+
(pyCMS) Gets the default intent name for the given profile.
|
1028 |
+
|
1029 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
1030 |
+
:exc:`PyCMSError` is raised.
|
1031 |
+
|
1032 |
+
If an error occurs while trying to obtain the default intent, a
|
1033 |
+
:exc:`PyCMSError` is raised.
|
1034 |
+
|
1035 |
+
Use this function to determine the default (and usually best optimized)
|
1036 |
+
rendering intent for this profile. Most profiles support multiple
|
1037 |
+
rendering intents, but are intended mostly for one type of conversion.
|
1038 |
+
If you wish to use a different intent than returned, use
|
1039 |
+
ImageCms.isIntentSupported() to verify it will work first.
|
1040 |
+
|
1041 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
1042 |
+
filename of an ICC profile.
|
1043 |
+
:returns: Integer 0-3 specifying the default rendering intent for this
|
1044 |
+
profile.
|
1045 |
+
|
1046 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
1047 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
1048 |
+
ImageCms.Intent.SATURATION = 2
|
1049 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
1050 |
+
|
1051 |
+
see the pyCMS documentation for details on rendering intents and what
|
1052 |
+
they do.
|
1053 |
+
:exception PyCMSError:
|
1054 |
+
"""
|
1055 |
+
|
1056 |
+
try:
|
1057 |
+
if not isinstance(profile, ImageCmsProfile):
|
1058 |
+
profile = ImageCmsProfile(profile)
|
1059 |
+
return profile.profile.rendering_intent
|
1060 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
1061 |
+
raise PyCMSError(v) from v
|
1062 |
+
|
1063 |
+
|
1064 |
+
def isIntentSupported(
|
1065 |
+
profile: _CmsProfileCompatible, intent: Intent, direction: Direction
|
1066 |
+
) -> Literal[-1, 1]:
|
1067 |
+
"""
|
1068 |
+
(pyCMS) Checks if a given intent is supported.
|
1069 |
+
|
1070 |
+
Use this function to verify that you can use your desired
|
1071 |
+
``intent`` with ``profile``, and that ``profile`` can be used for the
|
1072 |
+
input/output/proof profile as you desire.
|
1073 |
+
|
1074 |
+
Some profiles are created specifically for one "direction", can cannot
|
1075 |
+
be used for others. Some profiles can only be used for certain
|
1076 |
+
rendering intents, so it's best to either verify this before trying
|
1077 |
+
to create a transform with them (using this function), or catch the
|
1078 |
+
potential :exc:`PyCMSError` that will occur if they don't
|
1079 |
+
support the modes you select.
|
1080 |
+
|
1081 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
1082 |
+
filename of an ICC profile.
|
1083 |
+
:param intent: Integer (0-3) specifying the rendering intent you wish to
|
1084 |
+
use with this profile
|
1085 |
+
|
1086 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
1087 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
1088 |
+
ImageCms.Intent.SATURATION = 2
|
1089 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
1090 |
+
|
1091 |
+
see the pyCMS documentation for details on rendering intents and what
|
1092 |
+
they do.
|
1093 |
+
:param direction: Integer specifying if the profile is to be used for
|
1094 |
+
input, output, or proof
|
1095 |
+
|
1096 |
+
INPUT = 0 (or use ImageCms.Direction.INPUT)
|
1097 |
+
OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
|
1098 |
+
PROOF = 2 (or use ImageCms.Direction.PROOF)
|
1099 |
+
|
1100 |
+
:returns: 1 if the intent/direction are supported, -1 if they are not.
|
1101 |
+
:exception PyCMSError:
|
1102 |
+
"""
|
1103 |
+
|
1104 |
+
try:
|
1105 |
+
if not isinstance(profile, ImageCmsProfile):
|
1106 |
+
profile = ImageCmsProfile(profile)
|
1107 |
+
# FIXME: I get different results for the same data w. different
|
1108 |
+
# compilers. Bug in LittleCMS or in the binding?
|
1109 |
+
if profile.profile.is_intent_supported(intent, direction):
|
1110 |
+
return 1
|
1111 |
+
else:
|
1112 |
+
return -1
|
1113 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
1114 |
+
raise PyCMSError(v) from v
|
1115 |
+
|
1116 |
+
|
1117 |
+
def versions() -> tuple[str, str | None, str, str]:
|
1118 |
+
"""
|
1119 |
+
(pyCMS) Fetches versions.
|
1120 |
+
"""
|
1121 |
+
|
1122 |
+
deprecate(
|
1123 |
+
"PIL.ImageCms.versions()",
|
1124 |
+
12,
|
1125 |
+
'(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
|
1126 |
+
)
|
1127 |
+
return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
|
MLPY/Lib/site-packages/PIL/ImageColor.py
ADDED
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# map CSS3-style colour description strings to RGB
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2002-10-24 fl Added support for CSS-style color strings
|
9 |
+
# 2002-12-15 fl Added RGBA support
|
10 |
+
# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
|
11 |
+
# 2004-07-19 fl Fixed gray/grey spelling issues
|
12 |
+
# 2009-03-05 fl Fixed rounding error in grayscale calculation
|
13 |
+
#
|
14 |
+
# Copyright (c) 2002-2004 by Secret Labs AB
|
15 |
+
# Copyright (c) 2002-2004 by Fredrik Lundh
|
16 |
+
#
|
17 |
+
# See the README file for information on usage and redistribution.
|
18 |
+
#
|
19 |
+
from __future__ import annotations
|
20 |
+
|
21 |
+
import re
|
22 |
+
from functools import lru_cache
|
23 |
+
|
24 |
+
from . import Image
|
25 |
+
|
26 |
+
|
27 |
+
@lru_cache
|
28 |
+
def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
|
29 |
+
"""
|
30 |
+
Convert a color string to an RGB or RGBA tuple. If the string cannot be
|
31 |
+
parsed, this function raises a :py:exc:`ValueError` exception.
|
32 |
+
|
33 |
+
.. versionadded:: 1.1.4
|
34 |
+
|
35 |
+
:param color: A color string
|
36 |
+
:return: ``(red, green, blue[, alpha])``
|
37 |
+
"""
|
38 |
+
if len(color) > 100:
|
39 |
+
msg = "color specifier is too long"
|
40 |
+
raise ValueError(msg)
|
41 |
+
color = color.lower()
|
42 |
+
|
43 |
+
rgb = colormap.get(color, None)
|
44 |
+
if rgb:
|
45 |
+
if isinstance(rgb, tuple):
|
46 |
+
return rgb
|
47 |
+
rgb_tuple = getrgb(rgb)
|
48 |
+
assert len(rgb_tuple) == 3
|
49 |
+
colormap[color] = rgb_tuple
|
50 |
+
return rgb_tuple
|
51 |
+
|
52 |
+
# check for known string formats
|
53 |
+
if re.match("#[a-f0-9]{3}$", color):
|
54 |
+
return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
|
55 |
+
|
56 |
+
if re.match("#[a-f0-9]{4}$", color):
|
57 |
+
return (
|
58 |
+
int(color[1] * 2, 16),
|
59 |
+
int(color[2] * 2, 16),
|
60 |
+
int(color[3] * 2, 16),
|
61 |
+
int(color[4] * 2, 16),
|
62 |
+
)
|
63 |
+
|
64 |
+
if re.match("#[a-f0-9]{6}$", color):
|
65 |
+
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
|
66 |
+
|
67 |
+
if re.match("#[a-f0-9]{8}$", color):
|
68 |
+
return (
|
69 |
+
int(color[1:3], 16),
|
70 |
+
int(color[3:5], 16),
|
71 |
+
int(color[5:7], 16),
|
72 |
+
int(color[7:9], 16),
|
73 |
+
)
|
74 |
+
|
75 |
+
m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
76 |
+
if m:
|
77 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3))
|
78 |
+
|
79 |
+
m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
|
80 |
+
if m:
|
81 |
+
return (
|
82 |
+
int((int(m.group(1)) * 255) / 100.0 + 0.5),
|
83 |
+
int((int(m.group(2)) * 255) / 100.0 + 0.5),
|
84 |
+
int((int(m.group(3)) * 255) / 100.0 + 0.5),
|
85 |
+
)
|
86 |
+
|
87 |
+
m = re.match(
|
88 |
+
r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
89 |
+
)
|
90 |
+
if m:
|
91 |
+
from colorsys import hls_to_rgb
|
92 |
+
|
93 |
+
rgb_floats = hls_to_rgb(
|
94 |
+
float(m.group(1)) / 360.0,
|
95 |
+
float(m.group(3)) / 100.0,
|
96 |
+
float(m.group(2)) / 100.0,
|
97 |
+
)
|
98 |
+
return (
|
99 |
+
int(rgb_floats[0] * 255 + 0.5),
|
100 |
+
int(rgb_floats[1] * 255 + 0.5),
|
101 |
+
int(rgb_floats[2] * 255 + 0.5),
|
102 |
+
)
|
103 |
+
|
104 |
+
m = re.match(
|
105 |
+
r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
106 |
+
)
|
107 |
+
if m:
|
108 |
+
from colorsys import hsv_to_rgb
|
109 |
+
|
110 |
+
rgb_floats = hsv_to_rgb(
|
111 |
+
float(m.group(1)) / 360.0,
|
112 |
+
float(m.group(2)) / 100.0,
|
113 |
+
float(m.group(3)) / 100.0,
|
114 |
+
)
|
115 |
+
return (
|
116 |
+
int(rgb_floats[0] * 255 + 0.5),
|
117 |
+
int(rgb_floats[1] * 255 + 0.5),
|
118 |
+
int(rgb_floats[2] * 255 + 0.5),
|
119 |
+
)
|
120 |
+
|
121 |
+
m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
122 |
+
if m:
|
123 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
|
124 |
+
msg = f"unknown color specifier: {repr(color)}"
|
125 |
+
raise ValueError(msg)
|
126 |
+
|
127 |
+
|
128 |
+
@lru_cache
|
129 |
+
def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
|
130 |
+
"""
|
131 |
+
Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
|
132 |
+
``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
|
133 |
+
not color or a palette image, converts the RGB value to a grayscale value.
|
134 |
+
If the string cannot be parsed, this function raises a :py:exc:`ValueError`
|
135 |
+
exception.
|
136 |
+
|
137 |
+
.. versionadded:: 1.1.4
|
138 |
+
|
139 |
+
:param color: A color string
|
140 |
+
:param mode: Convert result to this mode
|
141 |
+
:return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
|
142 |
+
"""
|
143 |
+
# same as getrgb, but converts the result to the given mode
|
144 |
+
rgb, alpha = getrgb(color), 255
|
145 |
+
if len(rgb) == 4:
|
146 |
+
alpha = rgb[3]
|
147 |
+
rgb = rgb[:3]
|
148 |
+
|
149 |
+
if mode == "HSV":
|
150 |
+
from colorsys import rgb_to_hsv
|
151 |
+
|
152 |
+
r, g, b = rgb
|
153 |
+
h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
|
154 |
+
return int(h * 255), int(s * 255), int(v * 255)
|
155 |
+
elif Image.getmodebase(mode) == "L":
|
156 |
+
r, g, b = rgb
|
157 |
+
# ITU-R Recommendation 601-2 for nonlinear RGB
|
158 |
+
# scaled to 24 bits to match the convert's implementation.
|
159 |
+
graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
|
160 |
+
if mode[-1] == "A":
|
161 |
+
return graylevel, alpha
|
162 |
+
return graylevel
|
163 |
+
elif mode[-1] == "A":
|
164 |
+
return rgb + (alpha,)
|
165 |
+
return rgb
|
166 |
+
|
167 |
+
|
168 |
+
colormap: dict[str, str | tuple[int, int, int]] = {
|
169 |
+
# X11 colour table from https://drafts.csswg.org/css-color-4/, with
|
170 |
+
# gray/grey spelling issues fixed. This is a superset of HTML 4.0
|
171 |
+
# colour names used in CSS 1.
|
172 |
+
"aliceblue": "#f0f8ff",
|
173 |
+
"antiquewhite": "#faebd7",
|
174 |
+
"aqua": "#00ffff",
|
175 |
+
"aquamarine": "#7fffd4",
|
176 |
+
"azure": "#f0ffff",
|
177 |
+
"beige": "#f5f5dc",
|
178 |
+
"bisque": "#ffe4c4",
|
179 |
+
"black": "#000000",
|
180 |
+
"blanchedalmond": "#ffebcd",
|
181 |
+
"blue": "#0000ff",
|
182 |
+
"blueviolet": "#8a2be2",
|
183 |
+
"brown": "#a52a2a",
|
184 |
+
"burlywood": "#deb887",
|
185 |
+
"cadetblue": "#5f9ea0",
|
186 |
+
"chartreuse": "#7fff00",
|
187 |
+
"chocolate": "#d2691e",
|
188 |
+
"coral": "#ff7f50",
|
189 |
+
"cornflowerblue": "#6495ed",
|
190 |
+
"cornsilk": "#fff8dc",
|
191 |
+
"crimson": "#dc143c",
|
192 |
+
"cyan": "#00ffff",
|
193 |
+
"darkblue": "#00008b",
|
194 |
+
"darkcyan": "#008b8b",
|
195 |
+
"darkgoldenrod": "#b8860b",
|
196 |
+
"darkgray": "#a9a9a9",
|
197 |
+
"darkgrey": "#a9a9a9",
|
198 |
+
"darkgreen": "#006400",
|
199 |
+
"darkkhaki": "#bdb76b",
|
200 |
+
"darkmagenta": "#8b008b",
|
201 |
+
"darkolivegreen": "#556b2f",
|
202 |
+
"darkorange": "#ff8c00",
|
203 |
+
"darkorchid": "#9932cc",
|
204 |
+
"darkred": "#8b0000",
|
205 |
+
"darksalmon": "#e9967a",
|
206 |
+
"darkseagreen": "#8fbc8f",
|
207 |
+
"darkslateblue": "#483d8b",
|
208 |
+
"darkslategray": "#2f4f4f",
|
209 |
+
"darkslategrey": "#2f4f4f",
|
210 |
+
"darkturquoise": "#00ced1",
|
211 |
+
"darkviolet": "#9400d3",
|
212 |
+
"deeppink": "#ff1493",
|
213 |
+
"deepskyblue": "#00bfff",
|
214 |
+
"dimgray": "#696969",
|
215 |
+
"dimgrey": "#696969",
|
216 |
+
"dodgerblue": "#1e90ff",
|
217 |
+
"firebrick": "#b22222",
|
218 |
+
"floralwhite": "#fffaf0",
|
219 |
+
"forestgreen": "#228b22",
|
220 |
+
"fuchsia": "#ff00ff",
|
221 |
+
"gainsboro": "#dcdcdc",
|
222 |
+
"ghostwhite": "#f8f8ff",
|
223 |
+
"gold": "#ffd700",
|
224 |
+
"goldenrod": "#daa520",
|
225 |
+
"gray": "#808080",
|
226 |
+
"grey": "#808080",
|
227 |
+
"green": "#008000",
|
228 |
+
"greenyellow": "#adff2f",
|
229 |
+
"honeydew": "#f0fff0",
|
230 |
+
"hotpink": "#ff69b4",
|
231 |
+
"indianred": "#cd5c5c",
|
232 |
+
"indigo": "#4b0082",
|
233 |
+
"ivory": "#fffff0",
|
234 |
+
"khaki": "#f0e68c",
|
235 |
+
"lavender": "#e6e6fa",
|
236 |
+
"lavenderblush": "#fff0f5",
|
237 |
+
"lawngreen": "#7cfc00",
|
238 |
+
"lemonchiffon": "#fffacd",
|
239 |
+
"lightblue": "#add8e6",
|
240 |
+
"lightcoral": "#f08080",
|
241 |
+
"lightcyan": "#e0ffff",
|
242 |
+
"lightgoldenrodyellow": "#fafad2",
|
243 |
+
"lightgreen": "#90ee90",
|
244 |
+
"lightgray": "#d3d3d3",
|
245 |
+
"lightgrey": "#d3d3d3",
|
246 |
+
"lightpink": "#ffb6c1",
|
247 |
+
"lightsalmon": "#ffa07a",
|
248 |
+
"lightseagreen": "#20b2aa",
|
249 |
+
"lightskyblue": "#87cefa",
|
250 |
+
"lightslategray": "#778899",
|
251 |
+
"lightslategrey": "#778899",
|
252 |
+
"lightsteelblue": "#b0c4de",
|
253 |
+
"lightyellow": "#ffffe0",
|
254 |
+
"lime": "#00ff00",
|
255 |
+
"limegreen": "#32cd32",
|
256 |
+
"linen": "#faf0e6",
|
257 |
+
"magenta": "#ff00ff",
|
258 |
+
"maroon": "#800000",
|
259 |
+
"mediumaquamarine": "#66cdaa",
|
260 |
+
"mediumblue": "#0000cd",
|
261 |
+
"mediumorchid": "#ba55d3",
|
262 |
+
"mediumpurple": "#9370db",
|
263 |
+
"mediumseagreen": "#3cb371",
|
264 |
+
"mediumslateblue": "#7b68ee",
|
265 |
+
"mediumspringgreen": "#00fa9a",
|
266 |
+
"mediumturquoise": "#48d1cc",
|
267 |
+
"mediumvioletred": "#c71585",
|
268 |
+
"midnightblue": "#191970",
|
269 |
+
"mintcream": "#f5fffa",
|
270 |
+
"mistyrose": "#ffe4e1",
|
271 |
+
"moccasin": "#ffe4b5",
|
272 |
+
"navajowhite": "#ffdead",
|
273 |
+
"navy": "#000080",
|
274 |
+
"oldlace": "#fdf5e6",
|
275 |
+
"olive": "#808000",
|
276 |
+
"olivedrab": "#6b8e23",
|
277 |
+
"orange": "#ffa500",
|
278 |
+
"orangered": "#ff4500",
|
279 |
+
"orchid": "#da70d6",
|
280 |
+
"palegoldenrod": "#eee8aa",
|
281 |
+
"palegreen": "#98fb98",
|
282 |
+
"paleturquoise": "#afeeee",
|
283 |
+
"palevioletred": "#db7093",
|
284 |
+
"papayawhip": "#ffefd5",
|
285 |
+
"peachpuff": "#ffdab9",
|
286 |
+
"peru": "#cd853f",
|
287 |
+
"pink": "#ffc0cb",
|
288 |
+
"plum": "#dda0dd",
|
289 |
+
"powderblue": "#b0e0e6",
|
290 |
+
"purple": "#800080",
|
291 |
+
"rebeccapurple": "#663399",
|
292 |
+
"red": "#ff0000",
|
293 |
+
"rosybrown": "#bc8f8f",
|
294 |
+
"royalblue": "#4169e1",
|
295 |
+
"saddlebrown": "#8b4513",
|
296 |
+
"salmon": "#fa8072",
|
297 |
+
"sandybrown": "#f4a460",
|
298 |
+
"seagreen": "#2e8b57",
|
299 |
+
"seashell": "#fff5ee",
|
300 |
+
"sienna": "#a0522d",
|
301 |
+
"silver": "#c0c0c0",
|
302 |
+
"skyblue": "#87ceeb",
|
303 |
+
"slateblue": "#6a5acd",
|
304 |
+
"slategray": "#708090",
|
305 |
+
"slategrey": "#708090",
|
306 |
+
"snow": "#fffafa",
|
307 |
+
"springgreen": "#00ff7f",
|
308 |
+
"steelblue": "#4682b4",
|
309 |
+
"tan": "#d2b48c",
|
310 |
+
"teal": "#008080",
|
311 |
+
"thistle": "#d8bfd8",
|
312 |
+
"tomato": "#ff6347",
|
313 |
+
"turquoise": "#40e0d0",
|
314 |
+
"violet": "#ee82ee",
|
315 |
+
"wheat": "#f5deb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Filled polygons, ellipses.
|
10 |
+
# 1996-08-13 fl Added text support
|
11 |
+
# 1998-06-28 fl Handle I and F images
|
12 |
+
# 1998-12-29 fl Added arc; use arc primitive to draw ellipses
|
13 |
+
# 1999-01-10 fl Added shape stuff (experimental)
|
14 |
+
# 1999-02-06 fl Added bitmap support
|
15 |
+
# 1999-02-11 fl Changed all primitives to take options
|
16 |
+
# 1999-02-20 fl Fixed backwards compatibility
|
17 |
+
# 2000-10-12 fl Copy on write, when necessary
|
18 |
+
# 2001-02-18 fl Use default ink for bitmap/text also in fill mode
|
19 |
+
# 2002-10-24 fl Added support for CSS-style color strings
|
20 |
+
# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
|
21 |
+
# 2002-12-11 fl Refactored low-level drawing API (work in progress)
|
22 |
+
# 2004-08-26 fl Made Draw() a factory function, added getdraw() support
|
23 |
+
# 2004-09-04 fl Added width support to line primitive
|
24 |
+
# 2004-09-10 fl Added font mode handling
|
25 |
+
# 2006-06-19 fl Added font bearing support (getmask2)
|
26 |
+
#
|
27 |
+
# Copyright (c) 1997-2006 by Secret Labs AB
|
28 |
+
# Copyright (c) 1996-2006 by Fredrik Lundh
|
29 |
+
#
|
30 |
+
# See the README file for information on usage and redistribution.
|
31 |
+
#
|
32 |
+
from __future__ import annotations
|
33 |
+
|
34 |
+
import math
|
35 |
+
import numbers
|
36 |
+
import struct
|
37 |
+
from types import ModuleType
|
38 |
+
from typing import TYPE_CHECKING, AnyStr, Callable, List, Sequence, Tuple, Union, cast
|
39 |
+
|
40 |
+
from . import Image, ImageColor
|
41 |
+
from ._deprecate import deprecate
|
42 |
+
from ._typing import Coords
|
43 |
+
|
44 |
+
# experimental access to the outline API
|
45 |
+
Outline: Callable[[], Image.core._Outline] | None
|
46 |
+
try:
|
47 |
+
Outline = Image.core.outline
|
48 |
+
except AttributeError:
|
49 |
+
Outline = None
|
50 |
+
|
51 |
+
if TYPE_CHECKING:
|
52 |
+
from . import ImageDraw2, ImageFont
|
53 |
+
|
54 |
+
_Ink = Union[float, Tuple[int, ...], str]
|
55 |
+
|
56 |
+
"""
|
57 |
+
A simple 2D drawing interface for PIL images.
|
58 |
+
<p>
|
59 |
+
Application code should use the <b>Draw</b> factory, instead of
|
60 |
+
directly.
|
61 |
+
"""
|
62 |
+
|
63 |
+
|
64 |
+
class ImageDraw:
|
65 |
+
font: (
|
66 |
+
ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
|
67 |
+
) = None
|
68 |
+
|
69 |
+
def __init__(self, im: Image.Image, mode: str | None = None) -> None:
|
70 |
+
"""
|
71 |
+
Create a drawing instance.
|
72 |
+
|
73 |
+
:param im: The image to draw in.
|
74 |
+
:param mode: Optional mode to use for color values. For RGB
|
75 |
+
images, this argument can be RGB or RGBA (to blend the
|
76 |
+
drawing into the image). For all other modes, this argument
|
77 |
+
must be the same as the image mode. If omitted, the mode
|
78 |
+
defaults to the mode of the image.
|
79 |
+
"""
|
80 |
+
im.load()
|
81 |
+
if im.readonly:
|
82 |
+
im._copy() # make it writeable
|
83 |
+
blend = 0
|
84 |
+
if mode is None:
|
85 |
+
mode = im.mode
|
86 |
+
if mode != im.mode:
|
87 |
+
if mode == "RGBA" and im.mode == "RGB":
|
88 |
+
blend = 1
|
89 |
+
else:
|
90 |
+
msg = "mode mismatch"
|
91 |
+
raise ValueError(msg)
|
92 |
+
if mode == "P":
|
93 |
+
self.palette = im.palette
|
94 |
+
else:
|
95 |
+
self.palette = None
|
96 |
+
self._image = im
|
97 |
+
self.im = im.im
|
98 |
+
self.draw = Image.core.draw(self.im, blend)
|
99 |
+
self.mode = mode
|
100 |
+
if mode in ("I", "F"):
|
101 |
+
self.ink = self.draw.draw_ink(1)
|
102 |
+
else:
|
103 |
+
self.ink = self.draw.draw_ink(-1)
|
104 |
+
if mode in ("1", "P", "I", "F"):
|
105 |
+
# FIXME: fix Fill2 to properly support matte for I+F images
|
106 |
+
self.fontmode = "1"
|
107 |
+
else:
|
108 |
+
self.fontmode = "L" # aliasing is okay for other modes
|
109 |
+
self.fill = False
|
110 |
+
|
111 |
+
def getfont(
|
112 |
+
self,
|
113 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
114 |
+
"""
|
115 |
+
Get the current default font.
|
116 |
+
|
117 |
+
To set the default font for this ImageDraw instance::
|
118 |
+
|
119 |
+
from PIL import ImageDraw, ImageFont
|
120 |
+
draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
121 |
+
|
122 |
+
To set the default font for all future ImageDraw instances::
|
123 |
+
|
124 |
+
from PIL import ImageDraw, ImageFont
|
125 |
+
ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
126 |
+
|
127 |
+
If the current default font is ``None``,
|
128 |
+
it is initialized with ``ImageFont.load_default()``.
|
129 |
+
|
130 |
+
:returns: An image font."""
|
131 |
+
if not self.font:
|
132 |
+
# FIXME: should add a font repository
|
133 |
+
from . import ImageFont
|
134 |
+
|
135 |
+
self.font = ImageFont.load_default()
|
136 |
+
return self.font
|
137 |
+
|
138 |
+
def _getfont(
|
139 |
+
self, font_size: float | None
|
140 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
141 |
+
if font_size is not None:
|
142 |
+
from . import ImageFont
|
143 |
+
|
144 |
+
return ImageFont.load_default(font_size)
|
145 |
+
else:
|
146 |
+
return self.getfont()
|
147 |
+
|
148 |
+
def _getink(
|
149 |
+
self, ink: _Ink | None, fill: _Ink | None = None
|
150 |
+
) -> tuple[int | None, int | None]:
|
151 |
+
result_ink = None
|
152 |
+
result_fill = None
|
153 |
+
if ink is None and fill is None:
|
154 |
+
if self.fill:
|
155 |
+
result_fill = self.ink
|
156 |
+
else:
|
157 |
+
result_ink = self.ink
|
158 |
+
else:
|
159 |
+
if ink is not None:
|
160 |
+
if isinstance(ink, str):
|
161 |
+
ink = ImageColor.getcolor(ink, self.mode)
|
162 |
+
if self.palette and not isinstance(ink, numbers.Number):
|
163 |
+
ink = self.palette.getcolor(ink, self._image)
|
164 |
+
result_ink = self.draw.draw_ink(ink)
|
165 |
+
if fill is not None:
|
166 |
+
if isinstance(fill, str):
|
167 |
+
fill = ImageColor.getcolor(fill, self.mode)
|
168 |
+
if self.palette and not isinstance(fill, numbers.Number):
|
169 |
+
fill = self.palette.getcolor(fill, self._image)
|
170 |
+
result_fill = self.draw.draw_ink(fill)
|
171 |
+
return result_ink, result_fill
|
172 |
+
|
173 |
+
def arc(
|
174 |
+
self,
|
175 |
+
xy: Coords,
|
176 |
+
start: float,
|
177 |
+
end: float,
|
178 |
+
fill: _Ink | None = None,
|
179 |
+
width: int = 1,
|
180 |
+
) -> None:
|
181 |
+
"""Draw an arc."""
|
182 |
+
ink, fill = self._getink(fill)
|
183 |
+
if ink is not None:
|
184 |
+
self.draw.draw_arc(xy, start, end, ink, width)
|
185 |
+
|
186 |
+
def bitmap(
|
187 |
+
self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
|
188 |
+
) -> None:
|
189 |
+
"""Draw a bitmap."""
|
190 |
+
bitmap.load()
|
191 |
+
ink, fill = self._getink(fill)
|
192 |
+
if ink is None:
|
193 |
+
ink = fill
|
194 |
+
if ink is not None:
|
195 |
+
self.draw.draw_bitmap(xy, bitmap.im, ink)
|
196 |
+
|
197 |
+
def chord(
|
198 |
+
self,
|
199 |
+
xy: Coords,
|
200 |
+
start: float,
|
201 |
+
end: float,
|
202 |
+
fill: _Ink | None = None,
|
203 |
+
outline: _Ink | None = None,
|
204 |
+
width: int = 1,
|
205 |
+
) -> None:
|
206 |
+
"""Draw a chord."""
|
207 |
+
ink, fill_ink = self._getink(outline, fill)
|
208 |
+
if fill_ink is not None:
|
209 |
+
self.draw.draw_chord(xy, start, end, fill_ink, 1)
|
210 |
+
if ink is not None and ink != fill_ink and width != 0:
|
211 |
+
self.draw.draw_chord(xy, start, end, ink, 0, width)
|
212 |
+
|
213 |
+
def ellipse(
|
214 |
+
self,
|
215 |
+
xy: Coords,
|
216 |
+
fill: _Ink | None = None,
|
217 |
+
outline: _Ink | None = None,
|
218 |
+
width: int = 1,
|
219 |
+
) -> None:
|
220 |
+
"""Draw an ellipse."""
|
221 |
+
ink, fill_ink = self._getink(outline, fill)
|
222 |
+
if fill_ink is not None:
|
223 |
+
self.draw.draw_ellipse(xy, fill_ink, 1)
|
224 |
+
if ink is not None and ink != fill_ink and width != 0:
|
225 |
+
self.draw.draw_ellipse(xy, ink, 0, width)
|
226 |
+
|
227 |
+
def circle(
|
228 |
+
self,
|
229 |
+
xy: Sequence[float],
|
230 |
+
radius: float,
|
231 |
+
fill: _Ink | None = None,
|
232 |
+
outline: _Ink | None = None,
|
233 |
+
width: int = 1,
|
234 |
+
) -> None:
|
235 |
+
"""Draw a circle given center coordinates and a radius."""
|
236 |
+
ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
|
237 |
+
self.ellipse(ellipse_xy, fill, outline, width)
|
238 |
+
|
239 |
+
def line(
|
240 |
+
self,
|
241 |
+
xy: Coords,
|
242 |
+
fill: _Ink | None = None,
|
243 |
+
width: int = 0,
|
244 |
+
joint: str | None = None,
|
245 |
+
) -> None:
|
246 |
+
"""Draw a line, or a connected sequence of line segments."""
|
247 |
+
ink = self._getink(fill)[0]
|
248 |
+
if ink is not None:
|
249 |
+
self.draw.draw_lines(xy, ink, width)
|
250 |
+
if joint == "curve" and width > 4:
|
251 |
+
points: Sequence[Sequence[float]]
|
252 |
+
if isinstance(xy[0], (list, tuple)):
|
253 |
+
points = cast(Sequence[Sequence[float]], xy)
|
254 |
+
else:
|
255 |
+
points = [
|
256 |
+
cast(Sequence[float], tuple(xy[i : i + 2]))
|
257 |
+
for i in range(0, len(xy), 2)
|
258 |
+
]
|
259 |
+
for i in range(1, len(points) - 1):
|
260 |
+
point = points[i]
|
261 |
+
angles = [
|
262 |
+
math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
|
263 |
+
% 360
|
264 |
+
for start, end in (
|
265 |
+
(points[i - 1], point),
|
266 |
+
(point, points[i + 1]),
|
267 |
+
)
|
268 |
+
]
|
269 |
+
if angles[0] == angles[1]:
|
270 |
+
# This is a straight line, so no joint is required
|
271 |
+
continue
|
272 |
+
|
273 |
+
def coord_at_angle(
|
274 |
+
coord: Sequence[float], angle: float
|
275 |
+
) -> tuple[float, ...]:
|
276 |
+
x, y = coord
|
277 |
+
angle -= 90
|
278 |
+
distance = width / 2 - 1
|
279 |
+
return tuple(
|
280 |
+
p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
|
281 |
+
for p, p_d in (
|
282 |
+
(x, distance * math.cos(math.radians(angle))),
|
283 |
+
(y, distance * math.sin(math.radians(angle))),
|
284 |
+
)
|
285 |
+
)
|
286 |
+
|
287 |
+
flipped = (
|
288 |
+
angles[1] > angles[0] and angles[1] - 180 > angles[0]
|
289 |
+
) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
|
290 |
+
coords = [
|
291 |
+
(point[0] - width / 2 + 1, point[1] - width / 2 + 1),
|
292 |
+
(point[0] + width / 2 - 1, point[1] + width / 2 - 1),
|
293 |
+
]
|
294 |
+
if flipped:
|
295 |
+
start, end = (angles[1] + 90, angles[0] + 90)
|
296 |
+
else:
|
297 |
+
start, end = (angles[0] - 90, angles[1] - 90)
|
298 |
+
self.pieslice(coords, start - 90, end - 90, fill)
|
299 |
+
|
300 |
+
if width > 8:
|
301 |
+
# Cover potential gaps between the line and the joint
|
302 |
+
if flipped:
|
303 |
+
gap_coords = [
|
304 |
+
coord_at_angle(point, angles[0] + 90),
|
305 |
+
point,
|
306 |
+
coord_at_angle(point, angles[1] + 90),
|
307 |
+
]
|
308 |
+
else:
|
309 |
+
gap_coords = [
|
310 |
+
coord_at_angle(point, angles[0] - 90),
|
311 |
+
point,
|
312 |
+
coord_at_angle(point, angles[1] - 90),
|
313 |
+
]
|
314 |
+
self.line(gap_coords, fill, width=3)
|
315 |
+
|
316 |
+
def shape(
|
317 |
+
self,
|
318 |
+
shape: Image.core._Outline,
|
319 |
+
fill: _Ink | None = None,
|
320 |
+
outline: _Ink | None = None,
|
321 |
+
) -> None:
|
322 |
+
"""(Experimental) Draw a shape."""
|
323 |
+
shape.close()
|
324 |
+
ink, fill_ink = self._getink(outline, fill)
|
325 |
+
if fill_ink is not None:
|
326 |
+
self.draw.draw_outline(shape, fill_ink, 1)
|
327 |
+
if ink is not None and ink != fill_ink:
|
328 |
+
self.draw.draw_outline(shape, ink, 0)
|
329 |
+
|
330 |
+
def pieslice(
|
331 |
+
self,
|
332 |
+
xy: Coords,
|
333 |
+
start: float,
|
334 |
+
end: float,
|
335 |
+
fill: _Ink | None = None,
|
336 |
+
outline: _Ink | None = None,
|
337 |
+
width: int = 1,
|
338 |
+
) -> None:
|
339 |
+
"""Draw a pieslice."""
|
340 |
+
ink, fill_ink = self._getink(outline, fill)
|
341 |
+
if fill_ink is not None:
|
342 |
+
self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
|
343 |
+
if ink is not None and ink != fill_ink and width != 0:
|
344 |
+
self.draw.draw_pieslice(xy, start, end, ink, 0, width)
|
345 |
+
|
346 |
+
def point(self, xy: Coords, fill: _Ink | None = None) -> None:
|
347 |
+
"""Draw one or more individual pixels."""
|
348 |
+
ink, fill = self._getink(fill)
|
349 |
+
if ink is not None:
|
350 |
+
self.draw.draw_points(xy, ink)
|
351 |
+
|
352 |
+
def polygon(
|
353 |
+
self,
|
354 |
+
xy: Coords,
|
355 |
+
fill: _Ink | None = None,
|
356 |
+
outline: _Ink | None = None,
|
357 |
+
width: int = 1,
|
358 |
+
) -> None:
|
359 |
+
"""Draw a polygon."""
|
360 |
+
ink, fill_ink = self._getink(outline, fill)
|
361 |
+
if fill_ink is not None:
|
362 |
+
self.draw.draw_polygon(xy, fill_ink, 1)
|
363 |
+
if ink is not None and ink != fill_ink and width != 0:
|
364 |
+
if width == 1:
|
365 |
+
self.draw.draw_polygon(xy, ink, 0, width)
|
366 |
+
elif self.im is not None:
|
367 |
+
# To avoid expanding the polygon outwards,
|
368 |
+
# use the fill as a mask
|
369 |
+
mask = Image.new("1", self.im.size)
|
370 |
+
mask_ink = self._getink(1)[0]
|
371 |
+
|
372 |
+
fill_im = mask.copy()
|
373 |
+
draw = Draw(fill_im)
|
374 |
+
draw.draw.draw_polygon(xy, mask_ink, 1)
|
375 |
+
|
376 |
+
ink_im = mask.copy()
|
377 |
+
draw = Draw(ink_im)
|
378 |
+
width = width * 2 - 1
|
379 |
+
draw.draw.draw_polygon(xy, mask_ink, 0, width)
|
380 |
+
|
381 |
+
mask.paste(ink_im, mask=fill_im)
|
382 |
+
|
383 |
+
im = Image.new(self.mode, self.im.size)
|
384 |
+
draw = Draw(im)
|
385 |
+
draw.draw.draw_polygon(xy, ink, 0, width)
|
386 |
+
self.im.paste(im.im, (0, 0) + im.size, mask.im)
|
387 |
+
|
388 |
+
def regular_polygon(
|
389 |
+
self,
|
390 |
+
bounding_circle: Sequence[Sequence[float] | float],
|
391 |
+
n_sides: int,
|
392 |
+
rotation: float = 0,
|
393 |
+
fill: _Ink | None = None,
|
394 |
+
outline: _Ink | None = None,
|
395 |
+
width: int = 1,
|
396 |
+
) -> None:
|
397 |
+
"""Draw a regular polygon."""
|
398 |
+
xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
|
399 |
+
self.polygon(xy, fill, outline, width)
|
400 |
+
|
401 |
+
def rectangle(
|
402 |
+
self,
|
403 |
+
xy: Coords,
|
404 |
+
fill: _Ink | None = None,
|
405 |
+
outline: _Ink | None = None,
|
406 |
+
width: int = 1,
|
407 |
+
) -> None:
|
408 |
+
"""Draw a rectangle."""
|
409 |
+
ink, fill_ink = self._getink(outline, fill)
|
410 |
+
if fill_ink is not None:
|
411 |
+
self.draw.draw_rectangle(xy, fill_ink, 1)
|
412 |
+
if ink is not None and ink != fill_ink and width != 0:
|
413 |
+
self.draw.draw_rectangle(xy, ink, 0, width)
|
414 |
+
|
415 |
+
def rounded_rectangle(
|
416 |
+
self,
|
417 |
+
xy: Coords,
|
418 |
+
radius: float = 0,
|
419 |
+
fill: _Ink | None = None,
|
420 |
+
outline: _Ink | None = None,
|
421 |
+
width: int = 1,
|
422 |
+
*,
|
423 |
+
corners: tuple[bool, bool, bool, bool] | None = None,
|
424 |
+
) -> None:
|
425 |
+
"""Draw a rounded rectangle."""
|
426 |
+
if isinstance(xy[0], (list, tuple)):
|
427 |
+
(x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
|
428 |
+
else:
|
429 |
+
x0, y0, x1, y1 = cast(Sequence[float], xy)
|
430 |
+
if x1 < x0:
|
431 |
+
msg = "x1 must be greater than or equal to x0"
|
432 |
+
raise ValueError(msg)
|
433 |
+
if y1 < y0:
|
434 |
+
msg = "y1 must be greater than or equal to y0"
|
435 |
+
raise ValueError(msg)
|
436 |
+
if corners is None:
|
437 |
+
corners = (True, True, True, True)
|
438 |
+
|
439 |
+
d = radius * 2
|
440 |
+
|
441 |
+
x0 = round(x0)
|
442 |
+
y0 = round(y0)
|
443 |
+
x1 = round(x1)
|
444 |
+
y1 = round(y1)
|
445 |
+
full_x, full_y = False, False
|
446 |
+
if all(corners):
|
447 |
+
full_x = d >= x1 - x0 - 1
|
448 |
+
if full_x:
|
449 |
+
# The two left and two right corners are joined
|
450 |
+
d = x1 - x0
|
451 |
+
full_y = d >= y1 - y0 - 1
|
452 |
+
if full_y:
|
453 |
+
# The two top and two bottom corners are joined
|
454 |
+
d = y1 - y0
|
455 |
+
if full_x and full_y:
|
456 |
+
# If all corners are joined, that is a circle
|
457 |
+
return self.ellipse(xy, fill, outline, width)
|
458 |
+
|
459 |
+
if d == 0 or not any(corners):
|
460 |
+
# If the corners have no curve,
|
461 |
+
# or there are no corners,
|
462 |
+
# that is a rectangle
|
463 |
+
return self.rectangle(xy, fill, outline, width)
|
464 |
+
|
465 |
+
r = int(d // 2)
|
466 |
+
ink, fill_ink = self._getink(outline, fill)
|
467 |
+
|
468 |
+
def draw_corners(pieslice: bool) -> None:
|
469 |
+
parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
|
470 |
+
if full_x:
|
471 |
+
# Draw top and bottom halves
|
472 |
+
parts = (
|
473 |
+
((x0, y0, x0 + d, y0 + d), 180, 360),
|
474 |
+
((x0, y1 - d, x0 + d, y1), 0, 180),
|
475 |
+
)
|
476 |
+
elif full_y:
|
477 |
+
# Draw left and right halves
|
478 |
+
parts = (
|
479 |
+
((x0, y0, x0 + d, y0 + d), 90, 270),
|
480 |
+
((x1 - d, y0, x1, y0 + d), 270, 90),
|
481 |
+
)
|
482 |
+
else:
|
483 |
+
# Draw four separate corners
|
484 |
+
parts = tuple(
|
485 |
+
part
|
486 |
+
for i, part in enumerate(
|
487 |
+
(
|
488 |
+
((x0, y0, x0 + d, y0 + d), 180, 270),
|
489 |
+
((x1 - d, y0, x1, y0 + d), 270, 360),
|
490 |
+
((x1 - d, y1 - d, x1, y1), 0, 90),
|
491 |
+
((x0, y1 - d, x0 + d, y1), 90, 180),
|
492 |
+
)
|
493 |
+
)
|
494 |
+
if corners[i]
|
495 |
+
)
|
496 |
+
for part in parts:
|
497 |
+
if pieslice:
|
498 |
+
self.draw.draw_pieslice(*(part + (fill_ink, 1)))
|
499 |
+
else:
|
500 |
+
self.draw.draw_arc(*(part + (ink, width)))
|
501 |
+
|
502 |
+
if fill_ink is not None:
|
503 |
+
draw_corners(True)
|
504 |
+
|
505 |
+
if full_x:
|
506 |
+
self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
|
507 |
+
else:
|
508 |
+
self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
|
509 |
+
if not full_x and not full_y:
|
510 |
+
left = [x0, y0, x0 + r, y1]
|
511 |
+
if corners[0]:
|
512 |
+
left[1] += r + 1
|
513 |
+
if corners[3]:
|
514 |
+
left[3] -= r + 1
|
515 |
+
self.draw.draw_rectangle(left, fill_ink, 1)
|
516 |
+
|
517 |
+
right = [x1 - r, y0, x1, y1]
|
518 |
+
if corners[1]:
|
519 |
+
right[1] += r + 1
|
520 |
+
if corners[2]:
|
521 |
+
right[3] -= r + 1
|
522 |
+
self.draw.draw_rectangle(right, fill_ink, 1)
|
523 |
+
if ink is not None and ink != fill_ink and width != 0:
|
524 |
+
draw_corners(False)
|
525 |
+
|
526 |
+
if not full_x:
|
527 |
+
top = [x0, y0, x1, y0 + width - 1]
|
528 |
+
if corners[0]:
|
529 |
+
top[0] += r + 1
|
530 |
+
if corners[1]:
|
531 |
+
top[2] -= r + 1
|
532 |
+
self.draw.draw_rectangle(top, ink, 1)
|
533 |
+
|
534 |
+
bottom = [x0, y1 - width + 1, x1, y1]
|
535 |
+
if corners[3]:
|
536 |
+
bottom[0] += r + 1
|
537 |
+
if corners[2]:
|
538 |
+
bottom[2] -= r + 1
|
539 |
+
self.draw.draw_rectangle(bottom, ink, 1)
|
540 |
+
if not full_y:
|
541 |
+
left = [x0, y0, x0 + width - 1, y1]
|
542 |
+
if corners[0]:
|
543 |
+
left[1] += r + 1
|
544 |
+
if corners[3]:
|
545 |
+
left[3] -= r + 1
|
546 |
+
self.draw.draw_rectangle(left, ink, 1)
|
547 |
+
|
548 |
+
right = [x1 - width + 1, y0, x1, y1]
|
549 |
+
if corners[1]:
|
550 |
+
right[1] += r + 1
|
551 |
+
if corners[2]:
|
552 |
+
right[3] -= r + 1
|
553 |
+
self.draw.draw_rectangle(right, ink, 1)
|
554 |
+
|
555 |
+
def _multiline_check(self, text: AnyStr) -> bool:
|
556 |
+
split_character = "\n" if isinstance(text, str) else b"\n"
|
557 |
+
|
558 |
+
return split_character in text
|
559 |
+
|
560 |
+
def _multiline_split(self, text: AnyStr) -> list[AnyStr]:
|
561 |
+
return text.split("\n" if isinstance(text, str) else b"\n")
|
562 |
+
|
563 |
+
def _multiline_spacing(self, font, spacing, stroke_width):
|
564 |
+
return (
|
565 |
+
self.textbbox((0, 0), "A", font, stroke_width=stroke_width)[3]
|
566 |
+
+ stroke_width
|
567 |
+
+ spacing
|
568 |
+
)
|
569 |
+
|
570 |
+
def text(
|
571 |
+
self,
|
572 |
+
xy: tuple[float, float],
|
573 |
+
text: str,
|
574 |
+
fill=None,
|
575 |
+
font: (
|
576 |
+
ImageFont.ImageFont
|
577 |
+
| ImageFont.FreeTypeFont
|
578 |
+
| ImageFont.TransposedFont
|
579 |
+
| None
|
580 |
+
) = None,
|
581 |
+
anchor=None,
|
582 |
+
spacing=4,
|
583 |
+
align="left",
|
584 |
+
direction=None,
|
585 |
+
features=None,
|
586 |
+
language=None,
|
587 |
+
stroke_width=0,
|
588 |
+
stroke_fill=None,
|
589 |
+
embedded_color=False,
|
590 |
+
*args,
|
591 |
+
**kwargs,
|
592 |
+
) -> None:
|
593 |
+
"""Draw text."""
|
594 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
595 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
596 |
+
raise ValueError(msg)
|
597 |
+
|
598 |
+
if font is None:
|
599 |
+
font = self._getfont(kwargs.get("font_size"))
|
600 |
+
|
601 |
+
if self._multiline_check(text):
|
602 |
+
return self.multiline_text(
|
603 |
+
xy,
|
604 |
+
text,
|
605 |
+
fill,
|
606 |
+
font,
|
607 |
+
anchor,
|
608 |
+
spacing,
|
609 |
+
align,
|
610 |
+
direction,
|
611 |
+
features,
|
612 |
+
language,
|
613 |
+
stroke_width,
|
614 |
+
stroke_fill,
|
615 |
+
embedded_color,
|
616 |
+
)
|
617 |
+
|
618 |
+
def getink(fill: _Ink | None) -> int:
|
619 |
+
ink, fill_ink = self._getink(fill)
|
620 |
+
if ink is None:
|
621 |
+
assert fill_ink is not None
|
622 |
+
return fill_ink
|
623 |
+
return ink
|
624 |
+
|
625 |
+
def draw_text(ink, stroke_width=0, stroke_offset=None) -> None:
|
626 |
+
mode = self.fontmode
|
627 |
+
if stroke_width == 0 and embedded_color:
|
628 |
+
mode = "RGBA"
|
629 |
+
coord = []
|
630 |
+
start = []
|
631 |
+
for i in range(2):
|
632 |
+
coord.append(int(xy[i]))
|
633 |
+
start.append(math.modf(xy[i])[0])
|
634 |
+
try:
|
635 |
+
mask, offset = font.getmask2( # type: ignore[union-attr,misc]
|
636 |
+
text,
|
637 |
+
mode,
|
638 |
+
direction=direction,
|
639 |
+
features=features,
|
640 |
+
language=language,
|
641 |
+
stroke_width=stroke_width,
|
642 |
+
anchor=anchor,
|
643 |
+
ink=ink,
|
644 |
+
start=start,
|
645 |
+
*args,
|
646 |
+
**kwargs,
|
647 |
+
)
|
648 |
+
coord = [coord[0] + offset[0], coord[1] + offset[1]]
|
649 |
+
except AttributeError:
|
650 |
+
try:
|
651 |
+
mask = font.getmask( # type: ignore[misc]
|
652 |
+
text,
|
653 |
+
mode,
|
654 |
+
direction,
|
655 |
+
features,
|
656 |
+
language,
|
657 |
+
stroke_width,
|
658 |
+
anchor,
|
659 |
+
ink,
|
660 |
+
start=start,
|
661 |
+
*args,
|
662 |
+
**kwargs,
|
663 |
+
)
|
664 |
+
except TypeError:
|
665 |
+
mask = font.getmask(text)
|
666 |
+
if stroke_offset:
|
667 |
+
coord = [coord[0] + stroke_offset[0], coord[1] + stroke_offset[1]]
|
668 |
+
if mode == "RGBA":
|
669 |
+
# font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
|
670 |
+
# extract mask and set text alpha
|
671 |
+
color, mask = mask, mask.getband(3)
|
672 |
+
ink_alpha = struct.pack("i", ink)[3]
|
673 |
+
color.fillband(3, ink_alpha)
|
674 |
+
x, y = coord
|
675 |
+
if self.im is not None:
|
676 |
+
self.im.paste(
|
677 |
+
color, (x, y, x + mask.size[0], y + mask.size[1]), mask
|
678 |
+
)
|
679 |
+
else:
|
680 |
+
self.draw.draw_bitmap(coord, mask, ink)
|
681 |
+
|
682 |
+
ink = getink(fill)
|
683 |
+
if ink is not None:
|
684 |
+
stroke_ink = None
|
685 |
+
if stroke_width:
|
686 |
+
stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
|
687 |
+
|
688 |
+
if stroke_ink is not None:
|
689 |
+
# Draw stroked text
|
690 |
+
draw_text(stroke_ink, stroke_width)
|
691 |
+
|
692 |
+
# Draw normal text
|
693 |
+
draw_text(ink, 0)
|
694 |
+
else:
|
695 |
+
# Only draw normal text
|
696 |
+
draw_text(ink)
|
697 |
+
|
698 |
+
def multiline_text(
|
699 |
+
self,
|
700 |
+
xy: tuple[float, float],
|
701 |
+
text: str,
|
702 |
+
fill=None,
|
703 |
+
font: (
|
704 |
+
ImageFont.ImageFont
|
705 |
+
| ImageFont.FreeTypeFont
|
706 |
+
| ImageFont.TransposedFont
|
707 |
+
| None
|
708 |
+
) = None,
|
709 |
+
anchor=None,
|
710 |
+
spacing=4,
|
711 |
+
align="left",
|
712 |
+
direction=None,
|
713 |
+
features=None,
|
714 |
+
language=None,
|
715 |
+
stroke_width=0,
|
716 |
+
stroke_fill=None,
|
717 |
+
embedded_color=False,
|
718 |
+
*,
|
719 |
+
font_size=None,
|
720 |
+
) -> None:
|
721 |
+
if direction == "ttb":
|
722 |
+
msg = "ttb direction is unsupported for multiline text"
|
723 |
+
raise ValueError(msg)
|
724 |
+
|
725 |
+
if anchor is None:
|
726 |
+
anchor = "la"
|
727 |
+
elif len(anchor) != 2:
|
728 |
+
msg = "anchor must be a 2 character string"
|
729 |
+
raise ValueError(msg)
|
730 |
+
elif anchor[1] in "tb":
|
731 |
+
msg = "anchor not supported for multiline text"
|
732 |
+
raise ValueError(msg)
|
733 |
+
|
734 |
+
if font is None:
|
735 |
+
font = self._getfont(font_size)
|
736 |
+
|
737 |
+
widths = []
|
738 |
+
max_width: float = 0
|
739 |
+
lines = self._multiline_split(text)
|
740 |
+
line_spacing = self._multiline_spacing(font, spacing, stroke_width)
|
741 |
+
for line in lines:
|
742 |
+
line_width = self.textlength(
|
743 |
+
line, font, direction=direction, features=features, language=language
|
744 |
+
)
|
745 |
+
widths.append(line_width)
|
746 |
+
max_width = max(max_width, line_width)
|
747 |
+
|
748 |
+
top = xy[1]
|
749 |
+
if anchor[1] == "m":
|
750 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
751 |
+
elif anchor[1] == "d":
|
752 |
+
top -= (len(lines) - 1) * line_spacing
|
753 |
+
|
754 |
+
for idx, line in enumerate(lines):
|
755 |
+
left = xy[0]
|
756 |
+
width_difference = max_width - widths[idx]
|
757 |
+
|
758 |
+
# first align left by anchor
|
759 |
+
if anchor[0] == "m":
|
760 |
+
left -= width_difference / 2.0
|
761 |
+
elif anchor[0] == "r":
|
762 |
+
left -= width_difference
|
763 |
+
|
764 |
+
# then align by align parameter
|
765 |
+
if align == "left":
|
766 |
+
pass
|
767 |
+
elif align == "center":
|
768 |
+
left += width_difference / 2.0
|
769 |
+
elif align == "right":
|
770 |
+
left += width_difference
|
771 |
+
else:
|
772 |
+
msg = 'align must be "left", "center" or "right"'
|
773 |
+
raise ValueError(msg)
|
774 |
+
|
775 |
+
self.text(
|
776 |
+
(left, top),
|
777 |
+
line,
|
778 |
+
fill,
|
779 |
+
font,
|
780 |
+
anchor,
|
781 |
+
direction=direction,
|
782 |
+
features=features,
|
783 |
+
language=language,
|
784 |
+
stroke_width=stroke_width,
|
785 |
+
stroke_fill=stroke_fill,
|
786 |
+
embedded_color=embedded_color,
|
787 |
+
)
|
788 |
+
top += line_spacing
|
789 |
+
|
790 |
+
def textlength(
|
791 |
+
self,
|
792 |
+
text: str,
|
793 |
+
font: (
|
794 |
+
ImageFont.ImageFont
|
795 |
+
| ImageFont.FreeTypeFont
|
796 |
+
| ImageFont.TransposedFont
|
797 |
+
| None
|
798 |
+
) = None,
|
799 |
+
direction=None,
|
800 |
+
features=None,
|
801 |
+
language=None,
|
802 |
+
embedded_color=False,
|
803 |
+
*,
|
804 |
+
font_size=None,
|
805 |
+
) -> float:
|
806 |
+
"""Get the length of a given string, in pixels with 1/64 precision."""
|
807 |
+
if self._multiline_check(text):
|
808 |
+
msg = "can't measure length of multiline text"
|
809 |
+
raise ValueError(msg)
|
810 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
811 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
812 |
+
raise ValueError(msg)
|
813 |
+
|
814 |
+
if font is None:
|
815 |
+
font = self._getfont(font_size)
|
816 |
+
mode = "RGBA" if embedded_color else self.fontmode
|
817 |
+
return font.getlength(text, mode, direction, features, language)
|
818 |
+
|
819 |
+
def textbbox(
|
820 |
+
self,
|
821 |
+
xy,
|
822 |
+
text,
|
823 |
+
font=None,
|
824 |
+
anchor=None,
|
825 |
+
spacing=4,
|
826 |
+
align="left",
|
827 |
+
direction=None,
|
828 |
+
features=None,
|
829 |
+
language=None,
|
830 |
+
stroke_width=0,
|
831 |
+
embedded_color=False,
|
832 |
+
*,
|
833 |
+
font_size=None,
|
834 |
+
) -> tuple[int, int, int, int]:
|
835 |
+
"""Get the bounding box of a given string, in pixels."""
|
836 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
837 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
838 |
+
raise ValueError(msg)
|
839 |
+
|
840 |
+
if font is None:
|
841 |
+
font = self._getfont(font_size)
|
842 |
+
|
843 |
+
if self._multiline_check(text):
|
844 |
+
return self.multiline_textbbox(
|
845 |
+
xy,
|
846 |
+
text,
|
847 |
+
font,
|
848 |
+
anchor,
|
849 |
+
spacing,
|
850 |
+
align,
|
851 |
+
direction,
|
852 |
+
features,
|
853 |
+
language,
|
854 |
+
stroke_width,
|
855 |
+
embedded_color,
|
856 |
+
)
|
857 |
+
|
858 |
+
mode = "RGBA" if embedded_color else self.fontmode
|
859 |
+
bbox = font.getbbox(
|
860 |
+
text, mode, direction, features, language, stroke_width, anchor
|
861 |
+
)
|
862 |
+
return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
|
863 |
+
|
864 |
+
def multiline_textbbox(
|
865 |
+
self,
|
866 |
+
xy,
|
867 |
+
text,
|
868 |
+
font=None,
|
869 |
+
anchor=None,
|
870 |
+
spacing=4,
|
871 |
+
align="left",
|
872 |
+
direction=None,
|
873 |
+
features=None,
|
874 |
+
language=None,
|
875 |
+
stroke_width=0,
|
876 |
+
embedded_color=False,
|
877 |
+
*,
|
878 |
+
font_size=None,
|
879 |
+
) -> tuple[int, int, int, int]:
|
880 |
+
if direction == "ttb":
|
881 |
+
msg = "ttb direction is unsupported for multiline text"
|
882 |
+
raise ValueError(msg)
|
883 |
+
|
884 |
+
if anchor is None:
|
885 |
+
anchor = "la"
|
886 |
+
elif len(anchor) != 2:
|
887 |
+
msg = "anchor must be a 2 character string"
|
888 |
+
raise ValueError(msg)
|
889 |
+
elif anchor[1] in "tb":
|
890 |
+
msg = "anchor not supported for multiline text"
|
891 |
+
raise ValueError(msg)
|
892 |
+
|
893 |
+
if font is None:
|
894 |
+
font = self._getfont(font_size)
|
895 |
+
|
896 |
+
widths = []
|
897 |
+
max_width: float = 0
|
898 |
+
lines = self._multiline_split(text)
|
899 |
+
line_spacing = self._multiline_spacing(font, spacing, stroke_width)
|
900 |
+
for line in lines:
|
901 |
+
line_width = self.textlength(
|
902 |
+
line,
|
903 |
+
font,
|
904 |
+
direction=direction,
|
905 |
+
features=features,
|
906 |
+
language=language,
|
907 |
+
embedded_color=embedded_color,
|
908 |
+
)
|
909 |
+
widths.append(line_width)
|
910 |
+
max_width = max(max_width, line_width)
|
911 |
+
|
912 |
+
top = xy[1]
|
913 |
+
if anchor[1] == "m":
|
914 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
915 |
+
elif anchor[1] == "d":
|
916 |
+
top -= (len(lines) - 1) * line_spacing
|
917 |
+
|
918 |
+
bbox: tuple[int, int, int, int] | None = None
|
919 |
+
|
920 |
+
for idx, line in enumerate(lines):
|
921 |
+
left = xy[0]
|
922 |
+
width_difference = max_width - widths[idx]
|
923 |
+
|
924 |
+
# first align left by anchor
|
925 |
+
if anchor[0] == "m":
|
926 |
+
left -= width_difference / 2.0
|
927 |
+
elif anchor[0] == "r":
|
928 |
+
left -= width_difference
|
929 |
+
|
930 |
+
# then align by align parameter
|
931 |
+
if align == "left":
|
932 |
+
pass
|
933 |
+
elif align == "center":
|
934 |
+
left += width_difference / 2.0
|
935 |
+
elif align == "right":
|
936 |
+
left += width_difference
|
937 |
+
else:
|
938 |
+
msg = 'align must be "left", "center" or "right"'
|
939 |
+
raise ValueError(msg)
|
940 |
+
|
941 |
+
bbox_line = self.textbbox(
|
942 |
+
(left, top),
|
943 |
+
line,
|
944 |
+
font,
|
945 |
+
anchor,
|
946 |
+
direction=direction,
|
947 |
+
features=features,
|
948 |
+
language=language,
|
949 |
+
stroke_width=stroke_width,
|
950 |
+
embedded_color=embedded_color,
|
951 |
+
)
|
952 |
+
if bbox is None:
|
953 |
+
bbox = bbox_line
|
954 |
+
else:
|
955 |
+
bbox = (
|
956 |
+
min(bbox[0], bbox_line[0]),
|
957 |
+
min(bbox[1], bbox_line[1]),
|
958 |
+
max(bbox[2], bbox_line[2]),
|
959 |
+
max(bbox[3], bbox_line[3]),
|
960 |
+
)
|
961 |
+
|
962 |
+
top += line_spacing
|
963 |
+
|
964 |
+
if bbox is None:
|
965 |
+
return xy[0], xy[1], xy[0], xy[1]
|
966 |
+
return bbox
|
967 |
+
|
968 |
+
|
969 |
+
def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
|
970 |
+
"""
|
971 |
+
A simple 2D drawing interface for PIL images.
|
972 |
+
|
973 |
+
:param im: The image to draw in.
|
974 |
+
:param mode: Optional mode to use for color values. For RGB
|
975 |
+
images, this argument can be RGB or RGBA (to blend the
|
976 |
+
drawing into the image). For all other modes, this argument
|
977 |
+
must be the same as the image mode. If omitted, the mode
|
978 |
+
defaults to the mode of the image.
|
979 |
+
"""
|
980 |
+
try:
|
981 |
+
return getattr(im, "getdraw")(mode)
|
982 |
+
except AttributeError:
|
983 |
+
return ImageDraw(im, mode)
|
984 |
+
|
985 |
+
|
986 |
+
def getdraw(
|
987 |
+
im: Image.Image | None = None, hints: list[str] | None = None
|
988 |
+
) -> tuple[ImageDraw2.Draw | None, ModuleType]:
|
989 |
+
"""
|
990 |
+
:param im: The image to draw in.
|
991 |
+
:param hints: An optional list of hints. Deprecated.
|
992 |
+
:returns: A (drawing context, drawing resource factory) tuple.
|
993 |
+
"""
|
994 |
+
if hints is not None:
|
995 |
+
deprecate("'hints' parameter", 12)
|
996 |
+
from . import ImageDraw2
|
997 |
+
|
998 |
+
draw = ImageDraw2.Draw(im) if im is not None else None
|
999 |
+
return draw, ImageDraw2
|
1000 |
+
|
1001 |
+
|
1002 |
+
def floodfill(
|
1003 |
+
image: Image.Image,
|
1004 |
+
xy: tuple[int, int],
|
1005 |
+
value: float | tuple[int, ...],
|
1006 |
+
border: float | tuple[int, ...] | None = None,
|
1007 |
+
thresh: float = 0,
|
1008 |
+
) -> None:
|
1009 |
+
"""
|
1010 |
+
.. warning:: This method is experimental.
|
1011 |
+
|
1012 |
+
Fills a bounded region with a given color.
|
1013 |
+
|
1014 |
+
:param image: Target image.
|
1015 |
+
:param xy: Seed position (a 2-item coordinate tuple). See
|
1016 |
+
:ref:`coordinate-system`.
|
1017 |
+
:param value: Fill color.
|
1018 |
+
:param border: Optional border value. If given, the region consists of
|
1019 |
+
pixels with a color different from the border color. If not given,
|
1020 |
+
the region consists of pixels having the same color as the seed
|
1021 |
+
pixel.
|
1022 |
+
:param thresh: Optional threshold value which specifies a maximum
|
1023 |
+
tolerable difference of a pixel value from the 'background' in
|
1024 |
+
order for it to be replaced. Useful for filling regions of
|
1025 |
+
non-homogeneous, but similar, colors.
|
1026 |
+
"""
|
1027 |
+
# based on an implementation by Eric S. Raymond
|
1028 |
+
# amended by yo1995 @20180806
|
1029 |
+
pixel = image.load()
|
1030 |
+
assert pixel is not None
|
1031 |
+
x, y = xy
|
1032 |
+
try:
|
1033 |
+
background = pixel[x, y]
|
1034 |
+
if _color_diff(value, background) <= thresh:
|
1035 |
+
return # seed point already has fill color
|
1036 |
+
pixel[x, y] = value
|
1037 |
+
except (ValueError, IndexError):
|
1038 |
+
return # seed point outside image
|
1039 |
+
edge = {(x, y)}
|
1040 |
+
# use a set to keep record of current and previous edge pixels
|
1041 |
+
# to reduce memory consumption
|
1042 |
+
full_edge = set()
|
1043 |
+
while edge:
|
1044 |
+
new_edge = set()
|
1045 |
+
for x, y in edge: # 4 adjacent method
|
1046 |
+
for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
1047 |
+
# If already processed, or if a coordinate is negative, skip
|
1048 |
+
if (s, t) in full_edge or s < 0 or t < 0:
|
1049 |
+
continue
|
1050 |
+
try:
|
1051 |
+
p = pixel[s, t]
|
1052 |
+
except (ValueError, IndexError):
|
1053 |
+
pass
|
1054 |
+
else:
|
1055 |
+
full_edge.add((s, t))
|
1056 |
+
if border is None:
|
1057 |
+
fill = _color_diff(p, background) <= thresh
|
1058 |
+
else:
|
1059 |
+
fill = p not in (value, border)
|
1060 |
+
if fill:
|
1061 |
+
pixel[s, t] = value
|
1062 |
+
new_edge.add((s, t))
|
1063 |
+
full_edge = edge # discard pixels processed
|
1064 |
+
edge = new_edge
|
1065 |
+
|
1066 |
+
|
1067 |
+
def _compute_regular_polygon_vertices(
|
1068 |
+
bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
|
1069 |
+
) -> list[tuple[float, float]]:
|
1070 |
+
"""
|
1071 |
+
Generate a list of vertices for a 2D regular polygon.
|
1072 |
+
|
1073 |
+
:param bounding_circle: The bounding circle is a sequence defined
|
1074 |
+
by a point and radius. The polygon is inscribed in this circle.
|
1075 |
+
(e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
|
1076 |
+
:param n_sides: Number of sides
|
1077 |
+
(e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
|
1078 |
+
:param rotation: Apply an arbitrary rotation to the polygon
|
1079 |
+
(e.g. ``rotation=90``, applies a 90 degree rotation)
|
1080 |
+
:return: List of regular polygon vertices
|
1081 |
+
(e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
|
1082 |
+
|
1083 |
+
How are the vertices computed?
|
1084 |
+
1. Compute the following variables
|
1085 |
+
- theta: Angle between the apothem & the nearest polygon vertex
|
1086 |
+
- side_length: Length of each polygon edge
|
1087 |
+
- centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
|
1088 |
+
- polygon_radius: Polygon radius (last element of bounding_circle)
|
1089 |
+
- angles: Location of each polygon vertex in polar grid
|
1090 |
+
(e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
|
1091 |
+
|
1092 |
+
2. For each angle in angles, get the polygon vertex at that angle
|
1093 |
+
The vertex is computed using the equation below.
|
1094 |
+
X= xcos(φ) + ysin(φ)
|
1095 |
+
Y= −xsin(φ) + ycos(φ)
|
1096 |
+
|
1097 |
+
Note:
|
1098 |
+
φ = angle in degrees
|
1099 |
+
x = 0
|
1100 |
+
y = polygon_radius
|
1101 |
+
|
1102 |
+
The formula above assumes rotation around the origin.
|
1103 |
+
In our case, we are rotating around the centroid.
|
1104 |
+
To account for this, we use the formula below
|
1105 |
+
X = xcos(φ) + ysin(φ) + centroid_x
|
1106 |
+
Y = −xsin(φ) + ycos(φ) + centroid_y
|
1107 |
+
"""
|
1108 |
+
# 1. Error Handling
|
1109 |
+
# 1.1 Check `n_sides` has an appropriate value
|
1110 |
+
if not isinstance(n_sides, int):
|
1111 |
+
msg = "n_sides should be an int" # type: ignore[unreachable]
|
1112 |
+
raise TypeError(msg)
|
1113 |
+
if n_sides < 3:
|
1114 |
+
msg = "n_sides should be an int > 2"
|
1115 |
+
raise ValueError(msg)
|
1116 |
+
|
1117 |
+
# 1.2 Check `bounding_circle` has an appropriate value
|
1118 |
+
if not isinstance(bounding_circle, (list, tuple)):
|
1119 |
+
msg = "bounding_circle should be a sequence"
|
1120 |
+
raise TypeError(msg)
|
1121 |
+
|
1122 |
+
if len(bounding_circle) == 3:
|
1123 |
+
if not all(isinstance(i, (int, float)) for i in bounding_circle):
|
1124 |
+
msg = "bounding_circle should only contain numeric data"
|
1125 |
+
raise ValueError(msg)
|
1126 |
+
|
1127 |
+
*centroid, polygon_radius = cast(List[float], list(bounding_circle))
|
1128 |
+
elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
|
1129 |
+
if not all(
|
1130 |
+
isinstance(i, (int, float)) for i in bounding_circle[0]
|
1131 |
+
) or not isinstance(bounding_circle[1], (int, float)):
|
1132 |
+
msg = "bounding_circle should only contain numeric data"
|
1133 |
+
raise ValueError(msg)
|
1134 |
+
|
1135 |
+
if len(bounding_circle[0]) != 2:
|
1136 |
+
msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
|
1137 |
+
raise ValueError(msg)
|
1138 |
+
|
1139 |
+
centroid = cast(List[float], list(bounding_circle[0]))
|
1140 |
+
polygon_radius = cast(float, bounding_circle[1])
|
1141 |
+
else:
|
1142 |
+
msg = (
|
1143 |
+
"bounding_circle should contain 2D coordinates "
|
1144 |
+
"and a radius (e.g. (x, y, r) or ((x, y), r) )"
|
1145 |
+
)
|
1146 |
+
raise ValueError(msg)
|
1147 |
+
|
1148 |
+
if polygon_radius <= 0:
|
1149 |
+
msg = "bounding_circle radius should be > 0"
|
1150 |
+
raise ValueError(msg)
|
1151 |
+
|
1152 |
+
# 1.3 Check `rotation` has an appropriate value
|
1153 |
+
if not isinstance(rotation, (int, float)):
|
1154 |
+
msg = "rotation should be an int or float" # type: ignore[unreachable]
|
1155 |
+
raise ValueError(msg)
|
1156 |
+
|
1157 |
+
# 2. Define Helper Functions
|
1158 |
+
def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
|
1159 |
+
return (
|
1160 |
+
round(
|
1161 |
+
point[0] * math.cos(math.radians(360 - degrees))
|
1162 |
+
- point[1] * math.sin(math.radians(360 - degrees))
|
1163 |
+
+ centroid[0],
|
1164 |
+
2,
|
1165 |
+
),
|
1166 |
+
round(
|
1167 |
+
point[1] * math.cos(math.radians(360 - degrees))
|
1168 |
+
+ point[0] * math.sin(math.radians(360 - degrees))
|
1169 |
+
+ centroid[1],
|
1170 |
+
2,
|
1171 |
+
),
|
1172 |
+
)
|
1173 |
+
|
1174 |
+
def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
|
1175 |
+
start_point = [polygon_radius, 0]
|
1176 |
+
return _apply_rotation(start_point, angle)
|
1177 |
+
|
1178 |
+
def _get_angles(n_sides: int, rotation: float) -> list[float]:
|
1179 |
+
angles = []
|
1180 |
+
degrees = 360 / n_sides
|
1181 |
+
# Start with the bottom left polygon vertex
|
1182 |
+
current_angle = (270 - 0.5 * degrees) + rotation
|
1183 |
+
for _ in range(0, n_sides):
|
1184 |
+
angles.append(current_angle)
|
1185 |
+
current_angle += degrees
|
1186 |
+
if current_angle > 360:
|
1187 |
+
current_angle -= 360
|
1188 |
+
return angles
|
1189 |
+
|
1190 |
+
# 3. Variable Declarations
|
1191 |
+
angles = _get_angles(n_sides, rotation)
|
1192 |
+
|
1193 |
+
# 4. Compute Vertices
|
1194 |
+
return [_compute_polygon_vertex(angle) for angle in angles]
|
1195 |
+
|
1196 |
+
|
1197 |
+
def _color_diff(
|
1198 |
+
color1: float | tuple[int, ...], color2: float | tuple[int, ...]
|
1199 |
+
) -> float:
|
1200 |
+
"""
|
1201 |
+
Uses 1-norm distance to calculate difference between two values.
|
1202 |
+
"""
|
1203 |
+
first = color1 if isinstance(color1, tuple) else (color1,)
|
1204 |
+
second = color2 if isinstance(color2, tuple) else (color2,)
|
1205 |
+
|
1206 |
+
return sum(abs(first[i] - second[i]) for i in range(0, len(second)))
|
MLPY/Lib/site-packages/PIL/ImageDraw2.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# WCK-style drawing interface operations
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2003-12-07 fl created
|
9 |
+
# 2005-05-15 fl updated; added to PIL as ImageDraw2
|
10 |
+
# 2005-05-15 fl added text support
|
11 |
+
# 2005-05-20 fl added arc/chord/pieslice support
|
12 |
+
#
|
13 |
+
# Copyright (c) 2003-2005 by Secret Labs AB
|
14 |
+
# Copyright (c) 2003-2005 by Fredrik Lundh
|
15 |
+
#
|
16 |
+
# See the README file for information on usage and redistribution.
|
17 |
+
#
|
18 |
+
|
19 |
+
|
20 |
+
"""
|
21 |
+
(Experimental) WCK-style drawing interface operations
|
22 |
+
|
23 |
+
.. seealso:: :py:mod:`PIL.ImageDraw`
|
24 |
+
"""
|
25 |
+
from __future__ import annotations
|
26 |
+
|
27 |
+
from typing import BinaryIO
|
28 |
+
|
29 |
+
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
|
30 |
+
from ._typing import StrOrBytesPath
|
31 |
+
|
32 |
+
|
33 |
+
class Pen:
|
34 |
+
"""Stores an outline color and width."""
|
35 |
+
|
36 |
+
def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
|
37 |
+
self.color = ImageColor.getrgb(color)
|
38 |
+
self.width = width
|
39 |
+
|
40 |
+
|
41 |
+
class Brush:
|
42 |
+
"""Stores a fill color"""
|
43 |
+
|
44 |
+
def __init__(self, color: str, opacity: int = 255) -> None:
|
45 |
+
self.color = ImageColor.getrgb(color)
|
46 |
+
|
47 |
+
|
48 |
+
class Font:
|
49 |
+
"""Stores a TrueType font and color"""
|
50 |
+
|
51 |
+
def __init__(
|
52 |
+
self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
|
53 |
+
) -> None:
|
54 |
+
# FIXME: add support for bitmap fonts
|
55 |
+
self.color = ImageColor.getrgb(color)
|
56 |
+
self.font = ImageFont.truetype(file, size)
|
57 |
+
|
58 |
+
|
59 |
+
class Draw:
|
60 |
+
"""
|
61 |
+
(Experimental) WCK-style drawing interface
|
62 |
+
"""
|
63 |
+
|
64 |
+
def __init__(
|
65 |
+
self,
|
66 |
+
image: Image.Image | str,
|
67 |
+
size: tuple[int, int] | list[int] | None = None,
|
68 |
+
color: float | tuple[float, ...] | str | None = None,
|
69 |
+
) -> None:
|
70 |
+
if isinstance(image, str):
|
71 |
+
if size is None:
|
72 |
+
msg = "If image argument is mode string, size must be a list or tuple"
|
73 |
+
raise ValueError(msg)
|
74 |
+
image = Image.new(image, size, color)
|
75 |
+
self.draw = ImageDraw.Draw(image)
|
76 |
+
self.image = image
|
77 |
+
self.transform = None
|
78 |
+
|
79 |
+
def flush(self) -> Image.Image:
|
80 |
+
return self.image
|
81 |
+
|
82 |
+
def render(self, op, xy, pen, brush=None):
|
83 |
+
# handle color arguments
|
84 |
+
outline = fill = None
|
85 |
+
width = 1
|
86 |
+
if isinstance(pen, Pen):
|
87 |
+
outline = pen.color
|
88 |
+
width = pen.width
|
89 |
+
elif isinstance(brush, Pen):
|
90 |
+
outline = brush.color
|
91 |
+
width = brush.width
|
92 |
+
if isinstance(brush, Brush):
|
93 |
+
fill = brush.color
|
94 |
+
elif isinstance(pen, Brush):
|
95 |
+
fill = pen.color
|
96 |
+
# handle transformation
|
97 |
+
if self.transform:
|
98 |
+
xy = ImagePath.Path(xy)
|
99 |
+
xy.transform(self.transform)
|
100 |
+
# render the item
|
101 |
+
if op == "line":
|
102 |
+
self.draw.line(xy, fill=outline, width=width)
|
103 |
+
else:
|
104 |
+
getattr(self.draw, op)(xy, fill=fill, outline=outline)
|
105 |
+
|
106 |
+
def settransform(self, offset):
|
107 |
+
"""Sets a transformation offset."""
|
108 |
+
(xoffset, yoffset) = offset
|
109 |
+
self.transform = (1, 0, xoffset, 0, 1, yoffset)
|
110 |
+
|
111 |
+
def arc(self, xy, start, end, *options):
|
112 |
+
"""
|
113 |
+
Draws an arc (a portion of a circle outline) between the start and end
|
114 |
+
angles, inside the given bounding box.
|
115 |
+
|
116 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
117 |
+
"""
|
118 |
+
self.render("arc", xy, start, end, *options)
|
119 |
+
|
120 |
+
def chord(self, xy, start, end, *options):
|
121 |
+
"""
|
122 |
+
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
|
123 |
+
with a straight line.
|
124 |
+
|
125 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
126 |
+
"""
|
127 |
+
self.render("chord", xy, start, end, *options)
|
128 |
+
|
129 |
+
def ellipse(self, xy, *options):
|
130 |
+
"""
|
131 |
+
Draws an ellipse inside the given bounding box.
|
132 |
+
|
133 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
134 |
+
"""
|
135 |
+
self.render("ellipse", xy, *options)
|
136 |
+
|
137 |
+
def line(self, xy, *options):
|
138 |
+
"""
|
139 |
+
Draws a line between the coordinates in the ``xy`` list.
|
140 |
+
|
141 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
142 |
+
"""
|
143 |
+
self.render("line", xy, *options)
|
144 |
+
|
145 |
+
def pieslice(self, xy, start, end, *options):
|
146 |
+
"""
|
147 |
+
Same as arc, but also draws straight lines between the end points and the
|
148 |
+
center of the bounding box.
|
149 |
+
|
150 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
151 |
+
"""
|
152 |
+
self.render("pieslice", xy, start, end, *options)
|
153 |
+
|
154 |
+
def polygon(self, xy, *options):
|
155 |
+
"""
|
156 |
+
Draws a polygon.
|
157 |
+
|
158 |
+
The polygon outline consists of straight lines between the given
|
159 |
+
coordinates, plus a straight line between the last and the first
|
160 |
+
coordinate.
|
161 |
+
|
162 |
+
|
163 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
164 |
+
"""
|
165 |
+
self.render("polygon", xy, *options)
|
166 |
+
|
167 |
+
def rectangle(self, xy, *options):
|
168 |
+
"""
|
169 |
+
Draws a rectangle.
|
170 |
+
|
171 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
172 |
+
"""
|
173 |
+
self.render("rectangle", xy, *options)
|
174 |
+
|
175 |
+
def text(self, xy, text, font):
|
176 |
+
"""
|
177 |
+
Draws the string at the given position.
|
178 |
+
|
179 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
180 |
+
"""
|
181 |
+
if self.transform:
|
182 |
+
xy = ImagePath.Path(xy)
|
183 |
+
xy.transform(self.transform)
|
184 |
+
self.draw.text(xy, text, font=font.font, fill=font.color)
|
185 |
+
|
186 |
+
def textbbox(self, xy, text, font):
|
187 |
+
"""
|
188 |
+
Returns bounding box (in pixels) of given text.
|
189 |
+
|
190 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
191 |
+
|
192 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
|
193 |
+
"""
|
194 |
+
if self.transform:
|
195 |
+
xy = ImagePath.Path(xy)
|
196 |
+
xy.transform(self.transform)
|
197 |
+
return self.draw.textbbox(xy, text, font=font.font)
|
198 |
+
|
199 |
+
def textlength(self, text, font):
|
200 |
+
"""
|
201 |
+
Returns length (in pixels) of given text.
|
202 |
+
This is the amount by which following text should be offset.
|
203 |
+
|
204 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
|
205 |
+
"""
|
206 |
+
return self.draw.textlength(text, font=font.font)
|
MLPY/Lib/site-packages/PIL/ImageEnhance.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# image enhancement classes
|
6 |
+
#
|
7 |
+
# For a background, see "Image Processing By Interpolation and
|
8 |
+
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
|
9 |
+
# at http://www.graficaobscura.com/interp/index.html
|
10 |
+
#
|
11 |
+
# History:
|
12 |
+
# 1996-03-23 fl Created
|
13 |
+
# 2009-06-16 fl Fixed mean calculation
|
14 |
+
#
|
15 |
+
# Copyright (c) Secret Labs AB 1997.
|
16 |
+
# Copyright (c) Fredrik Lundh 1996.
|
17 |
+
#
|
18 |
+
# See the README file for information on usage and redistribution.
|
19 |
+
#
|
20 |
+
from __future__ import annotations
|
21 |
+
|
22 |
+
from . import Image, ImageFilter, ImageStat
|
23 |
+
|
24 |
+
|
25 |
+
class _Enhance:
|
26 |
+
image: Image.Image
|
27 |
+
degenerate: Image.Image
|
28 |
+
|
29 |
+
def enhance(self, factor: float) -> Image.Image:
|
30 |
+
"""
|
31 |
+
Returns an enhanced image.
|
32 |
+
|
33 |
+
:param factor: A floating point value controlling the enhancement.
|
34 |
+
Factor 1.0 always returns a copy of the original image,
|
35 |
+
lower factors mean less color (brightness, contrast,
|
36 |
+
etc), and higher values more. There are no restrictions
|
37 |
+
on this value.
|
38 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
39 |
+
"""
|
40 |
+
return Image.blend(self.degenerate, self.image, factor)
|
41 |
+
|
42 |
+
|
43 |
+
class Color(_Enhance):
|
44 |
+
"""Adjust image color balance.
|
45 |
+
|
46 |
+
This class can be used to adjust the colour balance of an image, in
|
47 |
+
a manner similar to the controls on a colour TV set. An enhancement
|
48 |
+
factor of 0.0 gives a black and white image. A factor of 1.0 gives
|
49 |
+
the original image.
|
50 |
+
"""
|
51 |
+
|
52 |
+
def __init__(self, image: Image.Image) -> None:
|
53 |
+
self.image = image
|
54 |
+
self.intermediate_mode = "L"
|
55 |
+
if "A" in image.getbands():
|
56 |
+
self.intermediate_mode = "LA"
|
57 |
+
|
58 |
+
self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
|
59 |
+
|
60 |
+
|
61 |
+
class Contrast(_Enhance):
|
62 |
+
"""Adjust image contrast.
|
63 |
+
|
64 |
+
This class can be used to control the contrast of an image, similar
|
65 |
+
to the contrast control on a TV set. An enhancement factor of 0.0
|
66 |
+
gives a solid gray image. A factor of 1.0 gives the original image.
|
67 |
+
"""
|
68 |
+
|
69 |
+
def __init__(self, image: Image.Image) -> None:
|
70 |
+
self.image = image
|
71 |
+
mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
|
72 |
+
self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
|
73 |
+
|
74 |
+
if "A" in image.getbands():
|
75 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
76 |
+
|
77 |
+
|
78 |
+
class Brightness(_Enhance):
|
79 |
+
"""Adjust image brightness.
|
80 |
+
|
81 |
+
This class can be used to control the brightness of an image. An
|
82 |
+
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
|
83 |
+
original image.
|
84 |
+
"""
|
85 |
+
|
86 |
+
def __init__(self, image: Image.Image) -> None:
|
87 |
+
self.image = image
|
88 |
+
self.degenerate = Image.new(image.mode, image.size, 0)
|
89 |
+
|
90 |
+
if "A" in image.getbands():
|
91 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
92 |
+
|
93 |
+
|
94 |
+
class Sharpness(_Enhance):
|
95 |
+
"""Adjust image sharpness.
|
96 |
+
|
97 |
+
This class can be used to adjust the sharpness of an image. An
|
98 |
+
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
|
99 |
+
original image, and a factor of 2.0 gives a sharpened image.
|
100 |
+
"""
|
101 |
+
|
102 |
+
def __init__(self, image: Image.Image) -> None:
|
103 |
+
self.image = image
|
104 |
+
self.degenerate = image.filter(ImageFilter.SMOOTH)
|
105 |
+
|
106 |
+
if "A" in image.getbands():
|
107 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
MLPY/Lib/site-packages/PIL/ImageFile.py
ADDED
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# base class for image file handlers
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 1995-09-09 fl Created
|
9 |
+
# 1996-03-11 fl Fixed load mechanism.
|
10 |
+
# 1996-04-15 fl Added pcx/xbm decoders.
|
11 |
+
# 1996-04-30 fl Added encoders.
|
12 |
+
# 1996-12-14 fl Added load helpers
|
13 |
+
# 1997-01-11 fl Use encode_to_file where possible
|
14 |
+
# 1997-08-27 fl Flush output in _save
|
15 |
+
# 1998-03-05 fl Use memory mapping for some modes
|
16 |
+
# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
|
17 |
+
# 1999-05-31 fl Added image parser
|
18 |
+
# 2000-10-12 fl Set readonly flag on memory-mapped images
|
19 |
+
# 2002-03-20 fl Use better messages for common decoder errors
|
20 |
+
# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
|
21 |
+
# 2003-10-30 fl Added StubImageFile class
|
22 |
+
# 2004-02-25 fl Made incremental parser more robust
|
23 |
+
#
|
24 |
+
# Copyright (c) 1997-2004 by Secret Labs AB
|
25 |
+
# Copyright (c) 1995-2004 by Fredrik Lundh
|
26 |
+
#
|
27 |
+
# See the README file for information on usage and redistribution.
|
28 |
+
#
|
29 |
+
from __future__ import annotations
|
30 |
+
|
31 |
+
import abc
|
32 |
+
import io
|
33 |
+
import itertools
|
34 |
+
import struct
|
35 |
+
import sys
|
36 |
+
from typing import IO, Any, NamedTuple
|
37 |
+
|
38 |
+
from . import Image
|
39 |
+
from ._deprecate import deprecate
|
40 |
+
from ._util import is_path
|
41 |
+
|
42 |
+
MAXBLOCK = 65536
|
43 |
+
|
44 |
+
SAFEBLOCK = 1024 * 1024
|
45 |
+
|
46 |
+
LOAD_TRUNCATED_IMAGES = False
|
47 |
+
"""Whether or not to load truncated image files. User code may change this."""
|
48 |
+
|
49 |
+
ERRORS = {
|
50 |
+
-1: "image buffer overrun error",
|
51 |
+
-2: "decoding error",
|
52 |
+
-3: "unknown error",
|
53 |
+
-8: "bad configuration",
|
54 |
+
-9: "out of memory error",
|
55 |
+
}
|
56 |
+
"""
|
57 |
+
Dict of known error codes returned from :meth:`.PyDecoder.decode`,
|
58 |
+
:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
|
59 |
+
:meth:`.PyEncoder.encode_to_file`.
|
60 |
+
"""
|
61 |
+
|
62 |
+
|
63 |
+
#
|
64 |
+
# --------------------------------------------------------------------
|
65 |
+
# Helpers
|
66 |
+
|
67 |
+
|
68 |
+
def _get_oserror(error: int, *, encoder: bool) -> OSError:
|
69 |
+
try:
|
70 |
+
msg = Image.core.getcodecstatus(error)
|
71 |
+
except AttributeError:
|
72 |
+
msg = ERRORS.get(error)
|
73 |
+
if not msg:
|
74 |
+
msg = f"{'encoder' if encoder else 'decoder'} error {error}"
|
75 |
+
msg += f" when {'writing' if encoder else 'reading'} image file"
|
76 |
+
return OSError(msg)
|
77 |
+
|
78 |
+
|
79 |
+
def raise_oserror(error: int) -> OSError:
|
80 |
+
deprecate(
|
81 |
+
"raise_oserror",
|
82 |
+
12,
|
83 |
+
action="It is only useful for translating error codes returned by a codec's "
|
84 |
+
"decode() method, which ImageFile already does automatically.",
|
85 |
+
)
|
86 |
+
raise _get_oserror(error, encoder=False)
|
87 |
+
|
88 |
+
|
89 |
+
def _tilesort(t):
|
90 |
+
# sort on offset
|
91 |
+
return t[2]
|
92 |
+
|
93 |
+
|
94 |
+
class _Tile(NamedTuple):
|
95 |
+
codec_name: str
|
96 |
+
extents: tuple[int, int, int, int]
|
97 |
+
offset: int
|
98 |
+
args: tuple[Any, ...] | str | None
|
99 |
+
|
100 |
+
|
101 |
+
#
|
102 |
+
# --------------------------------------------------------------------
|
103 |
+
# ImageFile base class
|
104 |
+
|
105 |
+
|
106 |
+
class ImageFile(Image.Image):
|
107 |
+
"""Base class for image file format handlers."""
|
108 |
+
|
109 |
+
def __init__(self, fp=None, filename=None):
|
110 |
+
super().__init__()
|
111 |
+
|
112 |
+
self._min_frame = 0
|
113 |
+
|
114 |
+
self.custom_mimetype = None
|
115 |
+
|
116 |
+
self.tile = None
|
117 |
+
""" A list of tile descriptors, or ``None`` """
|
118 |
+
|
119 |
+
self.readonly = 1 # until we know better
|
120 |
+
|
121 |
+
self.decoderconfig = ()
|
122 |
+
self.decodermaxblock = MAXBLOCK
|
123 |
+
|
124 |
+
if is_path(fp):
|
125 |
+
# filename
|
126 |
+
self.fp = open(fp, "rb")
|
127 |
+
self.filename = fp
|
128 |
+
self._exclusive_fp = True
|
129 |
+
else:
|
130 |
+
# stream
|
131 |
+
self.fp = fp
|
132 |
+
self.filename = filename
|
133 |
+
# can be overridden
|
134 |
+
self._exclusive_fp = None
|
135 |
+
|
136 |
+
try:
|
137 |
+
try:
|
138 |
+
self._open()
|
139 |
+
except (
|
140 |
+
IndexError, # end of data
|
141 |
+
TypeError, # end of data (ord)
|
142 |
+
KeyError, # unsupported mode
|
143 |
+
EOFError, # got header but not the first frame
|
144 |
+
struct.error,
|
145 |
+
) as v:
|
146 |
+
raise SyntaxError(v) from v
|
147 |
+
|
148 |
+
if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
|
149 |
+
msg = "not identified by this driver"
|
150 |
+
raise SyntaxError(msg)
|
151 |
+
except BaseException:
|
152 |
+
# close the file only if we have opened it this constructor
|
153 |
+
if self._exclusive_fp:
|
154 |
+
self.fp.close()
|
155 |
+
raise
|
156 |
+
|
157 |
+
def get_format_mimetype(self) -> str | None:
|
158 |
+
if self.custom_mimetype:
|
159 |
+
return self.custom_mimetype
|
160 |
+
if self.format is not None:
|
161 |
+
return Image.MIME.get(self.format.upper())
|
162 |
+
return None
|
163 |
+
|
164 |
+
def __setstate__(self, state):
|
165 |
+
self.tile = []
|
166 |
+
super().__setstate__(state)
|
167 |
+
|
168 |
+
def verify(self) -> None:
|
169 |
+
"""Check file integrity"""
|
170 |
+
|
171 |
+
# raise exception if something's wrong. must be called
|
172 |
+
# directly after open, and closes file when finished.
|
173 |
+
if self._exclusive_fp:
|
174 |
+
self.fp.close()
|
175 |
+
self.fp = None
|
176 |
+
|
177 |
+
def load(self):
|
178 |
+
"""Load image data based on tile list"""
|
179 |
+
|
180 |
+
if self.tile is None:
|
181 |
+
msg = "cannot load this image"
|
182 |
+
raise OSError(msg)
|
183 |
+
|
184 |
+
pixel = Image.Image.load(self)
|
185 |
+
if not self.tile:
|
186 |
+
return pixel
|
187 |
+
|
188 |
+
self.map = None
|
189 |
+
use_mmap = self.filename and len(self.tile) == 1
|
190 |
+
# As of pypy 2.1.0, memory mapping was failing here.
|
191 |
+
use_mmap = use_mmap and not hasattr(sys, "pypy_version_info")
|
192 |
+
|
193 |
+
readonly = 0
|
194 |
+
|
195 |
+
# look for read/seek overrides
|
196 |
+
try:
|
197 |
+
read = self.load_read
|
198 |
+
# don't use mmap if there are custom read/seek functions
|
199 |
+
use_mmap = False
|
200 |
+
except AttributeError:
|
201 |
+
read = self.fp.read
|
202 |
+
|
203 |
+
try:
|
204 |
+
seek = self.load_seek
|
205 |
+
use_mmap = False
|
206 |
+
except AttributeError:
|
207 |
+
seek = self.fp.seek
|
208 |
+
|
209 |
+
if use_mmap:
|
210 |
+
# try memory mapping
|
211 |
+
decoder_name, extents, offset, args = self.tile[0]
|
212 |
+
if isinstance(args, str):
|
213 |
+
args = (args, 0, 1)
|
214 |
+
if (
|
215 |
+
decoder_name == "raw"
|
216 |
+
and len(args) >= 3
|
217 |
+
and args[0] == self.mode
|
218 |
+
and args[0] in Image._MAPMODES
|
219 |
+
):
|
220 |
+
try:
|
221 |
+
# use mmap, if possible
|
222 |
+
import mmap
|
223 |
+
|
224 |
+
with open(self.filename) as fp:
|
225 |
+
self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
|
226 |
+
if offset + self.size[1] * args[1] > self.map.size():
|
227 |
+
msg = "buffer is not large enough"
|
228 |
+
raise OSError(msg)
|
229 |
+
self.im = Image.core.map_buffer(
|
230 |
+
self.map, self.size, decoder_name, offset, args
|
231 |
+
)
|
232 |
+
readonly = 1
|
233 |
+
# After trashing self.im,
|
234 |
+
# we might need to reload the palette data.
|
235 |
+
if self.palette:
|
236 |
+
self.palette.dirty = 1
|
237 |
+
except (AttributeError, OSError, ImportError):
|
238 |
+
self.map = None
|
239 |
+
|
240 |
+
self.load_prepare()
|
241 |
+
err_code = -3 # initialize to unknown error
|
242 |
+
if not self.map:
|
243 |
+
# sort tiles in file order
|
244 |
+
self.tile.sort(key=_tilesort)
|
245 |
+
|
246 |
+
try:
|
247 |
+
# FIXME: This is a hack to handle TIFF's JpegTables tag.
|
248 |
+
prefix = self.tile_prefix
|
249 |
+
except AttributeError:
|
250 |
+
prefix = b""
|
251 |
+
|
252 |
+
# Remove consecutive duplicates that only differ by their offset
|
253 |
+
self.tile = [
|
254 |
+
list(tiles)[-1]
|
255 |
+
for _, tiles in itertools.groupby(
|
256 |
+
self.tile, lambda tile: (tile[0], tile[1], tile[3])
|
257 |
+
)
|
258 |
+
]
|
259 |
+
for decoder_name, extents, offset, args in self.tile:
|
260 |
+
seek(offset)
|
261 |
+
decoder = Image._getdecoder(
|
262 |
+
self.mode, decoder_name, args, self.decoderconfig
|
263 |
+
)
|
264 |
+
try:
|
265 |
+
decoder.setimage(self.im, extents)
|
266 |
+
if decoder.pulls_fd:
|
267 |
+
decoder.setfd(self.fp)
|
268 |
+
err_code = decoder.decode(b"")[1]
|
269 |
+
else:
|
270 |
+
b = prefix
|
271 |
+
while True:
|
272 |
+
try:
|
273 |
+
s = read(self.decodermaxblock)
|
274 |
+
except (IndexError, struct.error) as e:
|
275 |
+
# truncated png/gif
|
276 |
+
if LOAD_TRUNCATED_IMAGES:
|
277 |
+
break
|
278 |
+
else:
|
279 |
+
msg = "image file is truncated"
|
280 |
+
raise OSError(msg) from e
|
281 |
+
|
282 |
+
if not s: # truncated jpeg
|
283 |
+
if LOAD_TRUNCATED_IMAGES:
|
284 |
+
break
|
285 |
+
else:
|
286 |
+
msg = (
|
287 |
+
"image file is truncated "
|
288 |
+
f"({len(b)} bytes not processed)"
|
289 |
+
)
|
290 |
+
raise OSError(msg)
|
291 |
+
|
292 |
+
b = b + s
|
293 |
+
n, err_code = decoder.decode(b)
|
294 |
+
if n < 0:
|
295 |
+
break
|
296 |
+
b = b[n:]
|
297 |
+
finally:
|
298 |
+
# Need to cleanup here to prevent leaks
|
299 |
+
decoder.cleanup()
|
300 |
+
|
301 |
+
self.tile = []
|
302 |
+
self.readonly = readonly
|
303 |
+
|
304 |
+
self.load_end()
|
305 |
+
|
306 |
+
if self._exclusive_fp and self._close_exclusive_fp_after_loading:
|
307 |
+
self.fp.close()
|
308 |
+
self.fp = None
|
309 |
+
|
310 |
+
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
|
311 |
+
# still raised if decoder fails to return anything
|
312 |
+
raise _get_oserror(err_code, encoder=False)
|
313 |
+
|
314 |
+
return Image.Image.load(self)
|
315 |
+
|
316 |
+
def load_prepare(self) -> None:
|
317 |
+
# create image memory if necessary
|
318 |
+
if not self.im or self.im.mode != self.mode or self.im.size != self.size:
|
319 |
+
self.im = Image.core.new(self.mode, self.size)
|
320 |
+
# create palette (optional)
|
321 |
+
if self.mode == "P":
|
322 |
+
Image.Image.load(self)
|
323 |
+
|
324 |
+
def load_end(self) -> None:
|
325 |
+
# may be overridden
|
326 |
+
pass
|
327 |
+
|
328 |
+
# may be defined for contained formats
|
329 |
+
# def load_seek(self, pos: int) -> None:
|
330 |
+
# pass
|
331 |
+
|
332 |
+
# may be defined for blocked formats (e.g. PNG)
|
333 |
+
# def load_read(self, read_bytes: int) -> bytes:
|
334 |
+
# pass
|
335 |
+
|
336 |
+
def _seek_check(self, frame):
|
337 |
+
if (
|
338 |
+
frame < self._min_frame
|
339 |
+
# Only check upper limit on frames if additional seek operations
|
340 |
+
# are not required to do so
|
341 |
+
or (
|
342 |
+
not (hasattr(self, "_n_frames") and self._n_frames is None)
|
343 |
+
and frame >= self.n_frames + self._min_frame
|
344 |
+
)
|
345 |
+
):
|
346 |
+
msg = "attempt to seek outside sequence"
|
347 |
+
raise EOFError(msg)
|
348 |
+
|
349 |
+
return self.tell() != frame
|
350 |
+
|
351 |
+
|
352 |
+
class StubHandler:
|
353 |
+
def open(self, im: StubImageFile) -> None:
|
354 |
+
pass
|
355 |
+
|
356 |
+
@abc.abstractmethod
|
357 |
+
def load(self, im: StubImageFile) -> Image.Image:
|
358 |
+
pass
|
359 |
+
|
360 |
+
|
361 |
+
class StubImageFile(ImageFile):
|
362 |
+
"""
|
363 |
+
Base class for stub image loaders.
|
364 |
+
|
365 |
+
A stub loader is an image loader that can identify files of a
|
366 |
+
certain format, but relies on external code to load the file.
|
367 |
+
"""
|
368 |
+
|
369 |
+
def _open(self) -> None:
|
370 |
+
msg = "StubImageFile subclass must implement _open"
|
371 |
+
raise NotImplementedError(msg)
|
372 |
+
|
373 |
+
def load(self):
|
374 |
+
loader = self._load()
|
375 |
+
if loader is None:
|
376 |
+
msg = f"cannot find loader for this {self.format} file"
|
377 |
+
raise OSError(msg)
|
378 |
+
image = loader.load(self)
|
379 |
+
assert image is not None
|
380 |
+
# become the other object (!)
|
381 |
+
self.__class__ = image.__class__
|
382 |
+
self.__dict__ = image.__dict__
|
383 |
+
return image.load()
|
384 |
+
|
385 |
+
def _load(self) -> StubHandler | None:
|
386 |
+
"""(Hook) Find actual image loader."""
|
387 |
+
msg = "StubImageFile subclass must implement _load"
|
388 |
+
raise NotImplementedError(msg)
|
389 |
+
|
390 |
+
|
391 |
+
class Parser:
|
392 |
+
"""
|
393 |
+
Incremental image parser. This class implements the standard
|
394 |
+
feed/close consumer interface.
|
395 |
+
"""
|
396 |
+
|
397 |
+
incremental = None
|
398 |
+
image: Image.Image | None = None
|
399 |
+
data = None
|
400 |
+
decoder = None
|
401 |
+
offset = 0
|
402 |
+
finished = 0
|
403 |
+
|
404 |
+
def reset(self) -> None:
|
405 |
+
"""
|
406 |
+
(Consumer) Reset the parser. Note that you can only call this
|
407 |
+
method immediately after you've created a parser; parser
|
408 |
+
instances cannot be reused.
|
409 |
+
"""
|
410 |
+
assert self.data is None, "cannot reuse parsers"
|
411 |
+
|
412 |
+
def feed(self, data):
|
413 |
+
"""
|
414 |
+
(Consumer) Feed data to the parser.
|
415 |
+
|
416 |
+
:param data: A string buffer.
|
417 |
+
:exception OSError: If the parser failed to parse the image file.
|
418 |
+
"""
|
419 |
+
# collect data
|
420 |
+
|
421 |
+
if self.finished:
|
422 |
+
return
|
423 |
+
|
424 |
+
if self.data is None:
|
425 |
+
self.data = data
|
426 |
+
else:
|
427 |
+
self.data = self.data + data
|
428 |
+
|
429 |
+
# parse what we have
|
430 |
+
if self.decoder:
|
431 |
+
if self.offset > 0:
|
432 |
+
# skip header
|
433 |
+
skip = min(len(self.data), self.offset)
|
434 |
+
self.data = self.data[skip:]
|
435 |
+
self.offset = self.offset - skip
|
436 |
+
if self.offset > 0 or not self.data:
|
437 |
+
return
|
438 |
+
|
439 |
+
n, e = self.decoder.decode(self.data)
|
440 |
+
|
441 |
+
if n < 0:
|
442 |
+
# end of stream
|
443 |
+
self.data = None
|
444 |
+
self.finished = 1
|
445 |
+
if e < 0:
|
446 |
+
# decoding error
|
447 |
+
self.image = None
|
448 |
+
raise _get_oserror(e, encoder=False)
|
449 |
+
else:
|
450 |
+
# end of image
|
451 |
+
return
|
452 |
+
self.data = self.data[n:]
|
453 |
+
|
454 |
+
elif self.image:
|
455 |
+
# if we end up here with no decoder, this file cannot
|
456 |
+
# be incrementally parsed. wait until we've gotten all
|
457 |
+
# available data
|
458 |
+
pass
|
459 |
+
|
460 |
+
else:
|
461 |
+
# attempt to open this file
|
462 |
+
try:
|
463 |
+
with io.BytesIO(self.data) as fp:
|
464 |
+
im = Image.open(fp)
|
465 |
+
except OSError:
|
466 |
+
pass # not enough data
|
467 |
+
else:
|
468 |
+
flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
|
469 |
+
if flag or len(im.tile) != 1:
|
470 |
+
# custom load code, or multiple tiles
|
471 |
+
self.decode = None
|
472 |
+
else:
|
473 |
+
# initialize decoder
|
474 |
+
im.load_prepare()
|
475 |
+
d, e, o, a = im.tile[0]
|
476 |
+
im.tile = []
|
477 |
+
self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
|
478 |
+
self.decoder.setimage(im.im, e)
|
479 |
+
|
480 |
+
# calculate decoder offset
|
481 |
+
self.offset = o
|
482 |
+
if self.offset <= len(self.data):
|
483 |
+
self.data = self.data[self.offset :]
|
484 |
+
self.offset = 0
|
485 |
+
|
486 |
+
self.image = im
|
487 |
+
|
488 |
+
def __enter__(self):
|
489 |
+
return self
|
490 |
+
|
491 |
+
def __exit__(self, *args: object) -> None:
|
492 |
+
self.close()
|
493 |
+
|
494 |
+
def close(self):
|
495 |
+
"""
|
496 |
+
(Consumer) Close the stream.
|
497 |
+
|
498 |
+
:returns: An image object.
|
499 |
+
:exception OSError: If the parser failed to parse the image file either
|
500 |
+
because it cannot be identified or cannot be
|
501 |
+
decoded.
|
502 |
+
"""
|
503 |
+
# finish decoding
|
504 |
+
if self.decoder:
|
505 |
+
# get rid of what's left in the buffers
|
506 |
+
self.feed(b"")
|
507 |
+
self.data = self.decoder = None
|
508 |
+
if not self.finished:
|
509 |
+
msg = "image was incomplete"
|
510 |
+
raise OSError(msg)
|
511 |
+
if not self.image:
|
512 |
+
msg = "cannot parse this image"
|
513 |
+
raise OSError(msg)
|
514 |
+
if self.data:
|
515 |
+
# incremental parsing not possible; reopen the file
|
516 |
+
# not that we have all data
|
517 |
+
with io.BytesIO(self.data) as fp:
|
518 |
+
try:
|
519 |
+
self.image = Image.open(fp)
|
520 |
+
finally:
|
521 |
+
self.image.load()
|
522 |
+
return self.image
|
523 |
+
|
524 |
+
|
525 |
+
# --------------------------------------------------------------------
|
526 |
+
|
527 |
+
|
528 |
+
def _save(im, fp, tile, bufsize=0) -> None:
|
529 |
+
"""Helper to save image based on tile list
|
530 |
+
|
531 |
+
:param im: Image object.
|
532 |
+
:param fp: File object.
|
533 |
+
:param tile: Tile list.
|
534 |
+
:param bufsize: Optional buffer size
|
535 |
+
"""
|
536 |
+
|
537 |
+
im.load()
|
538 |
+
if not hasattr(im, "encoderconfig"):
|
539 |
+
im.encoderconfig = ()
|
540 |
+
tile.sort(key=_tilesort)
|
541 |
+
# FIXME: make MAXBLOCK a configuration parameter
|
542 |
+
# It would be great if we could have the encoder specify what it needs
|
543 |
+
# But, it would need at least the image size in most cases. RawEncode is
|
544 |
+
# a tricky case.
|
545 |
+
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
|
546 |
+
try:
|
547 |
+
fh = fp.fileno()
|
548 |
+
fp.flush()
|
549 |
+
_encode_tile(im, fp, tile, bufsize, fh)
|
550 |
+
except (AttributeError, io.UnsupportedOperation) as exc:
|
551 |
+
_encode_tile(im, fp, tile, bufsize, None, exc)
|
552 |
+
if hasattr(fp, "flush"):
|
553 |
+
fp.flush()
|
554 |
+
|
555 |
+
|
556 |
+
def _encode_tile(im, fp, tile: list[_Tile], bufsize, fh, exc=None):
|
557 |
+
for encoder_name, extents, offset, args in tile:
|
558 |
+
if offset > 0:
|
559 |
+
fp.seek(offset)
|
560 |
+
encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
|
561 |
+
try:
|
562 |
+
encoder.setimage(im.im, extents)
|
563 |
+
if encoder.pushes_fd:
|
564 |
+
encoder.setfd(fp)
|
565 |
+
errcode = encoder.encode_to_pyfd()[1]
|
566 |
+
else:
|
567 |
+
if exc:
|
568 |
+
# compress to Python file-compatible object
|
569 |
+
while True:
|
570 |
+
errcode, data = encoder.encode(bufsize)[1:]
|
571 |
+
fp.write(data)
|
572 |
+
if errcode:
|
573 |
+
break
|
574 |
+
else:
|
575 |
+
# slight speedup: compress to real file object
|
576 |
+
errcode = encoder.encode_to_file(fh, bufsize)
|
577 |
+
if errcode < 0:
|
578 |
+
raise _get_oserror(errcode, encoder=True) from exc
|
579 |
+
finally:
|
580 |
+
encoder.cleanup()
|
581 |
+
|
582 |
+
|
583 |
+
def _safe_read(fp, size):
|
584 |
+
"""
|
585 |
+
Reads large blocks in a safe way. Unlike fp.read(n), this function
|
586 |
+
doesn't trust the user. If the requested size is larger than
|
587 |
+
SAFEBLOCK, the file is read block by block.
|
588 |
+
|
589 |
+
:param fp: File handle. Must implement a <b>read</b> method.
|
590 |
+
:param size: Number of bytes to read.
|
591 |
+
:returns: A string containing <i>size</i> bytes of data.
|
592 |
+
|
593 |
+
Raises an OSError if the file is truncated and the read cannot be completed
|
594 |
+
|
595 |
+
"""
|
596 |
+
if size <= 0:
|
597 |
+
return b""
|
598 |
+
if size <= SAFEBLOCK:
|
599 |
+
data = fp.read(size)
|
600 |
+
if len(data) < size:
|
601 |
+
msg = "Truncated File Read"
|
602 |
+
raise OSError(msg)
|
603 |
+
return data
|
604 |
+
data = []
|
605 |
+
remaining_size = size
|
606 |
+
while remaining_size > 0:
|
607 |
+
block = fp.read(min(remaining_size, SAFEBLOCK))
|
608 |
+
if not block:
|
609 |
+
break
|
610 |
+
data.append(block)
|
611 |
+
remaining_size -= len(block)
|
612 |
+
if sum(len(d) for d in data) < size:
|
613 |
+
msg = "Truncated File Read"
|
614 |
+
raise OSError(msg)
|
615 |
+
return b"".join(data)
|
616 |
+
|
617 |
+
|
618 |
+
class PyCodecState:
|
619 |
+
def __init__(self) -> None:
|
620 |
+
self.xsize = 0
|
621 |
+
self.ysize = 0
|
622 |
+
self.xoff = 0
|
623 |
+
self.yoff = 0
|
624 |
+
|
625 |
+
def extents(self) -> tuple[int, int, int, int]:
|
626 |
+
return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
|
627 |
+
|
628 |
+
|
629 |
+
class PyCodec:
|
630 |
+
fd: IO[bytes] | None
|
631 |
+
|
632 |
+
def __init__(self, mode, *args):
|
633 |
+
self.im = None
|
634 |
+
self.state = PyCodecState()
|
635 |
+
self.fd = None
|
636 |
+
self.mode = mode
|
637 |
+
self.init(args)
|
638 |
+
|
639 |
+
def init(self, args):
|
640 |
+
"""
|
641 |
+
Override to perform codec specific initialization
|
642 |
+
|
643 |
+
:param args: Array of args items from the tile entry
|
644 |
+
:returns: None
|
645 |
+
"""
|
646 |
+
self.args = args
|
647 |
+
|
648 |
+
def cleanup(self) -> None:
|
649 |
+
"""
|
650 |
+
Override to perform codec specific cleanup
|
651 |
+
|
652 |
+
:returns: None
|
653 |
+
"""
|
654 |
+
pass
|
655 |
+
|
656 |
+
def setfd(self, fd):
|
657 |
+
"""
|
658 |
+
Called from ImageFile to set the Python file-like object
|
659 |
+
|
660 |
+
:param fd: A Python file-like object
|
661 |
+
:returns: None
|
662 |
+
"""
|
663 |
+
self.fd = fd
|
664 |
+
|
665 |
+
def setimage(self, im, extents: tuple[int, int, int, int] | None = None) -> None:
|
666 |
+
"""
|
667 |
+
Called from ImageFile to set the core output image for the codec
|
668 |
+
|
669 |
+
:param im: A core image object
|
670 |
+
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
|
671 |
+
for this tile
|
672 |
+
:returns: None
|
673 |
+
"""
|
674 |
+
|
675 |
+
# following c code
|
676 |
+
self.im = im
|
677 |
+
|
678 |
+
if extents:
|
679 |
+
(x0, y0, x1, y1) = extents
|
680 |
+
else:
|
681 |
+
(x0, y0, x1, y1) = (0, 0, 0, 0)
|
682 |
+
|
683 |
+
if x0 == 0 and x1 == 0:
|
684 |
+
self.state.xsize, self.state.ysize = self.im.size
|
685 |
+
else:
|
686 |
+
self.state.xoff = x0
|
687 |
+
self.state.yoff = y0
|
688 |
+
self.state.xsize = x1 - x0
|
689 |
+
self.state.ysize = y1 - y0
|
690 |
+
|
691 |
+
if self.state.xsize <= 0 or self.state.ysize <= 0:
|
692 |
+
msg = "Size cannot be negative"
|
693 |
+
raise ValueError(msg)
|
694 |
+
|
695 |
+
if (
|
696 |
+
self.state.xsize + self.state.xoff > self.im.size[0]
|
697 |
+
or self.state.ysize + self.state.yoff > self.im.size[1]
|
698 |
+
):
|
699 |
+
msg = "Tile cannot extend outside image"
|
700 |
+
raise ValueError(msg)
|
701 |
+
|
702 |
+
|
703 |
+
class PyDecoder(PyCodec):
|
704 |
+
"""
|
705 |
+
Python implementation of a format decoder. Override this class and
|
706 |
+
add the decoding logic in the :meth:`decode` method.
|
707 |
+
|
708 |
+
See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
|
709 |
+
"""
|
710 |
+
|
711 |
+
_pulls_fd = False
|
712 |
+
|
713 |
+
@property
|
714 |
+
def pulls_fd(self) -> bool:
|
715 |
+
return self._pulls_fd
|
716 |
+
|
717 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
718 |
+
"""
|
719 |
+
Override to perform the decoding process.
|
720 |
+
|
721 |
+
:param buffer: A bytes object with the data to be decoded.
|
722 |
+
:returns: A tuple of ``(bytes consumed, errcode)``.
|
723 |
+
If finished with decoding return -1 for the bytes consumed.
|
724 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
725 |
+
"""
|
726 |
+
msg = "unavailable in base decoder"
|
727 |
+
raise NotImplementedError(msg)
|
728 |
+
|
729 |
+
def set_as_raw(self, data: bytes, rawmode=None) -> None:
|
730 |
+
"""
|
731 |
+
Convenience method to set the internal image from a stream of raw data
|
732 |
+
|
733 |
+
:param data: Bytes to be set
|
734 |
+
:param rawmode: The rawmode to be used for the decoder.
|
735 |
+
If not specified, it will default to the mode of the image
|
736 |
+
:returns: None
|
737 |
+
"""
|
738 |
+
|
739 |
+
if not rawmode:
|
740 |
+
rawmode = self.mode
|
741 |
+
d = Image._getdecoder(self.mode, "raw", rawmode)
|
742 |
+
assert self.im is not None
|
743 |
+
d.setimage(self.im, self.state.extents())
|
744 |
+
s = d.decode(data)
|
745 |
+
|
746 |
+
if s[0] >= 0:
|
747 |
+
msg = "not enough image data"
|
748 |
+
raise ValueError(msg)
|
749 |
+
if s[1] != 0:
|
750 |
+
msg = "cannot decode image data"
|
751 |
+
raise ValueError(msg)
|
752 |
+
|
753 |
+
|
754 |
+
class PyEncoder(PyCodec):
|
755 |
+
"""
|
756 |
+
Python implementation of a format encoder. Override this class and
|
757 |
+
add the decoding logic in the :meth:`encode` method.
|
758 |
+
|
759 |
+
See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
|
760 |
+
"""
|
761 |
+
|
762 |
+
_pushes_fd = False
|
763 |
+
|
764 |
+
@property
|
765 |
+
def pushes_fd(self) -> bool:
|
766 |
+
return self._pushes_fd
|
767 |
+
|
768 |
+
def encode(self, bufsize: int) -> tuple[int, int, bytes]:
|
769 |
+
"""
|
770 |
+
Override to perform the encoding process.
|
771 |
+
|
772 |
+
:param bufsize: Buffer size.
|
773 |
+
:returns: A tuple of ``(bytes encoded, errcode, bytes)``.
|
774 |
+
If finished with encoding return 1 for the error code.
|
775 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
776 |
+
"""
|
777 |
+
msg = "unavailable in base encoder"
|
778 |
+
raise NotImplementedError(msg)
|
779 |
+
|
780 |
+
def encode_to_pyfd(self) -> tuple[int, int]:
|
781 |
+
"""
|
782 |
+
If ``pushes_fd`` is ``True``, then this method will be used,
|
783 |
+
and ``encode()`` will only be called once.
|
784 |
+
|
785 |
+
:returns: A tuple of ``(bytes consumed, errcode)``.
|
786 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
787 |
+
"""
|
788 |
+
if not self.pushes_fd:
|
789 |
+
return 0, -8 # bad configuration
|
790 |
+
bytes_consumed, errcode, data = self.encode(0)
|
791 |
+
if data:
|
792 |
+
assert self.fd is not None
|
793 |
+
self.fd.write(data)
|
794 |
+
return bytes_consumed, errcode
|
795 |
+
|
796 |
+
def encode_to_file(self, fh, bufsize):
|
797 |
+
"""
|
798 |
+
:param fh: File handle.
|
799 |
+
:param bufsize: Buffer size.
|
800 |
+
|
801 |
+
:returns: If finished successfully, return 0.
|
802 |
+
Otherwise, return an error code. Err codes are from
|
803 |
+
:data:`.ImageFile.ERRORS`.
|
804 |
+
"""
|
805 |
+
errcode = 0
|
806 |
+
while errcode == 0:
|
807 |
+
status, errcode, buf = self.encode(bufsize)
|
808 |
+
if status > 0:
|
809 |
+
fh.write(buf[status:])
|
810 |
+
return errcode
|
MLPY/Lib/site-packages/PIL/ImageFilter.py
ADDED
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# standard filters
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1995-11-27 fl Created
|
9 |
+
# 2002-06-08 fl Added rank and mode filters
|
10 |
+
# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
|
11 |
+
#
|
12 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
13 |
+
# Copyright (c) 1995-2002 by Fredrik Lundh.
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
import abc
|
20 |
+
import functools
|
21 |
+
from types import ModuleType
|
22 |
+
from typing import TYPE_CHECKING, Any, Callable, Sequence, cast
|
23 |
+
|
24 |
+
if TYPE_CHECKING:
|
25 |
+
from . import _imaging
|
26 |
+
from ._typing import NumpyArray
|
27 |
+
|
28 |
+
|
29 |
+
class Filter:
|
30 |
+
@abc.abstractmethod
|
31 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
32 |
+
pass
|
33 |
+
|
34 |
+
|
35 |
+
class MultibandFilter(Filter):
|
36 |
+
pass
|
37 |
+
|
38 |
+
|
39 |
+
class BuiltinFilter(MultibandFilter):
|
40 |
+
filterargs: tuple[Any, ...]
|
41 |
+
|
42 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
43 |
+
if image.mode == "P":
|
44 |
+
msg = "cannot filter palette images"
|
45 |
+
raise ValueError(msg)
|
46 |
+
return image.filter(*self.filterargs)
|
47 |
+
|
48 |
+
|
49 |
+
class Kernel(BuiltinFilter):
|
50 |
+
"""
|
51 |
+
Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
|
52 |
+
point kernels.
|
53 |
+
|
54 |
+
Kernels can only be applied to "L" and "RGB" images.
|
55 |
+
|
56 |
+
:param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
|
57 |
+
:param kernel: A sequence containing kernel weights. The kernel will be flipped
|
58 |
+
vertically before being applied to the image.
|
59 |
+
:param scale: Scale factor. If given, the result for each pixel is divided by this
|
60 |
+
value. The default is the sum of the kernel weights.
|
61 |
+
:param offset: Offset. If given, this value is added to the result, after it has
|
62 |
+
been divided by the scale factor.
|
63 |
+
"""
|
64 |
+
|
65 |
+
name = "Kernel"
|
66 |
+
|
67 |
+
def __init__(
|
68 |
+
self,
|
69 |
+
size: tuple[int, int],
|
70 |
+
kernel: Sequence[float],
|
71 |
+
scale: float | None = None,
|
72 |
+
offset: float = 0,
|
73 |
+
) -> None:
|
74 |
+
if scale is None:
|
75 |
+
# default scale is sum of kernel
|
76 |
+
scale = functools.reduce(lambda a, b: a + b, kernel)
|
77 |
+
if size[0] * size[1] != len(kernel):
|
78 |
+
msg = "not enough coefficients in kernel"
|
79 |
+
raise ValueError(msg)
|
80 |
+
self.filterargs = size, scale, offset, kernel
|
81 |
+
|
82 |
+
|
83 |
+
class RankFilter(Filter):
|
84 |
+
"""
|
85 |
+
Create a rank filter. The rank filter sorts all pixels in
|
86 |
+
a window of the given size, and returns the ``rank``'th value.
|
87 |
+
|
88 |
+
:param size: The kernel size, in pixels.
|
89 |
+
:param rank: What pixel value to pick. Use 0 for a min filter,
|
90 |
+
``size * size / 2`` for a median filter, ``size * size - 1``
|
91 |
+
for a max filter, etc.
|
92 |
+
"""
|
93 |
+
|
94 |
+
name = "Rank"
|
95 |
+
|
96 |
+
def __init__(self, size: int, rank: int) -> None:
|
97 |
+
self.size = size
|
98 |
+
self.rank = rank
|
99 |
+
|
100 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
101 |
+
if image.mode == "P":
|
102 |
+
msg = "cannot filter palette images"
|
103 |
+
raise ValueError(msg)
|
104 |
+
image = image.expand(self.size // 2, self.size // 2)
|
105 |
+
return image.rankfilter(self.size, self.rank)
|
106 |
+
|
107 |
+
|
108 |
+
class MedianFilter(RankFilter):
|
109 |
+
"""
|
110 |
+
Create a median filter. Picks the median pixel value in a window with the
|
111 |
+
given size.
|
112 |
+
|
113 |
+
:param size: The kernel size, in pixels.
|
114 |
+
"""
|
115 |
+
|
116 |
+
name = "Median"
|
117 |
+
|
118 |
+
def __init__(self, size: int = 3) -> None:
|
119 |
+
self.size = size
|
120 |
+
self.rank = size * size // 2
|
121 |
+
|
122 |
+
|
123 |
+
class MinFilter(RankFilter):
|
124 |
+
"""
|
125 |
+
Create a min filter. Picks the lowest pixel value in a window with the
|
126 |
+
given size.
|
127 |
+
|
128 |
+
:param size: The kernel size, in pixels.
|
129 |
+
"""
|
130 |
+
|
131 |
+
name = "Min"
|
132 |
+
|
133 |
+
def __init__(self, size: int = 3) -> None:
|
134 |
+
self.size = size
|
135 |
+
self.rank = 0
|
136 |
+
|
137 |
+
|
138 |
+
class MaxFilter(RankFilter):
|
139 |
+
"""
|
140 |
+
Create a max filter. Picks the largest pixel value in a window with the
|
141 |
+
given size.
|
142 |
+
|
143 |
+
:param size: The kernel size, in pixels.
|
144 |
+
"""
|
145 |
+
|
146 |
+
name = "Max"
|
147 |
+
|
148 |
+
def __init__(self, size: int = 3) -> None:
|
149 |
+
self.size = size
|
150 |
+
self.rank = size * size - 1
|
151 |
+
|
152 |
+
|
153 |
+
class ModeFilter(Filter):
|
154 |
+
"""
|
155 |
+
Create a mode filter. Picks the most frequent pixel value in a box with the
|
156 |
+
given size. Pixel values that occur only once or twice are ignored; if no
|
157 |
+
pixel value occurs more than twice, the original pixel value is preserved.
|
158 |
+
|
159 |
+
:param size: The kernel size, in pixels.
|
160 |
+
"""
|
161 |
+
|
162 |
+
name = "Mode"
|
163 |
+
|
164 |
+
def __init__(self, size: int = 3) -> None:
|
165 |
+
self.size = size
|
166 |
+
|
167 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
168 |
+
return image.modefilter(self.size)
|
169 |
+
|
170 |
+
|
171 |
+
class GaussianBlur(MultibandFilter):
|
172 |
+
"""Blurs the image with a sequence of extended box filters, which
|
173 |
+
approximates a Gaussian kernel. For details on accuracy see
|
174 |
+
<https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
|
175 |
+
|
176 |
+
:param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
|
177 |
+
numbers for x and y, or a single number for both.
|
178 |
+
"""
|
179 |
+
|
180 |
+
name = "GaussianBlur"
|
181 |
+
|
182 |
+
def __init__(self, radius: float | Sequence[float] = 2) -> None:
|
183 |
+
self.radius = radius
|
184 |
+
|
185 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
186 |
+
xy = self.radius
|
187 |
+
if isinstance(xy, (int, float)):
|
188 |
+
xy = (xy, xy)
|
189 |
+
if xy == (0, 0):
|
190 |
+
return image.copy()
|
191 |
+
return image.gaussian_blur(xy)
|
192 |
+
|
193 |
+
|
194 |
+
class BoxBlur(MultibandFilter):
|
195 |
+
"""Blurs the image by setting each pixel to the average value of the pixels
|
196 |
+
in a square box extending radius pixels in each direction.
|
197 |
+
Supports float radius of arbitrary size. Uses an optimized implementation
|
198 |
+
which runs in linear time relative to the size of the image
|
199 |
+
for any radius value.
|
200 |
+
|
201 |
+
:param radius: Size of the box in a direction. Either a sequence of two numbers for
|
202 |
+
x and y, or a single number for both.
|
203 |
+
|
204 |
+
Radius 0 does not blur, returns an identical image.
|
205 |
+
Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
|
206 |
+
"""
|
207 |
+
|
208 |
+
name = "BoxBlur"
|
209 |
+
|
210 |
+
def __init__(self, radius: float | Sequence[float]) -> None:
|
211 |
+
xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
|
212 |
+
if xy[0] < 0 or xy[1] < 0:
|
213 |
+
msg = "radius must be >= 0"
|
214 |
+
raise ValueError(msg)
|
215 |
+
self.radius = radius
|
216 |
+
|
217 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
218 |
+
xy = self.radius
|
219 |
+
if isinstance(xy, (int, float)):
|
220 |
+
xy = (xy, xy)
|
221 |
+
if xy == (0, 0):
|
222 |
+
return image.copy()
|
223 |
+
return image.box_blur(xy)
|
224 |
+
|
225 |
+
|
226 |
+
class UnsharpMask(MultibandFilter):
|
227 |
+
"""Unsharp mask filter.
|
228 |
+
|
229 |
+
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
|
230 |
+
the parameters.
|
231 |
+
|
232 |
+
:param radius: Blur Radius
|
233 |
+
:param percent: Unsharp strength, in percent
|
234 |
+
:param threshold: Threshold controls the minimum brightness change that
|
235 |
+
will be sharpened
|
236 |
+
|
237 |
+
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
|
238 |
+
|
239 |
+
"""
|
240 |
+
|
241 |
+
name = "UnsharpMask"
|
242 |
+
|
243 |
+
def __init__(
|
244 |
+
self, radius: float = 2, percent: int = 150, threshold: int = 3
|
245 |
+
) -> None:
|
246 |
+
self.radius = radius
|
247 |
+
self.percent = percent
|
248 |
+
self.threshold = threshold
|
249 |
+
|
250 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
251 |
+
return image.unsharp_mask(self.radius, self.percent, self.threshold)
|
252 |
+
|
253 |
+
|
254 |
+
class BLUR(BuiltinFilter):
|
255 |
+
name = "Blur"
|
256 |
+
# fmt: off
|
257 |
+
filterargs = (5, 5), 16, 0, (
|
258 |
+
1, 1, 1, 1, 1,
|
259 |
+
1, 0, 0, 0, 1,
|
260 |
+
1, 0, 0, 0, 1,
|
261 |
+
1, 0, 0, 0, 1,
|
262 |
+
1, 1, 1, 1, 1,
|
263 |
+
)
|
264 |
+
# fmt: on
|
265 |
+
|
266 |
+
|
267 |
+
class CONTOUR(BuiltinFilter):
|
268 |
+
name = "Contour"
|
269 |
+
# fmt: off
|
270 |
+
filterargs = (3, 3), 1, 255, (
|
271 |
+
-1, -1, -1,
|
272 |
+
-1, 8, -1,
|
273 |
+
-1, -1, -1,
|
274 |
+
)
|
275 |
+
# fmt: on
|
276 |
+
|
277 |
+
|
278 |
+
class DETAIL(BuiltinFilter):
|
279 |
+
name = "Detail"
|
280 |
+
# fmt: off
|
281 |
+
filterargs = (3, 3), 6, 0, (
|
282 |
+
0, -1, 0,
|
283 |
+
-1, 10, -1,
|
284 |
+
0, -1, 0,
|
285 |
+
)
|
286 |
+
# fmt: on
|
287 |
+
|
288 |
+
|
289 |
+
class EDGE_ENHANCE(BuiltinFilter):
|
290 |
+
name = "Edge-enhance"
|
291 |
+
# fmt: off
|
292 |
+
filterargs = (3, 3), 2, 0, (
|
293 |
+
-1, -1, -1,
|
294 |
+
-1, 10, -1,
|
295 |
+
-1, -1, -1,
|
296 |
+
)
|
297 |
+
# fmt: on
|
298 |
+
|
299 |
+
|
300 |
+
class EDGE_ENHANCE_MORE(BuiltinFilter):
|
301 |
+
name = "Edge-enhance More"
|
302 |
+
# fmt: off
|
303 |
+
filterargs = (3, 3), 1, 0, (
|
304 |
+
-1, -1, -1,
|
305 |
+
-1, 9, -1,
|
306 |
+
-1, -1, -1,
|
307 |
+
)
|
308 |
+
# fmt: on
|
309 |
+
|
310 |
+
|
311 |
+
class EMBOSS(BuiltinFilter):
|
312 |
+
name = "Emboss"
|
313 |
+
# fmt: off
|
314 |
+
filterargs = (3, 3), 1, 128, (
|
315 |
+
-1, 0, 0,
|
316 |
+
0, 1, 0,
|
317 |
+
0, 0, 0,
|
318 |
+
)
|
319 |
+
# fmt: on
|
320 |
+
|
321 |
+
|
322 |
+
class FIND_EDGES(BuiltinFilter):
|
323 |
+
name = "Find Edges"
|
324 |
+
# fmt: off
|
325 |
+
filterargs = (3, 3), 1, 0, (
|
326 |
+
-1, -1, -1,
|
327 |
+
-1, 8, -1,
|
328 |
+
-1, -1, -1,
|
329 |
+
)
|
330 |
+
# fmt: on
|
331 |
+
|
332 |
+
|
333 |
+
class SHARPEN(BuiltinFilter):
|
334 |
+
name = "Sharpen"
|
335 |
+
# fmt: off
|
336 |
+
filterargs = (3, 3), 16, 0, (
|
337 |
+
-2, -2, -2,
|
338 |
+
-2, 32, -2,
|
339 |
+
-2, -2, -2,
|
340 |
+
)
|
341 |
+
# fmt: on
|
342 |
+
|
343 |
+
|
344 |
+
class SMOOTH(BuiltinFilter):
|
345 |
+
name = "Smooth"
|
346 |
+
# fmt: off
|
347 |
+
filterargs = (3, 3), 13, 0, (
|
348 |
+
1, 1, 1,
|
349 |
+
1, 5, 1,
|
350 |
+
1, 1, 1,
|
351 |
+
)
|
352 |
+
# fmt: on
|
353 |
+
|
354 |
+
|
355 |
+
class SMOOTH_MORE(BuiltinFilter):
|
356 |
+
name = "Smooth More"
|
357 |
+
# fmt: off
|
358 |
+
filterargs = (5, 5), 100, 0, (
|
359 |
+
1, 1, 1, 1, 1,
|
360 |
+
1, 5, 5, 5, 1,
|
361 |
+
1, 5, 44, 5, 1,
|
362 |
+
1, 5, 5, 5, 1,
|
363 |
+
1, 1, 1, 1, 1,
|
364 |
+
)
|
365 |
+
# fmt: on
|
366 |
+
|
367 |
+
|
368 |
+
class Color3DLUT(MultibandFilter):
|
369 |
+
"""Three-dimensional color lookup table.
|
370 |
+
|
371 |
+
Transforms 3-channel pixels using the values of the channels as coordinates
|
372 |
+
in the 3D lookup table and interpolating the nearest elements.
|
373 |
+
|
374 |
+
This method allows you to apply almost any color transformation
|
375 |
+
in constant time by using pre-calculated decimated tables.
|
376 |
+
|
377 |
+
.. versionadded:: 5.2.0
|
378 |
+
|
379 |
+
:param size: Size of the table. One int or tuple of (int, int, int).
|
380 |
+
Minimal size in any dimension is 2, maximum is 65.
|
381 |
+
:param table: Flat lookup table. A list of ``channels * size**3``
|
382 |
+
float elements or a list of ``size**3`` channels-sized
|
383 |
+
tuples with floats. Channels are changed first,
|
384 |
+
then first dimension, then second, then third.
|
385 |
+
Value 0.0 corresponds lowest value of output, 1.0 highest.
|
386 |
+
:param channels: Number of channels in the table. Could be 3 or 4.
|
387 |
+
Default is 3.
|
388 |
+
:param target_mode: A mode for the result image. Should have not less
|
389 |
+
than ``channels`` channels. Default is ``None``,
|
390 |
+
which means that mode wouldn't be changed.
|
391 |
+
"""
|
392 |
+
|
393 |
+
name = "Color 3D LUT"
|
394 |
+
|
395 |
+
def __init__(
|
396 |
+
self,
|
397 |
+
size: int | tuple[int, int, int],
|
398 |
+
table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
|
399 |
+
channels: int = 3,
|
400 |
+
target_mode: str | None = None,
|
401 |
+
**kwargs: bool,
|
402 |
+
) -> None:
|
403 |
+
if channels not in (3, 4):
|
404 |
+
msg = "Only 3 or 4 output channels are supported"
|
405 |
+
raise ValueError(msg)
|
406 |
+
self.size = size = self._check_size(size)
|
407 |
+
self.channels = channels
|
408 |
+
self.mode = target_mode
|
409 |
+
|
410 |
+
# Hidden flag `_copy_table=False` could be used to avoid extra copying
|
411 |
+
# of the table if the table is specially made for the constructor.
|
412 |
+
copy_table = kwargs.get("_copy_table", True)
|
413 |
+
items = size[0] * size[1] * size[2]
|
414 |
+
wrong_size = False
|
415 |
+
|
416 |
+
numpy: ModuleType | None = None
|
417 |
+
if hasattr(table, "shape"):
|
418 |
+
try:
|
419 |
+
import numpy
|
420 |
+
except ImportError:
|
421 |
+
pass
|
422 |
+
|
423 |
+
if numpy and isinstance(table, numpy.ndarray):
|
424 |
+
numpy_table: NumpyArray = table
|
425 |
+
if copy_table:
|
426 |
+
numpy_table = numpy_table.copy()
|
427 |
+
|
428 |
+
if numpy_table.shape in [
|
429 |
+
(items * channels,),
|
430 |
+
(items, channels),
|
431 |
+
(size[2], size[1], size[0], channels),
|
432 |
+
]:
|
433 |
+
table = numpy_table.reshape(items * channels)
|
434 |
+
else:
|
435 |
+
wrong_size = True
|
436 |
+
|
437 |
+
else:
|
438 |
+
if copy_table:
|
439 |
+
table = list(table)
|
440 |
+
|
441 |
+
# Convert to a flat list
|
442 |
+
if table and isinstance(table[0], (list, tuple)):
|
443 |
+
raw_table = cast(Sequence[Sequence[int]], table)
|
444 |
+
flat_table: list[int] = []
|
445 |
+
for pixel in raw_table:
|
446 |
+
if len(pixel) != channels:
|
447 |
+
msg = (
|
448 |
+
"The elements of the table should "
|
449 |
+
f"have a length of {channels}."
|
450 |
+
)
|
451 |
+
raise ValueError(msg)
|
452 |
+
flat_table.extend(pixel)
|
453 |
+
table = flat_table
|
454 |
+
|
455 |
+
if wrong_size or len(table) != items * channels:
|
456 |
+
msg = (
|
457 |
+
"The table should have either channels * size**3 float items "
|
458 |
+
"or size**3 items of channels-sized tuples with floats. "
|
459 |
+
f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
|
460 |
+
f"Actual length: {len(table)}"
|
461 |
+
)
|
462 |
+
raise ValueError(msg)
|
463 |
+
self.table = table
|
464 |
+
|
465 |
+
@staticmethod
|
466 |
+
def _check_size(size: Any) -> tuple[int, int, int]:
|
467 |
+
try:
|
468 |
+
_, _, _ = size
|
469 |
+
except ValueError as e:
|
470 |
+
msg = "Size should be either an integer or a tuple of three integers."
|
471 |
+
raise ValueError(msg) from e
|
472 |
+
except TypeError:
|
473 |
+
size = (size, size, size)
|
474 |
+
size = tuple(int(x) for x in size)
|
475 |
+
for size_1d in size:
|
476 |
+
if not 2 <= size_1d <= 65:
|
477 |
+
msg = "Size should be in [2, 65] range."
|
478 |
+
raise ValueError(msg)
|
479 |
+
return size
|
480 |
+
|
481 |
+
@classmethod
|
482 |
+
def generate(
|
483 |
+
cls,
|
484 |
+
size: int | tuple[int, int, int],
|
485 |
+
callback: Callable[[float, float, float], tuple[float, ...]],
|
486 |
+
channels: int = 3,
|
487 |
+
target_mode: str | None = None,
|
488 |
+
) -> Color3DLUT:
|
489 |
+
"""Generates new LUT using provided callback.
|
490 |
+
|
491 |
+
:param size: Size of the table. Passed to the constructor.
|
492 |
+
:param callback: Function with three parameters which correspond
|
493 |
+
three color channels. Will be called ``size**3``
|
494 |
+
times with values from 0.0 to 1.0 and should return
|
495 |
+
a tuple with ``channels`` elements.
|
496 |
+
:param channels: The number of channels which should return callback.
|
497 |
+
:param target_mode: Passed to the constructor of the resulting
|
498 |
+
lookup table.
|
499 |
+
"""
|
500 |
+
size_1d, size_2d, size_3d = cls._check_size(size)
|
501 |
+
if channels not in (3, 4):
|
502 |
+
msg = "Only 3 or 4 output channels are supported"
|
503 |
+
raise ValueError(msg)
|
504 |
+
|
505 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
|
506 |
+
idx_out = 0
|
507 |
+
for b in range(size_3d):
|
508 |
+
for g in range(size_2d):
|
509 |
+
for r in range(size_1d):
|
510 |
+
table[idx_out : idx_out + channels] = callback(
|
511 |
+
r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
|
512 |
+
)
|
513 |
+
idx_out += channels
|
514 |
+
|
515 |
+
return cls(
|
516 |
+
(size_1d, size_2d, size_3d),
|
517 |
+
table,
|
518 |
+
channels=channels,
|
519 |
+
target_mode=target_mode,
|
520 |
+
_copy_table=False,
|
521 |
+
)
|
522 |
+
|
523 |
+
def transform(
|
524 |
+
self,
|
525 |
+
callback: Callable[..., tuple[float, ...]],
|
526 |
+
with_normals: bool = False,
|
527 |
+
channels: int | None = None,
|
528 |
+
target_mode: str | None = None,
|
529 |
+
) -> Color3DLUT:
|
530 |
+
"""Transforms the table values using provided callback and returns
|
531 |
+
a new LUT with altered values.
|
532 |
+
|
533 |
+
:param callback: A function which takes old lookup table values
|
534 |
+
and returns a new set of values. The number
|
535 |
+
of arguments which function should take is
|
536 |
+
``self.channels`` or ``3 + self.channels``
|
537 |
+
if ``with_normals`` flag is set.
|
538 |
+
Should return a tuple of ``self.channels`` or
|
539 |
+
``channels`` elements if it is set.
|
540 |
+
:param with_normals: If true, ``callback`` will be called with
|
541 |
+
coordinates in the color cube as the first
|
542 |
+
three arguments. Otherwise, ``callback``
|
543 |
+
will be called only with actual color values.
|
544 |
+
:param channels: The number of channels in the resulting lookup table.
|
545 |
+
:param target_mode: Passed to the constructor of the resulting
|
546 |
+
lookup table.
|
547 |
+
"""
|
548 |
+
if channels not in (None, 3, 4):
|
549 |
+
msg = "Only 3 or 4 output channels are supported"
|
550 |
+
raise ValueError(msg)
|
551 |
+
ch_in = self.channels
|
552 |
+
ch_out = channels or ch_in
|
553 |
+
size_1d, size_2d, size_3d = self.size
|
554 |
+
|
555 |
+
table = [0] * (size_1d * size_2d * size_3d * ch_out)
|
556 |
+
idx_in = 0
|
557 |
+
idx_out = 0
|
558 |
+
for b in range(size_3d):
|
559 |
+
for g in range(size_2d):
|
560 |
+
for r in range(size_1d):
|
561 |
+
values = self.table[idx_in : idx_in + ch_in]
|
562 |
+
if with_normals:
|
563 |
+
values = callback(
|
564 |
+
r / (size_1d - 1),
|
565 |
+
g / (size_2d - 1),
|
566 |
+
b / (size_3d - 1),
|
567 |
+
*values,
|
568 |
+
)
|
569 |
+
else:
|
570 |
+
values = callback(*values)
|
571 |
+
table[idx_out : idx_out + ch_out] = values
|
572 |
+
idx_in += ch_in
|
573 |
+
idx_out += ch_out
|
574 |
+
|
575 |
+
return type(self)(
|
576 |
+
self.size,
|
577 |
+
table,
|
578 |
+
channels=ch_out,
|
579 |
+
target_mode=target_mode or self.mode,
|
580 |
+
_copy_table=False,
|
581 |
+
)
|
582 |
+
|
583 |
+
def __repr__(self) -> str:
|
584 |
+
r = [
|
585 |
+
f"{self.__class__.__name__} from {self.table.__class__.__name__}",
|
586 |
+
"size={:d}x{:d}x{:d}".format(*self.size),
|
587 |
+
f"channels={self.channels:d}",
|
588 |
+
]
|
589 |
+
if self.mode:
|
590 |
+
r.append(f"target_mode={self.mode}")
|
591 |
+
return "<{}>".format(" ".join(r))
|
592 |
+
|
593 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
594 |
+
from . import Image
|
595 |
+
|
596 |
+
return image.color_lut_3d(
|
597 |
+
self.mode or image.mode,
|
598 |
+
Image.Resampling.BILINEAR,
|
599 |
+
self.channels,
|
600 |
+
self.size[0],
|
601 |
+
self.size[1],
|
602 |
+
self.size[2],
|
603 |
+
self.table,
|
604 |
+
)
|
MLPY/Lib/site-packages/PIL/ImageFont.py
ADDED
@@ -0,0 +1,1290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# PIL raster font management
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-08-07 fl created (experimental)
|
9 |
+
# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
|
10 |
+
# 1999-02-06 fl rewrote most font management stuff in C
|
11 |
+
# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
|
12 |
+
# 2001-02-17 fl added freetype support
|
13 |
+
# 2001-05-09 fl added TransposedFont wrapper class
|
14 |
+
# 2002-03-04 fl make sure we have a "L" or "1" font
|
15 |
+
# 2002-12-04 fl skip non-directory entries in the system path
|
16 |
+
# 2003-04-29 fl add embedded default font
|
17 |
+
# 2003-09-27 fl added support for truetype charmap encodings
|
18 |
+
#
|
19 |
+
# Todo:
|
20 |
+
# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
|
21 |
+
#
|
22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB
|
23 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
24 |
+
#
|
25 |
+
# See the README file for information on usage and redistribution.
|
26 |
+
#
|
27 |
+
|
28 |
+
from __future__ import annotations
|
29 |
+
|
30 |
+
import base64
|
31 |
+
import os
|
32 |
+
import sys
|
33 |
+
import warnings
|
34 |
+
from enum import IntEnum
|
35 |
+
from io import BytesIO
|
36 |
+
from types import ModuleType
|
37 |
+
from typing import IO, TYPE_CHECKING, Any, BinaryIO
|
38 |
+
|
39 |
+
from . import Image
|
40 |
+
from ._typing import StrOrBytesPath
|
41 |
+
from ._util import DeferredError, is_path
|
42 |
+
|
43 |
+
if TYPE_CHECKING:
|
44 |
+
from . import ImageFile
|
45 |
+
from ._imaging import ImagingFont
|
46 |
+
from ._imagingft import Font
|
47 |
+
|
48 |
+
|
49 |
+
class Layout(IntEnum):
|
50 |
+
BASIC = 0
|
51 |
+
RAQM = 1
|
52 |
+
|
53 |
+
|
54 |
+
MAX_STRING_LENGTH = 1_000_000
|
55 |
+
|
56 |
+
|
57 |
+
core: ModuleType | DeferredError
|
58 |
+
try:
|
59 |
+
from . import _imagingft as core
|
60 |
+
except ImportError as ex:
|
61 |
+
core = DeferredError.new(ex)
|
62 |
+
|
63 |
+
|
64 |
+
def _string_length_check(text: str | bytes | bytearray) -> None:
|
65 |
+
if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
|
66 |
+
msg = "too many characters in string"
|
67 |
+
raise ValueError(msg)
|
68 |
+
|
69 |
+
|
70 |
+
# FIXME: add support for pilfont2 format (see FontFile.py)
|
71 |
+
|
72 |
+
# --------------------------------------------------------------------
|
73 |
+
# Font metrics format:
|
74 |
+
# "PILfont" LF
|
75 |
+
# fontdescriptor LF
|
76 |
+
# (optional) key=value... LF
|
77 |
+
# "DATA" LF
|
78 |
+
# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
|
79 |
+
#
|
80 |
+
# To place a character, cut out srcbox and paste at dstbox,
|
81 |
+
# relative to the character position. Then move the character
|
82 |
+
# position according to dx, dy.
|
83 |
+
# --------------------------------------------------------------------
|
84 |
+
|
85 |
+
|
86 |
+
class ImageFont:
|
87 |
+
"""PIL font wrapper"""
|
88 |
+
|
89 |
+
font: ImagingFont
|
90 |
+
|
91 |
+
def _load_pilfont(self, filename: str) -> None:
|
92 |
+
with open(filename, "rb") as fp:
|
93 |
+
image: ImageFile.ImageFile | None = None
|
94 |
+
for ext in (".png", ".gif", ".pbm"):
|
95 |
+
if image:
|
96 |
+
image.close()
|
97 |
+
try:
|
98 |
+
fullname = os.path.splitext(filename)[0] + ext
|
99 |
+
image = Image.open(fullname)
|
100 |
+
except Exception:
|
101 |
+
pass
|
102 |
+
else:
|
103 |
+
if image and image.mode in ("1", "L"):
|
104 |
+
break
|
105 |
+
else:
|
106 |
+
if image:
|
107 |
+
image.close()
|
108 |
+
msg = "cannot find glyph data file"
|
109 |
+
raise OSError(msg)
|
110 |
+
|
111 |
+
self.file = fullname
|
112 |
+
|
113 |
+
self._load_pilfont_data(fp, image)
|
114 |
+
image.close()
|
115 |
+
|
116 |
+
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
|
117 |
+
# read PILfont header
|
118 |
+
if file.readline() != b"PILfont\n":
|
119 |
+
msg = "Not a PILfont file"
|
120 |
+
raise SyntaxError(msg)
|
121 |
+
file.readline().split(b";")
|
122 |
+
self.info = [] # FIXME: should be a dictionary
|
123 |
+
while True:
|
124 |
+
s = file.readline()
|
125 |
+
if not s or s == b"DATA\n":
|
126 |
+
break
|
127 |
+
self.info.append(s)
|
128 |
+
|
129 |
+
# read PILfont metrics
|
130 |
+
data = file.read(256 * 20)
|
131 |
+
|
132 |
+
# check image
|
133 |
+
if image.mode not in ("1", "L"):
|
134 |
+
msg = "invalid font image mode"
|
135 |
+
raise TypeError(msg)
|
136 |
+
|
137 |
+
image.load()
|
138 |
+
|
139 |
+
self.font = Image.core.font(image.im, data)
|
140 |
+
|
141 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
142 |
+
"""
|
143 |
+
Create a bitmap for the text.
|
144 |
+
|
145 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
146 |
+
maximum value of 255. Otherwise, it should have mode ``1``.
|
147 |
+
|
148 |
+
:param text: Text to render.
|
149 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
150 |
+
driver prefers; if empty, the renderer may return either
|
151 |
+
mode. Note that the mode is always a string, to simplify
|
152 |
+
C-level implementations.
|
153 |
+
|
154 |
+
.. versionadded:: 1.1.5
|
155 |
+
|
156 |
+
:return: An internal PIL storage memory instance as defined by the
|
157 |
+
:py:mod:`PIL.Image.core` interface module.
|
158 |
+
"""
|
159 |
+
_string_length_check(text)
|
160 |
+
Image._decompression_bomb_check(self.font.getsize(text))
|
161 |
+
return self.font.getmask(text, mode)
|
162 |
+
|
163 |
+
def getbbox(
|
164 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
165 |
+
) -> tuple[int, int, int, int]:
|
166 |
+
"""
|
167 |
+
Returns bounding box (in pixels) of given text.
|
168 |
+
|
169 |
+
.. versionadded:: 9.2.0
|
170 |
+
|
171 |
+
:param text: Text to render.
|
172 |
+
|
173 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
174 |
+
"""
|
175 |
+
_string_length_check(text)
|
176 |
+
width, height = self.font.getsize(text)
|
177 |
+
return 0, 0, width, height
|
178 |
+
|
179 |
+
def getlength(
|
180 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
181 |
+
) -> int:
|
182 |
+
"""
|
183 |
+
Returns length (in pixels) of given text.
|
184 |
+
This is the amount by which following text should be offset.
|
185 |
+
|
186 |
+
.. versionadded:: 9.2.0
|
187 |
+
"""
|
188 |
+
_string_length_check(text)
|
189 |
+
width, height = self.font.getsize(text)
|
190 |
+
return width
|
191 |
+
|
192 |
+
|
193 |
+
##
|
194 |
+
# Wrapper for FreeType fonts. Application code should use the
|
195 |
+
# <b>truetype</b> factory function to create font objects.
|
196 |
+
|
197 |
+
|
198 |
+
class FreeTypeFont:
|
199 |
+
"""FreeType font wrapper (requires _imagingft service)"""
|
200 |
+
|
201 |
+
font: Font
|
202 |
+
font_bytes: bytes
|
203 |
+
|
204 |
+
def __init__(
|
205 |
+
self,
|
206 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
207 |
+
size: float = 10,
|
208 |
+
index: int = 0,
|
209 |
+
encoding: str = "",
|
210 |
+
layout_engine: Layout | None = None,
|
211 |
+
) -> None:
|
212 |
+
# FIXME: use service provider instead
|
213 |
+
|
214 |
+
if isinstance(core, DeferredError):
|
215 |
+
raise core.ex
|
216 |
+
|
217 |
+
if size <= 0:
|
218 |
+
msg = "font size must be greater than 0"
|
219 |
+
raise ValueError(msg)
|
220 |
+
|
221 |
+
self.path = font
|
222 |
+
self.size = size
|
223 |
+
self.index = index
|
224 |
+
self.encoding = encoding
|
225 |
+
|
226 |
+
if layout_engine not in (Layout.BASIC, Layout.RAQM):
|
227 |
+
layout_engine = Layout.BASIC
|
228 |
+
if core.HAVE_RAQM:
|
229 |
+
layout_engine = Layout.RAQM
|
230 |
+
elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
|
231 |
+
warnings.warn(
|
232 |
+
"Raqm layout was requested, but Raqm is not available. "
|
233 |
+
"Falling back to basic layout."
|
234 |
+
)
|
235 |
+
layout_engine = Layout.BASIC
|
236 |
+
|
237 |
+
self.layout_engine = layout_engine
|
238 |
+
|
239 |
+
def load_from_bytes(f):
|
240 |
+
self.font_bytes = f.read()
|
241 |
+
self.font = core.getfont(
|
242 |
+
"", size, index, encoding, self.font_bytes, layout_engine
|
243 |
+
)
|
244 |
+
|
245 |
+
if is_path(font):
|
246 |
+
font = os.path.realpath(os.fspath(font))
|
247 |
+
if sys.platform == "win32":
|
248 |
+
font_bytes_path = font if isinstance(font, bytes) else font.encode()
|
249 |
+
try:
|
250 |
+
font_bytes_path.decode("ascii")
|
251 |
+
except UnicodeDecodeError:
|
252 |
+
# FreeType cannot load fonts with non-ASCII characters on Windows
|
253 |
+
# So load it into memory first
|
254 |
+
with open(font, "rb") as f:
|
255 |
+
load_from_bytes(f)
|
256 |
+
return
|
257 |
+
self.font = core.getfont(
|
258 |
+
font, size, index, encoding, layout_engine=layout_engine
|
259 |
+
)
|
260 |
+
else:
|
261 |
+
load_from_bytes(font)
|
262 |
+
|
263 |
+
def __getstate__(self):
|
264 |
+
return [self.path, self.size, self.index, self.encoding, self.layout_engine]
|
265 |
+
|
266 |
+
def __setstate__(self, state):
|
267 |
+
path, size, index, encoding, layout_engine = state
|
268 |
+
self.__init__(path, size, index, encoding, layout_engine)
|
269 |
+
|
270 |
+
def getname(self) -> tuple[str | None, str | None]:
|
271 |
+
"""
|
272 |
+
:return: A tuple of the font family (e.g. Helvetica) and the font style
|
273 |
+
(e.g. Bold)
|
274 |
+
"""
|
275 |
+
return self.font.family, self.font.style
|
276 |
+
|
277 |
+
def getmetrics(self) -> tuple[int, int]:
|
278 |
+
"""
|
279 |
+
:return: A tuple of the font ascent (the distance from the baseline to
|
280 |
+
the highest outline point) and descent (the distance from the
|
281 |
+
baseline to the lowest outline point, a negative value)
|
282 |
+
"""
|
283 |
+
return self.font.ascent, self.font.descent
|
284 |
+
|
285 |
+
def getlength(
|
286 |
+
self, text: str | bytes, mode="", direction=None, features=None, language=None
|
287 |
+
) -> float:
|
288 |
+
"""
|
289 |
+
Returns length (in pixels with 1/64 precision) of given text when rendered
|
290 |
+
in font with provided direction, features, and language.
|
291 |
+
|
292 |
+
This is the amount by which following text should be offset.
|
293 |
+
Text bounding box may extend past the length in some fonts,
|
294 |
+
e.g. when using italics or accents.
|
295 |
+
|
296 |
+
The result is returned as a float; it is a whole number if using basic layout.
|
297 |
+
|
298 |
+
Note that the sum of two lengths may not equal the length of a concatenated
|
299 |
+
string due to kerning. If you need to adjust for kerning, include the following
|
300 |
+
character and subtract its length.
|
301 |
+
|
302 |
+
For example, instead of ::
|
303 |
+
|
304 |
+
hello = font.getlength("Hello")
|
305 |
+
world = font.getlength("World")
|
306 |
+
hello_world = hello + world # not adjusted for kerning
|
307 |
+
assert hello_world == font.getlength("HelloWorld") # may fail
|
308 |
+
|
309 |
+
use ::
|
310 |
+
|
311 |
+
hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
|
312 |
+
world = font.getlength("World")
|
313 |
+
hello_world = hello + world # adjusted for kerning
|
314 |
+
assert hello_world == font.getlength("HelloWorld") # True
|
315 |
+
|
316 |
+
or disable kerning with (requires libraqm) ::
|
317 |
+
|
318 |
+
hello = draw.textlength("Hello", font, features=["-kern"])
|
319 |
+
world = draw.textlength("World", font, features=["-kern"])
|
320 |
+
hello_world = hello + world # kerning is disabled, no need to adjust
|
321 |
+
assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
|
322 |
+
|
323 |
+
.. versionadded:: 8.0.0
|
324 |
+
|
325 |
+
:param text: Text to measure.
|
326 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
327 |
+
driver prefers; if empty, the renderer may return either
|
328 |
+
mode. Note that the mode is always a string, to simplify
|
329 |
+
C-level implementations.
|
330 |
+
|
331 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
332 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
333 |
+
Requires libraqm.
|
334 |
+
|
335 |
+
:param features: A list of OpenType font features to be used during text
|
336 |
+
layout. This is usually used to turn on optional
|
337 |
+
font features that are not enabled by default,
|
338 |
+
for example 'dlig' or 'ss01', but can be also
|
339 |
+
used to turn off default font features for
|
340 |
+
example '-liga' to disable ligatures or '-kern'
|
341 |
+
to disable kerning. To get all supported
|
342 |
+
features, see
|
343 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
344 |
+
Requires libraqm.
|
345 |
+
|
346 |
+
:param language: Language of the text. Different languages may use
|
347 |
+
different glyph shapes or ligatures. This parameter tells
|
348 |
+
the font which language the text is in, and to apply the
|
349 |
+
correct substitutions as appropriate, if available.
|
350 |
+
It should be a `BCP 47 language code
|
351 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
352 |
+
Requires libraqm.
|
353 |
+
|
354 |
+
:return: Either width for horizontal text, or height for vertical text.
|
355 |
+
"""
|
356 |
+
_string_length_check(text)
|
357 |
+
return self.font.getlength(text, mode, direction, features, language) / 64
|
358 |
+
|
359 |
+
def getbbox(
|
360 |
+
self,
|
361 |
+
text: str | bytes,
|
362 |
+
mode: str = "",
|
363 |
+
direction: str | None = None,
|
364 |
+
features: list[str] | None = None,
|
365 |
+
language: str | None = None,
|
366 |
+
stroke_width: float = 0,
|
367 |
+
anchor: str | None = None,
|
368 |
+
) -> tuple[float, float, float, float]:
|
369 |
+
"""
|
370 |
+
Returns bounding box (in pixels) of given text relative to given anchor
|
371 |
+
when rendered in font with provided direction, features, and language.
|
372 |
+
|
373 |
+
Use :py:meth:`getlength()` to get the offset of following text with
|
374 |
+
1/64 pixel precision. The bounding box includes extra margins for
|
375 |
+
some fonts, e.g. italics or accents.
|
376 |
+
|
377 |
+
.. versionadded:: 8.0.0
|
378 |
+
|
379 |
+
:param text: Text to render.
|
380 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
381 |
+
driver prefers; if empty, the renderer may return either
|
382 |
+
mode. Note that the mode is always a string, to simplify
|
383 |
+
C-level implementations.
|
384 |
+
|
385 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
386 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
387 |
+
Requires libraqm.
|
388 |
+
|
389 |
+
:param features: A list of OpenType font features to be used during text
|
390 |
+
layout. This is usually used to turn on optional
|
391 |
+
font features that are not enabled by default,
|
392 |
+
for example 'dlig' or 'ss01', but can be also
|
393 |
+
used to turn off default font features for
|
394 |
+
example '-liga' to disable ligatures or '-kern'
|
395 |
+
to disable kerning. To get all supported
|
396 |
+
features, see
|
397 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
398 |
+
Requires libraqm.
|
399 |
+
|
400 |
+
:param language: Language of the text. Different languages may use
|
401 |
+
different glyph shapes or ligatures. This parameter tells
|
402 |
+
the font which language the text is in, and to apply the
|
403 |
+
correct substitutions as appropriate, if available.
|
404 |
+
It should be a `BCP 47 language code
|
405 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
406 |
+
Requires libraqm.
|
407 |
+
|
408 |
+
:param stroke_width: The width of the text stroke.
|
409 |
+
|
410 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
411 |
+
the anchor to the text. The default alignment is top left,
|
412 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
413 |
+
vertical text. See :ref:`text-anchors` for details.
|
414 |
+
|
415 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
416 |
+
"""
|
417 |
+
_string_length_check(text)
|
418 |
+
size, offset = self.font.getsize(
|
419 |
+
text, mode, direction, features, language, anchor
|
420 |
+
)
|
421 |
+
left, top = offset[0] - stroke_width, offset[1] - stroke_width
|
422 |
+
width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
|
423 |
+
return left, top, left + width, top + height
|
424 |
+
|
425 |
+
def getmask(
|
426 |
+
self,
|
427 |
+
text,
|
428 |
+
mode="",
|
429 |
+
direction=None,
|
430 |
+
features=None,
|
431 |
+
language=None,
|
432 |
+
stroke_width=0,
|
433 |
+
anchor=None,
|
434 |
+
ink=0,
|
435 |
+
start=None,
|
436 |
+
):
|
437 |
+
"""
|
438 |
+
Create a bitmap for the text.
|
439 |
+
|
440 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
441 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
442 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
443 |
+
|
444 |
+
:param text: Text to render.
|
445 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
446 |
+
driver prefers; if empty, the renderer may return either
|
447 |
+
mode. Note that the mode is always a string, to simplify
|
448 |
+
C-level implementations.
|
449 |
+
|
450 |
+
.. versionadded:: 1.1.5
|
451 |
+
|
452 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
453 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
454 |
+
Requires libraqm.
|
455 |
+
|
456 |
+
.. versionadded:: 4.2.0
|
457 |
+
|
458 |
+
:param features: A list of OpenType font features to be used during text
|
459 |
+
layout. This is usually used to turn on optional
|
460 |
+
font features that are not enabled by default,
|
461 |
+
for example 'dlig' or 'ss01', but can be also
|
462 |
+
used to turn off default font features for
|
463 |
+
example '-liga' to disable ligatures or '-kern'
|
464 |
+
to disable kerning. To get all supported
|
465 |
+
features, see
|
466 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
467 |
+
Requires libraqm.
|
468 |
+
|
469 |
+
.. versionadded:: 4.2.0
|
470 |
+
|
471 |
+
:param language: Language of the text. Different languages may use
|
472 |
+
different glyph shapes or ligatures. This parameter tells
|
473 |
+
the font which language the text is in, and to apply the
|
474 |
+
correct substitutions as appropriate, if available.
|
475 |
+
It should be a `BCP 47 language code
|
476 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
477 |
+
Requires libraqm.
|
478 |
+
|
479 |
+
.. versionadded:: 6.0.0
|
480 |
+
|
481 |
+
:param stroke_width: The width of the text stroke.
|
482 |
+
|
483 |
+
.. versionadded:: 6.2.0
|
484 |
+
|
485 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
486 |
+
the anchor to the text. The default alignment is top left,
|
487 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
488 |
+
vertical text. See :ref:`text-anchors` for details.
|
489 |
+
|
490 |
+
.. versionadded:: 8.0.0
|
491 |
+
|
492 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
493 |
+
|
494 |
+
.. versionadded:: 8.0.0
|
495 |
+
|
496 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
497 |
+
differently when starting at fractional coordinates.
|
498 |
+
|
499 |
+
.. versionadded:: 9.4.0
|
500 |
+
|
501 |
+
:return: An internal PIL storage memory instance as defined by the
|
502 |
+
:py:mod:`PIL.Image.core` interface module.
|
503 |
+
"""
|
504 |
+
return self.getmask2(
|
505 |
+
text,
|
506 |
+
mode,
|
507 |
+
direction=direction,
|
508 |
+
features=features,
|
509 |
+
language=language,
|
510 |
+
stroke_width=stroke_width,
|
511 |
+
anchor=anchor,
|
512 |
+
ink=ink,
|
513 |
+
start=start,
|
514 |
+
)[0]
|
515 |
+
|
516 |
+
def getmask2(
|
517 |
+
self,
|
518 |
+
text: str | bytes,
|
519 |
+
mode="",
|
520 |
+
direction=None,
|
521 |
+
features=None,
|
522 |
+
language=None,
|
523 |
+
stroke_width=0,
|
524 |
+
anchor=None,
|
525 |
+
ink=0,
|
526 |
+
start=None,
|
527 |
+
*args,
|
528 |
+
**kwargs,
|
529 |
+
):
|
530 |
+
"""
|
531 |
+
Create a bitmap for the text.
|
532 |
+
|
533 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
534 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
535 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
536 |
+
|
537 |
+
:param text: Text to render.
|
538 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
539 |
+
driver prefers; if empty, the renderer may return either
|
540 |
+
mode. Note that the mode is always a string, to simplify
|
541 |
+
C-level implementations.
|
542 |
+
|
543 |
+
.. versionadded:: 1.1.5
|
544 |
+
|
545 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
546 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
547 |
+
Requires libraqm.
|
548 |
+
|
549 |
+
.. versionadded:: 4.2.0
|
550 |
+
|
551 |
+
:param features: A list of OpenType font features to be used during text
|
552 |
+
layout. This is usually used to turn on optional
|
553 |
+
font features that are not enabled by default,
|
554 |
+
for example 'dlig' or 'ss01', but can be also
|
555 |
+
used to turn off default font features for
|
556 |
+
example '-liga' to disable ligatures or '-kern'
|
557 |
+
to disable kerning. To get all supported
|
558 |
+
features, see
|
559 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
560 |
+
Requires libraqm.
|
561 |
+
|
562 |
+
.. versionadded:: 4.2.0
|
563 |
+
|
564 |
+
:param language: Language of the text. Different languages may use
|
565 |
+
different glyph shapes or ligatures. This parameter tells
|
566 |
+
the font which language the text is in, and to apply the
|
567 |
+
correct substitutions as appropriate, if available.
|
568 |
+
It should be a `BCP 47 language code
|
569 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
570 |
+
Requires libraqm.
|
571 |
+
|
572 |
+
.. versionadded:: 6.0.0
|
573 |
+
|
574 |
+
:param stroke_width: The width of the text stroke.
|
575 |
+
|
576 |
+
.. versionadded:: 6.2.0
|
577 |
+
|
578 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
579 |
+
the anchor to the text. The default alignment is top left,
|
580 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
581 |
+
vertical text. See :ref:`text-anchors` for details.
|
582 |
+
|
583 |
+
.. versionadded:: 8.0.0
|
584 |
+
|
585 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
586 |
+
|
587 |
+
.. versionadded:: 8.0.0
|
588 |
+
|
589 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
590 |
+
differently when starting at fractional coordinates.
|
591 |
+
|
592 |
+
.. versionadded:: 9.4.0
|
593 |
+
|
594 |
+
:return: A tuple of an internal PIL storage memory instance as defined by the
|
595 |
+
:py:mod:`PIL.Image.core` interface module, and the text offset, the
|
596 |
+
gap between the starting coordinate and the first marking
|
597 |
+
"""
|
598 |
+
_string_length_check(text)
|
599 |
+
if start is None:
|
600 |
+
start = (0, 0)
|
601 |
+
|
602 |
+
def fill(width, height):
|
603 |
+
size = (width, height)
|
604 |
+
Image._decompression_bomb_check(size)
|
605 |
+
return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
|
606 |
+
|
607 |
+
return self.font.render(
|
608 |
+
text,
|
609 |
+
fill,
|
610 |
+
mode,
|
611 |
+
direction,
|
612 |
+
features,
|
613 |
+
language,
|
614 |
+
stroke_width,
|
615 |
+
anchor,
|
616 |
+
ink,
|
617 |
+
start[0],
|
618 |
+
start[1],
|
619 |
+
)
|
620 |
+
|
621 |
+
def font_variant(
|
622 |
+
self, font=None, size=None, index=None, encoding=None, layout_engine=None
|
623 |
+
):
|
624 |
+
"""
|
625 |
+
Create a copy of this FreeTypeFont object,
|
626 |
+
using any specified arguments to override the settings.
|
627 |
+
|
628 |
+
Parameters are identical to the parameters used to initialize this
|
629 |
+
object.
|
630 |
+
|
631 |
+
:return: A FreeTypeFont object.
|
632 |
+
"""
|
633 |
+
if font is None:
|
634 |
+
try:
|
635 |
+
font = BytesIO(self.font_bytes)
|
636 |
+
except AttributeError:
|
637 |
+
font = self.path
|
638 |
+
return FreeTypeFont(
|
639 |
+
font=font,
|
640 |
+
size=self.size if size is None else size,
|
641 |
+
index=self.index if index is None else index,
|
642 |
+
encoding=self.encoding if encoding is None else encoding,
|
643 |
+
layout_engine=layout_engine or self.layout_engine,
|
644 |
+
)
|
645 |
+
|
646 |
+
def get_variation_names(self) -> list[bytes]:
|
647 |
+
"""
|
648 |
+
:returns: A list of the named styles in a variation font.
|
649 |
+
:exception OSError: If the font is not a variation font.
|
650 |
+
"""
|
651 |
+
try:
|
652 |
+
names = self.font.getvarnames()
|
653 |
+
except AttributeError as e:
|
654 |
+
msg = "FreeType 2.9.1 or greater is required"
|
655 |
+
raise NotImplementedError(msg) from e
|
656 |
+
return [name.replace(b"\x00", b"") for name in names]
|
657 |
+
|
658 |
+
def set_variation_by_name(self, name):
|
659 |
+
"""
|
660 |
+
:param name: The name of the style.
|
661 |
+
:exception OSError: If the font is not a variation font.
|
662 |
+
"""
|
663 |
+
names = self.get_variation_names()
|
664 |
+
if not isinstance(name, bytes):
|
665 |
+
name = name.encode()
|
666 |
+
index = names.index(name) + 1
|
667 |
+
|
668 |
+
if index == getattr(self, "_last_variation_index", None):
|
669 |
+
# When the same name is set twice in a row,
|
670 |
+
# there is an 'unknown freetype error'
|
671 |
+
# https://savannah.nongnu.org/bugs/?56186
|
672 |
+
return
|
673 |
+
self._last_variation_index = index
|
674 |
+
|
675 |
+
self.font.setvarname(index)
|
676 |
+
|
677 |
+
def get_variation_axes(self):
|
678 |
+
"""
|
679 |
+
:returns: A list of the axes in a variation font.
|
680 |
+
:exception OSError: If the font is not a variation font.
|
681 |
+
"""
|
682 |
+
try:
|
683 |
+
axes = self.font.getvaraxes()
|
684 |
+
except AttributeError as e:
|
685 |
+
msg = "FreeType 2.9.1 or greater is required"
|
686 |
+
raise NotImplementedError(msg) from e
|
687 |
+
for axis in axes:
|
688 |
+
if axis["name"]:
|
689 |
+
axis["name"] = axis["name"].replace(b"\x00", b"")
|
690 |
+
return axes
|
691 |
+
|
692 |
+
def set_variation_by_axes(self, axes: list[float]) -> None:
|
693 |
+
"""
|
694 |
+
:param axes: A list of values for each axis.
|
695 |
+
:exception OSError: If the font is not a variation font.
|
696 |
+
"""
|
697 |
+
try:
|
698 |
+
self.font.setvaraxes(axes)
|
699 |
+
except AttributeError as e:
|
700 |
+
msg = "FreeType 2.9.1 or greater is required"
|
701 |
+
raise NotImplementedError(msg) from e
|
702 |
+
|
703 |
+
|
704 |
+
class TransposedFont:
|
705 |
+
"""Wrapper for writing rotated or mirrored text"""
|
706 |
+
|
707 |
+
def __init__(self, font, orientation=None):
|
708 |
+
"""
|
709 |
+
Wrapper that creates a transposed font from any existing font
|
710 |
+
object.
|
711 |
+
|
712 |
+
:param font: A font object.
|
713 |
+
:param orientation: An optional orientation. If given, this should
|
714 |
+
be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
|
715 |
+
Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
|
716 |
+
Image.Transpose.ROTATE_270.
|
717 |
+
"""
|
718 |
+
self.font = font
|
719 |
+
self.orientation = orientation # any 'transpose' argument, or None
|
720 |
+
|
721 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
722 |
+
im = self.font.getmask(text, mode, *args, **kwargs)
|
723 |
+
if self.orientation is not None:
|
724 |
+
return im.transpose(self.orientation)
|
725 |
+
return im
|
726 |
+
|
727 |
+
def getbbox(self, text, *args, **kwargs):
|
728 |
+
# TransposedFont doesn't support getmask2, move top-left point to (0, 0)
|
729 |
+
# this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
|
730 |
+
left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
|
731 |
+
width = right - left
|
732 |
+
height = bottom - top
|
733 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
734 |
+
return 0, 0, height, width
|
735 |
+
return 0, 0, width, height
|
736 |
+
|
737 |
+
def getlength(self, text: str | bytes, *args, **kwargs) -> float:
|
738 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
739 |
+
msg = "text length is undefined for text rotated by 90 or 270 degrees"
|
740 |
+
raise ValueError(msg)
|
741 |
+
return self.font.getlength(text, *args, **kwargs)
|
742 |
+
|
743 |
+
|
744 |
+
def load(filename: str) -> ImageFont:
|
745 |
+
"""
|
746 |
+
Load a font file. This function loads a font object from the given
|
747 |
+
bitmap font file, and returns the corresponding font object.
|
748 |
+
|
749 |
+
:param filename: Name of font file.
|
750 |
+
:return: A font object.
|
751 |
+
:exception OSError: If the file could not be read.
|
752 |
+
"""
|
753 |
+
f = ImageFont()
|
754 |
+
f._load_pilfont(filename)
|
755 |
+
return f
|
756 |
+
|
757 |
+
|
758 |
+
def truetype(
|
759 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
760 |
+
size: float = 10,
|
761 |
+
index: int = 0,
|
762 |
+
encoding: str = "",
|
763 |
+
layout_engine: Layout | None = None,
|
764 |
+
) -> FreeTypeFont:
|
765 |
+
"""
|
766 |
+
Load a TrueType or OpenType font from a file or file-like object,
|
767 |
+
and create a font object.
|
768 |
+
This function loads a font object from the given file or file-like
|
769 |
+
object, and creates a font object for a font of the given size.
|
770 |
+
|
771 |
+
Pillow uses FreeType to open font files. On Windows, be aware that FreeType
|
772 |
+
will keep the file open as long as the FreeTypeFont object exists. Windows
|
773 |
+
limits the number of files that can be open in C at once to 512, so if many
|
774 |
+
fonts are opened simultaneously and that limit is approached, an
|
775 |
+
``OSError`` may be thrown, reporting that FreeType "cannot open resource".
|
776 |
+
A workaround would be to copy the file(s) into memory, and open that instead.
|
777 |
+
|
778 |
+
This function requires the _imagingft service.
|
779 |
+
|
780 |
+
:param font: A filename or file-like object containing a TrueType font.
|
781 |
+
If the file is not found in this filename, the loader may also
|
782 |
+
search in other directories, such as:
|
783 |
+
|
784 |
+
* The :file:`fonts/` directory on Windows,
|
785 |
+
* :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
|
786 |
+
and :file:`~/Library/Fonts/` on macOS.
|
787 |
+
* :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
|
788 |
+
and :file:`/usr/share/fonts` on Linux; or those specified by
|
789 |
+
the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
|
790 |
+
for user-installed and system-wide fonts, respectively.
|
791 |
+
|
792 |
+
:param size: The requested size, in pixels.
|
793 |
+
:param index: Which font face to load (default is first available face).
|
794 |
+
:param encoding: Which font encoding to use (default is Unicode). Possible
|
795 |
+
encodings include (see the FreeType documentation for more
|
796 |
+
information):
|
797 |
+
|
798 |
+
* "unic" (Unicode)
|
799 |
+
* "symb" (Microsoft Symbol)
|
800 |
+
* "ADOB" (Adobe Standard)
|
801 |
+
* "ADBE" (Adobe Expert)
|
802 |
+
* "ADBC" (Adobe Custom)
|
803 |
+
* "armn" (Apple Roman)
|
804 |
+
* "sjis" (Shift JIS)
|
805 |
+
* "gb " (PRC)
|
806 |
+
* "big5"
|
807 |
+
* "wans" (Extended Wansung)
|
808 |
+
* "joha" (Johab)
|
809 |
+
* "lat1" (Latin-1)
|
810 |
+
|
811 |
+
This specifies the character set to use. It does not alter the
|
812 |
+
encoding of any text provided in subsequent operations.
|
813 |
+
:param layout_engine: Which layout engine to use, if available:
|
814 |
+
:attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
|
815 |
+
If it is available, Raqm layout will be used by default.
|
816 |
+
Otherwise, basic layout will be used.
|
817 |
+
|
818 |
+
Raqm layout is recommended for all non-English text. If Raqm layout
|
819 |
+
is not required, basic layout will have better performance.
|
820 |
+
|
821 |
+
You can check support for Raqm layout using
|
822 |
+
:py:func:`PIL.features.check_feature` with ``feature="raqm"``.
|
823 |
+
|
824 |
+
.. versionadded:: 4.2.0
|
825 |
+
:return: A font object.
|
826 |
+
:exception OSError: If the file could not be read.
|
827 |
+
:exception ValueError: If the font size is not greater than zero.
|
828 |
+
"""
|
829 |
+
|
830 |
+
def freetype(font: StrOrBytesPath | BinaryIO | None) -> FreeTypeFont:
|
831 |
+
return FreeTypeFont(font, size, index, encoding, layout_engine)
|
832 |
+
|
833 |
+
try:
|
834 |
+
return freetype(font)
|
835 |
+
except OSError:
|
836 |
+
if not is_path(font):
|
837 |
+
raise
|
838 |
+
ttf_filename = os.path.basename(font)
|
839 |
+
|
840 |
+
dirs = []
|
841 |
+
if sys.platform == "win32":
|
842 |
+
# check the windows font repository
|
843 |
+
# NOTE: must use uppercase WINDIR, to work around bugs in
|
844 |
+
# 1.5.2's os.environ.get()
|
845 |
+
windir = os.environ.get("WINDIR")
|
846 |
+
if windir:
|
847 |
+
dirs.append(os.path.join(windir, "fonts"))
|
848 |
+
elif sys.platform in ("linux", "linux2"):
|
849 |
+
data_home = os.environ.get("XDG_DATA_HOME")
|
850 |
+
if not data_home:
|
851 |
+
# The freedesktop spec defines the following default directory for
|
852 |
+
# when XDG_DATA_HOME is unset or empty. This user-level directory
|
853 |
+
# takes precedence over system-level directories.
|
854 |
+
data_home = os.path.expanduser("~/.local/share")
|
855 |
+
xdg_dirs = [data_home]
|
856 |
+
|
857 |
+
data_dirs = os.environ.get("XDG_DATA_DIRS")
|
858 |
+
if not data_dirs:
|
859 |
+
# Similarly, defaults are defined for the system-level directories
|
860 |
+
data_dirs = "/usr/local/share:/usr/share"
|
861 |
+
xdg_dirs += data_dirs.split(":")
|
862 |
+
|
863 |
+
dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
|
864 |
+
elif sys.platform == "darwin":
|
865 |
+
dirs += [
|
866 |
+
"/Library/Fonts",
|
867 |
+
"/System/Library/Fonts",
|
868 |
+
os.path.expanduser("~/Library/Fonts"),
|
869 |
+
]
|
870 |
+
|
871 |
+
ext = os.path.splitext(ttf_filename)[1]
|
872 |
+
first_font_with_a_different_extension = None
|
873 |
+
for directory in dirs:
|
874 |
+
for walkroot, walkdir, walkfilenames in os.walk(directory):
|
875 |
+
for walkfilename in walkfilenames:
|
876 |
+
if ext and walkfilename == ttf_filename:
|
877 |
+
return freetype(os.path.join(walkroot, walkfilename))
|
878 |
+
elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
|
879 |
+
fontpath = os.path.join(walkroot, walkfilename)
|
880 |
+
if os.path.splitext(fontpath)[1] == ".ttf":
|
881 |
+
return freetype(fontpath)
|
882 |
+
if not ext and first_font_with_a_different_extension is None:
|
883 |
+
first_font_with_a_different_extension = fontpath
|
884 |
+
if first_font_with_a_different_extension:
|
885 |
+
return freetype(first_font_with_a_different_extension)
|
886 |
+
raise
|
887 |
+
|
888 |
+
|
889 |
+
def load_path(filename: str | bytes) -> ImageFont:
|
890 |
+
"""
|
891 |
+
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
|
892 |
+
bitmap font along the Python path.
|
893 |
+
|
894 |
+
:param filename: Name of font file.
|
895 |
+
:return: A font object.
|
896 |
+
:exception OSError: If the file could not be read.
|
897 |
+
"""
|
898 |
+
if not isinstance(filename, str):
|
899 |
+
filename = filename.decode("utf-8")
|
900 |
+
for directory in sys.path:
|
901 |
+
try:
|
902 |
+
return load(os.path.join(directory, filename))
|
903 |
+
except OSError:
|
904 |
+
pass
|
905 |
+
msg = "cannot find font file"
|
906 |
+
raise OSError(msg)
|
907 |
+
|
908 |
+
|
909 |
+
def load_default_imagefont() -> ImageFont:
|
910 |
+
f = ImageFont()
|
911 |
+
f._load_pilfont_data(
|
912 |
+
# courB08
|
913 |
+
BytesIO(
|
914 |
+
base64.b64decode(
|
915 |
+
b"""
|
916 |
+
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
917 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
918 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
919 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
920 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
921 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
922 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
923 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
|
937 |
+
AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
|
938 |
+
/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
|
939 |
+
AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
|
940 |
+
AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
|
941 |
+
AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
|
942 |
+
BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
|
943 |
+
AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
|
944 |
+
2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
|
945 |
+
AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
|
946 |
+
+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
|
947 |
+
////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
|
948 |
+
BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
|
949 |
+
AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
|
950 |
+
AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
|
951 |
+
AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
|
952 |
+
BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
|
953 |
+
//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
|
954 |
+
AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
|
955 |
+
AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
|
956 |
+
mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
|
957 |
+
AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
|
958 |
+
AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
|
959 |
+
AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
|
960 |
+
Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
|
961 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
962 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
963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A//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
|
976 |
+
DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
|
977 |
+
AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
|
978 |
+
+wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
|
979 |
+
AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
|
980 |
+
///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
|
981 |
+
AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
|
982 |
+
BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
|
983 |
+
Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
|
984 |
+
eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
|
985 |
+
AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
|
986 |
+
+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
|
987 |
+
////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
|
988 |
+
BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
|
989 |
+
AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
|
990 |
+
AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
|
991 |
+
Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
|
992 |
+
Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
|
993 |
+
//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
|
994 |
+
AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
|
995 |
+
AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
|
996 |
+
LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
|
997 |
+
AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
|
998 |
+
AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
|
999 |
+
AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
|
1000 |
+
AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
|
1001 |
+
AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
|
1002 |
+
EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
|
1003 |
+
AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
|
1004 |
+
pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
|
1005 |
+
AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
|
1006 |
+
+QAGAAIAzgAKANUAEw==
|
1007 |
+
"""
|
1008 |
+
)
|
1009 |
+
),
|
1010 |
+
Image.open(
|
1011 |
+
BytesIO(
|
1012 |
+
base64.b64decode(
|
1013 |
+
b"""
|
1014 |
+
iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
|
1015 |
+
Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
|
1016 |
+
M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
|
1017 |
+
LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
|
1018 |
+
IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
|
1019 |
+
Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
|
1020 |
+
NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
|
1021 |
+
in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHg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rkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
|
1035 |
+
Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
|
1036 |
+
w7IkEbzhVQAAAABJRU5ErkJggg==
|
1037 |
+
"""
|
1038 |
+
)
|
1039 |
+
)
|
1040 |
+
),
|
1041 |
+
)
|
1042 |
+
return f
|
1043 |
+
|
1044 |
+
|
1045 |
+
def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
|
1046 |
+
"""If FreeType support is available, load a version of Aileron Regular,
|
1047 |
+
https://dotcolon.net/font/aileron, with a more limited character set.
|
1048 |
+
|
1049 |
+
Otherwise, load a "better than nothing" font.
|
1050 |
+
|
1051 |
+
.. versionadded:: 1.1.4
|
1052 |
+
|
1053 |
+
:param size: The font size of Aileron Regular.
|
1054 |
+
|
1055 |
+
.. versionadded:: 10.1.0
|
1056 |
+
|
1057 |
+
:return: A font object.
|
1058 |
+
"""
|
1059 |
+
if isinstance(core, ModuleType) or size is not None:
|
1060 |
+
return truetype(
|
1061 |
+
BytesIO(
|
1062 |
+
base64.b64decode(
|
1063 |
+
b"""
|
1064 |
+
AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
|
1065 |
+
AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
|
1066 |
+
MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
|
1067 |
+
tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
|
1068 |
+
OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889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AAAwAAgAPABEAFgAAAAAAAAAAAAAAAA
|
1278 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA
|
1279 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ
|
1280 |
+
ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
|
1281 |
+
gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
|
1282 |
+
YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
|
1283 |
+
AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
|
1284 |
+
"""
|
1285 |
+
)
|
1286 |
+
),
|
1287 |
+
10 if size is None else size,
|
1288 |
+
layout_engine=Layout.BASIC,
|
1289 |
+
)
|
1290 |
+
return load_default_imagefont()
|
MLPY/Lib/site-packages/PIL/ImageGrab.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# screen grabber
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2001-04-26 fl created
|
9 |
+
# 2001-09-17 fl use builtin driver, if present
|
10 |
+
# 2002-11-19 fl added grabclipboard support
|
11 |
+
#
|
12 |
+
# Copyright (c) 2001-2002 by Secret Labs AB
|
13 |
+
# Copyright (c) 2001-2002 by Fredrik Lundh
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
import io
|
20 |
+
import os
|
21 |
+
import shutil
|
22 |
+
import subprocess
|
23 |
+
import sys
|
24 |
+
import tempfile
|
25 |
+
|
26 |
+
from . import Image
|
27 |
+
|
28 |
+
|
29 |
+
def grab(
|
30 |
+
bbox: tuple[int, int, int, int] | None = None,
|
31 |
+
include_layered_windows: bool = False,
|
32 |
+
all_screens: bool = False,
|
33 |
+
xdisplay: str | None = None,
|
34 |
+
) -> Image.Image:
|
35 |
+
im: Image.Image
|
36 |
+
if xdisplay is None:
|
37 |
+
if sys.platform == "darwin":
|
38 |
+
fh, filepath = tempfile.mkstemp(".png")
|
39 |
+
os.close(fh)
|
40 |
+
args = ["screencapture"]
|
41 |
+
if bbox:
|
42 |
+
left, top, right, bottom = bbox
|
43 |
+
args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
|
44 |
+
subprocess.call(args + ["-x", filepath])
|
45 |
+
im = Image.open(filepath)
|
46 |
+
im.load()
|
47 |
+
os.unlink(filepath)
|
48 |
+
if bbox:
|
49 |
+
im_resized = im.resize((right - left, bottom - top))
|
50 |
+
im.close()
|
51 |
+
return im_resized
|
52 |
+
return im
|
53 |
+
elif sys.platform == "win32":
|
54 |
+
offset, size, data = Image.core.grabscreen_win32(
|
55 |
+
include_layered_windows, all_screens
|
56 |
+
)
|
57 |
+
im = Image.frombytes(
|
58 |
+
"RGB",
|
59 |
+
size,
|
60 |
+
data,
|
61 |
+
# RGB, 32-bit line padding, origin lower left corner
|
62 |
+
"raw",
|
63 |
+
"BGR",
|
64 |
+
(size[0] * 3 + 3) & -4,
|
65 |
+
-1,
|
66 |
+
)
|
67 |
+
if bbox:
|
68 |
+
x0, y0 = offset
|
69 |
+
left, top, right, bottom = bbox
|
70 |
+
im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
|
71 |
+
return im
|
72 |
+
# Cast to Optional[str] needed for Windows and macOS.
|
73 |
+
display_name: str | None = xdisplay
|
74 |
+
try:
|
75 |
+
if not Image.core.HAVE_XCB:
|
76 |
+
msg = "Pillow was built without XCB support"
|
77 |
+
raise OSError(msg)
|
78 |
+
size, data = Image.core.grabscreen_x11(display_name)
|
79 |
+
except OSError:
|
80 |
+
if (
|
81 |
+
display_name is None
|
82 |
+
and sys.platform not in ("darwin", "win32")
|
83 |
+
and shutil.which("gnome-screenshot")
|
84 |
+
):
|
85 |
+
fh, filepath = tempfile.mkstemp(".png")
|
86 |
+
os.close(fh)
|
87 |
+
subprocess.call(["gnome-screenshot", "-f", filepath])
|
88 |
+
im = Image.open(filepath)
|
89 |
+
im.load()
|
90 |
+
os.unlink(filepath)
|
91 |
+
if bbox:
|
92 |
+
im_cropped = im.crop(bbox)
|
93 |
+
im.close()
|
94 |
+
return im_cropped
|
95 |
+
return im
|
96 |
+
else:
|
97 |
+
raise
|
98 |
+
else:
|
99 |
+
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
|
100 |
+
if bbox:
|
101 |
+
im = im.crop(bbox)
|
102 |
+
return im
|
103 |
+
|
104 |
+
|
105 |
+
def grabclipboard() -> Image.Image | list[str] | None:
|
106 |
+
if sys.platform == "darwin":
|
107 |
+
fh, filepath = tempfile.mkstemp(".png")
|
108 |
+
os.close(fh)
|
109 |
+
commands = [
|
110 |
+
'set theFile to (open for access POSIX file "'
|
111 |
+
+ filepath
|
112 |
+
+ '" with write permission)',
|
113 |
+
"try",
|
114 |
+
" write (the clipboard as «class PNGf») to theFile",
|
115 |
+
"end try",
|
116 |
+
"close access theFile",
|
117 |
+
]
|
118 |
+
script = ["osascript"]
|
119 |
+
for command in commands:
|
120 |
+
script += ["-e", command]
|
121 |
+
subprocess.call(script)
|
122 |
+
|
123 |
+
im = None
|
124 |
+
if os.stat(filepath).st_size != 0:
|
125 |
+
im = Image.open(filepath)
|
126 |
+
im.load()
|
127 |
+
os.unlink(filepath)
|
128 |
+
return im
|
129 |
+
elif sys.platform == "win32":
|
130 |
+
fmt, data = Image.core.grabclipboard_win32()
|
131 |
+
if fmt == "file": # CF_HDROP
|
132 |
+
import struct
|
133 |
+
|
134 |
+
o = struct.unpack_from("I", data)[0]
|
135 |
+
if data[16] != 0:
|
136 |
+
files = data[o:].decode("utf-16le").split("\0")
|
137 |
+
else:
|
138 |
+
files = data[o:].decode("mbcs").split("\0")
|
139 |
+
return files[: files.index("")]
|
140 |
+
if isinstance(data, bytes):
|
141 |
+
data = io.BytesIO(data)
|
142 |
+
if fmt == "png":
|
143 |
+
from . import PngImagePlugin
|
144 |
+
|
145 |
+
return PngImagePlugin.PngImageFile(data)
|
146 |
+
elif fmt == "DIB":
|
147 |
+
from . import BmpImagePlugin
|
148 |
+
|
149 |
+
return BmpImagePlugin.DibImageFile(data)
|
150 |
+
return None
|
151 |
+
else:
|
152 |
+
if os.getenv("WAYLAND_DISPLAY"):
|
153 |
+
session_type = "wayland"
|
154 |
+
elif os.getenv("DISPLAY"):
|
155 |
+
session_type = "x11"
|
156 |
+
else: # Session type check failed
|
157 |
+
session_type = None
|
158 |
+
|
159 |
+
if shutil.which("wl-paste") and session_type in ("wayland", None):
|
160 |
+
args = ["wl-paste", "-t", "image"]
|
161 |
+
elif shutil.which("xclip") and session_type in ("x11", None):
|
162 |
+
args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
|
163 |
+
else:
|
164 |
+
msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
|
165 |
+
raise NotImplementedError(msg)
|
166 |
+
|
167 |
+
p = subprocess.run(args, capture_output=True)
|
168 |
+
if p.returncode != 0:
|
169 |
+
err = p.stderr
|
170 |
+
for silent_error in [
|
171 |
+
# wl-paste, when the clipboard is empty
|
172 |
+
b"Nothing is copied",
|
173 |
+
# Ubuntu/Debian wl-paste, when the clipboard is empty
|
174 |
+
b"No selection",
|
175 |
+
# Ubuntu/Debian wl-paste, when an image isn't available
|
176 |
+
b"No suitable type of content copied",
|
177 |
+
# wl-paste or Ubuntu/Debian xclip, when an image isn't available
|
178 |
+
b" not available",
|
179 |
+
# xclip, when an image isn't available
|
180 |
+
b"cannot convert ",
|
181 |
+
# xclip, when the clipboard isn't initialized
|
182 |
+
b"xclip: Error: There is no owner for the ",
|
183 |
+
]:
|
184 |
+
if silent_error in err:
|
185 |
+
return None
|
186 |
+
msg = f"{args[0]} error"
|
187 |
+
if err:
|
188 |
+
msg += f": {err.strip().decode()}"
|
189 |
+
raise ChildProcessError(msg)
|
190 |
+
|
191 |
+
data = io.BytesIO(p.stdout)
|
192 |
+
im = Image.open(data)
|
193 |
+
im.load()
|
194 |
+
return im
|
MLPY/Lib/site-packages/PIL/ImageMath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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# a simple math add-on for the Python Imaging Library
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1999-02-15 fl Original PIL Plus release
|
9 |
+
# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
|
10 |
+
# 2005-09-12 fl Fixed int() and float() for Python 2.4.1
|
11 |
+
#
|
12 |
+
# Copyright (c) 1999-2005 by Secret Labs AB
|
13 |
+
# Copyright (c) 2005 by Fredrik Lundh
|
14 |
+
#
|
15 |
+
# See the README file for information on usage and redistribution.
|
16 |
+
#
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
import builtins
|
20 |
+
from types import CodeType
|
21 |
+
from typing import Any, Callable
|
22 |
+
|
23 |
+
from . import Image, _imagingmath
|
24 |
+
from ._deprecate import deprecate
|
25 |
+
|
26 |
+
|
27 |
+
class _Operand:
|
28 |
+
"""Wraps an image operand, providing standard operators"""
|
29 |
+
|
30 |
+
def __init__(self, im: Image.Image):
|
31 |
+
self.im = im
|
32 |
+
|
33 |
+
def __fixup(self, im1: _Operand | float) -> Image.Image:
|
34 |
+
# convert image to suitable mode
|
35 |
+
if isinstance(im1, _Operand):
|
36 |
+
# argument was an image.
|
37 |
+
if im1.im.mode in ("1", "L"):
|
38 |
+
return im1.im.convert("I")
|
39 |
+
elif im1.im.mode in ("I", "F"):
|
40 |
+
return im1.im
|
41 |
+
else:
|
42 |
+
msg = f"unsupported mode: {im1.im.mode}"
|
43 |
+
raise ValueError(msg)
|
44 |
+
else:
|
45 |
+
# argument was a constant
|
46 |
+
if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
|
47 |
+
return Image.new("I", self.im.size, im1)
|
48 |
+
else:
|
49 |
+
return Image.new("F", self.im.size, im1)
|
50 |
+
|
51 |
+
def apply(
|
52 |
+
self,
|
53 |
+
op: str,
|
54 |
+
im1: _Operand | float,
|
55 |
+
im2: _Operand | float | None = None,
|
56 |
+
mode: str | None = None,
|
57 |
+
) -> _Operand:
|
58 |
+
im_1 = self.__fixup(im1)
|
59 |
+
if im2 is None:
|
60 |
+
# unary operation
|
61 |
+
out = Image.new(mode or im_1.mode, im_1.size, None)
|
62 |
+
im_1.load()
|
63 |
+
try:
|
64 |
+
op = getattr(_imagingmath, f"{op}_{im_1.mode}")
|
65 |
+
except AttributeError as e:
|
66 |
+
msg = f"bad operand type for '{op}'"
|
67 |
+
raise TypeError(msg) from e
|
68 |
+
_imagingmath.unop(op, out.im.id, im_1.im.id)
|
69 |
+
else:
|
70 |
+
# binary operation
|
71 |
+
im_2 = self.__fixup(im2)
|
72 |
+
if im_1.mode != im_2.mode:
|
73 |
+
# convert both arguments to floating point
|
74 |
+
if im_1.mode != "F":
|
75 |
+
im_1 = im_1.convert("F")
|
76 |
+
if im_2.mode != "F":
|
77 |
+
im_2 = im_2.convert("F")
|
78 |
+
if im_1.size != im_2.size:
|
79 |
+
# crop both arguments to a common size
|
80 |
+
size = (
|
81 |
+
min(im_1.size[0], im_2.size[0]),
|
82 |
+
min(im_1.size[1], im_2.size[1]),
|
83 |
+
)
|
84 |
+
if im_1.size != size:
|
85 |
+
im_1 = im_1.crop((0, 0) + size)
|
86 |
+
if im_2.size != size:
|
87 |
+
im_2 = im_2.crop((0, 0) + size)
|
88 |
+
out = Image.new(mode or im_1.mode, im_1.size, None)
|
89 |
+
im_1.load()
|
90 |
+
im_2.load()
|
91 |
+
try:
|
92 |
+
op = getattr(_imagingmath, f"{op}_{im_1.mode}")
|
93 |
+
except AttributeError as e:
|
94 |
+
msg = f"bad operand type for '{op}'"
|
95 |
+
raise TypeError(msg) from e
|
96 |
+
_imagingmath.binop(op, out.im.id, im_1.im.id, im_2.im.id)
|
97 |
+
return _Operand(out)
|
98 |
+
|
99 |
+
# unary operators
|
100 |
+
def __bool__(self) -> bool:
|
101 |
+
# an image is "true" if it contains at least one non-zero pixel
|
102 |
+
return self.im.getbbox() is not None
|
103 |
+
|
104 |
+
def __abs__(self) -> _Operand:
|
105 |
+
return self.apply("abs", self)
|
106 |
+
|
107 |
+
def __pos__(self) -> _Operand:
|
108 |
+
return self
|
109 |
+
|
110 |
+
def __neg__(self) -> _Operand:
|
111 |
+
return self.apply("neg", self)
|
112 |
+
|
113 |
+
# binary operators
|
114 |
+
def __add__(self, other: _Operand | float) -> _Operand:
|
115 |
+
return self.apply("add", self, other)
|
116 |
+
|
117 |
+
def __radd__(self, other: _Operand | float) -> _Operand:
|
118 |
+
return self.apply("add", other, self)
|
119 |
+
|
120 |
+
def __sub__(self, other: _Operand | float) -> _Operand:
|
121 |
+
return self.apply("sub", self, other)
|
122 |
+
|
123 |
+
def __rsub__(self, other: _Operand | float) -> _Operand:
|
124 |
+
return self.apply("sub", other, self)
|
125 |
+
|
126 |
+
def __mul__(self, other: _Operand | float) -> _Operand:
|
127 |
+
return self.apply("mul", self, other)
|
128 |
+
|
129 |
+
def __rmul__(self, other: _Operand | float) -> _Operand:
|
130 |
+
return self.apply("mul", other, self)
|
131 |
+
|
132 |
+
def __truediv__(self, other: _Operand | float) -> _Operand:
|
133 |
+
return self.apply("div", self, other)
|
134 |
+
|
135 |
+
def __rtruediv__(self, other: _Operand | float) -> _Operand:
|
136 |
+
return self.apply("div", other, self)
|
137 |
+
|
138 |
+
def __mod__(self, other: _Operand | float) -> _Operand:
|
139 |
+
return self.apply("mod", self, other)
|
140 |
+
|
141 |
+
def __rmod__(self, other: _Operand | float) -> _Operand:
|
142 |
+
return self.apply("mod", other, self)
|
143 |
+
|
144 |
+
def __pow__(self, other: _Operand | float) -> _Operand:
|
145 |
+
return self.apply("pow", self, other)
|
146 |
+
|
147 |
+
def __rpow__(self, other: _Operand | float) -> _Operand:
|
148 |
+
return self.apply("pow", other, self)
|
149 |
+
|
150 |
+
# bitwise
|
151 |
+
def __invert__(self) -> _Operand:
|
152 |
+
return self.apply("invert", self)
|
153 |
+
|
154 |
+
def __and__(self, other: _Operand | float) -> _Operand:
|
155 |
+
return self.apply("and", self, other)
|
156 |
+
|
157 |
+
def __rand__(self, other: _Operand | float) -> _Operand:
|
158 |
+
return self.apply("and", other, self)
|
159 |
+
|
160 |
+
def __or__(self, other: _Operand | float) -> _Operand:
|
161 |
+
return self.apply("or", self, other)
|
162 |
+
|
163 |
+
def __ror__(self, other: _Operand | float) -> _Operand:
|
164 |
+
return self.apply("or", other, self)
|
165 |
+
|
166 |
+
def __xor__(self, other: _Operand | float) -> _Operand:
|
167 |
+
return self.apply("xor", self, other)
|
168 |
+
|
169 |
+
def __rxor__(self, other: _Operand | float) -> _Operand:
|
170 |
+
return self.apply("xor", other, self)
|
171 |
+
|
172 |
+
def __lshift__(self, other: _Operand | float) -> _Operand:
|
173 |
+
return self.apply("lshift", self, other)
|
174 |
+
|
175 |
+
def __rshift__(self, other: _Operand | float) -> _Operand:
|
176 |
+
return self.apply("rshift", self, other)
|
177 |
+
|
178 |
+
# logical
|
179 |
+
def __eq__(self, other):
|
180 |
+
return self.apply("eq", self, other)
|
181 |
+
|
182 |
+
def __ne__(self, other):
|
183 |
+
return self.apply("ne", self, other)
|
184 |
+
|
185 |
+
def __lt__(self, other: _Operand | float) -> _Operand:
|
186 |
+
return self.apply("lt", self, other)
|
187 |
+
|
188 |
+
def __le__(self, other: _Operand | float) -> _Operand:
|
189 |
+
return self.apply("le", self, other)
|
190 |
+
|
191 |
+
def __gt__(self, other: _Operand | float) -> _Operand:
|
192 |
+
return self.apply("gt", self, other)
|
193 |
+
|
194 |
+
def __ge__(self, other: _Operand | float) -> _Operand:
|
195 |
+
return self.apply("ge", self, other)
|
196 |
+
|
197 |
+
|
198 |
+
# conversions
|
199 |
+
def imagemath_int(self: _Operand) -> _Operand:
|
200 |
+
return _Operand(self.im.convert("I"))
|
201 |
+
|
202 |
+
|
203 |
+
def imagemath_float(self: _Operand) -> _Operand:
|
204 |
+
return _Operand(self.im.convert("F"))
|
205 |
+
|
206 |
+
|
207 |
+
# logical
|
208 |
+
def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
|
209 |
+
return self.apply("eq", self, other, mode="I")
|
210 |
+
|
211 |
+
|
212 |
+
def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
|
213 |
+
return self.apply("ne", self, other, mode="I")
|
214 |
+
|
215 |
+
|
216 |
+
def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
|
217 |
+
return self.apply("min", self, other)
|
218 |
+
|
219 |
+
|
220 |
+
def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
|
221 |
+
return self.apply("max", self, other)
|
222 |
+
|
223 |
+
|
224 |
+
def imagemath_convert(self: _Operand, mode: str) -> _Operand:
|
225 |
+
return _Operand(self.im.convert(mode))
|
226 |
+
|
227 |
+
|
228 |
+
ops = {
|
229 |
+
"int": imagemath_int,
|
230 |
+
"float": imagemath_float,
|
231 |
+
"equal": imagemath_equal,
|
232 |
+
"notequal": imagemath_notequal,
|
233 |
+
"min": imagemath_min,
|
234 |
+
"max": imagemath_max,
|
235 |
+
"convert": imagemath_convert,
|
236 |
+
}
|
237 |
+
|
238 |
+
|
239 |
+
def lambda_eval(
|
240 |
+
expression: Callable[[dict[str, Any]], Any],
|
241 |
+
options: dict[str, Any] = {},
|
242 |
+
**kw: Any,
|
243 |
+
) -> Any:
|
244 |
+
"""
|
245 |
+
Returns the result of an image function.
|
246 |
+
|
247 |
+
:py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
|
248 |
+
images, use the :py:meth:`~PIL.Image.Image.split` method or
|
249 |
+
:py:func:`~PIL.Image.merge` function.
|
250 |
+
|
251 |
+
:param expression: A function that receives a dictionary.
|
252 |
+
:param options: Values to add to the function's dictionary. You
|
253 |
+
can either use a dictionary, or one or more keyword
|
254 |
+
arguments.
|
255 |
+
:return: The expression result. This is usually an image object, but can
|
256 |
+
also be an integer, a floating point value, or a pixel tuple,
|
257 |
+
depending on the expression.
|
258 |
+
"""
|
259 |
+
|
260 |
+
args: dict[str, Any] = ops.copy()
|
261 |
+
args.update(options)
|
262 |
+
args.update(kw)
|
263 |
+
for k, v in args.items():
|
264 |
+
if hasattr(v, "im"):
|
265 |
+
args[k] = _Operand(v)
|
266 |
+
|
267 |
+
out = expression(args)
|
268 |
+
try:
|
269 |
+
return out.im
|
270 |
+
except AttributeError:
|
271 |
+
return out
|
272 |
+
|
273 |
+
|
274 |
+
def unsafe_eval(
|
275 |
+
expression: str,
|
276 |
+
options: dict[str, Any] = {},
|
277 |
+
**kw: Any,
|
278 |
+
) -> Any:
|
279 |
+
"""
|
280 |
+
Evaluates an image expression. This uses Python's ``eval()`` function to process
|
281 |
+
the expression string, and carries the security risks of doing so. It is not
|
282 |
+
recommended to process expressions without considering this.
|
283 |
+
:py:meth:`~lambda_eval` is a more secure alternative.
|
284 |
+
|
285 |
+
:py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
|
286 |
+
images, use the :py:meth:`~PIL.Image.Image.split` method or
|
287 |
+
:py:func:`~PIL.Image.merge` function.
|
288 |
+
|
289 |
+
:param expression: A string containing a Python-style expression.
|
290 |
+
:param options: Values to add to the evaluation context. You
|
291 |
+
can either use a dictionary, or one or more keyword
|
292 |
+
arguments.
|
293 |
+
:return: The evaluated expression. This is usually an image object, but can
|
294 |
+
also be an integer, a floating point value, or a pixel tuple,
|
295 |
+
depending on the expression.
|
296 |
+
"""
|
297 |
+
|
298 |
+
# build execution namespace
|
299 |
+
args: dict[str, Any] = ops.copy()
|
300 |
+
for k in list(options.keys()) + list(kw.keys()):
|
301 |
+
if "__" in k or hasattr(builtins, k):
|
302 |
+
msg = f"'{k}' not allowed"
|
303 |
+
raise ValueError(msg)
|
304 |
+
|
305 |
+
args.update(options)
|
306 |
+
args.update(kw)
|
307 |
+
for k, v in args.items():
|
308 |
+
if hasattr(v, "im"):
|
309 |
+
args[k] = _Operand(v)
|
310 |
+
|
311 |
+
compiled_code = compile(expression, "<string>", "eval")
|
312 |
+
|
313 |
+
def scan(code: CodeType) -> None:
|
314 |
+
for const in code.co_consts:
|
315 |
+
if type(const) is type(compiled_code):
|
316 |
+
scan(const)
|
317 |
+
|
318 |
+
for name in code.co_names:
|
319 |
+
if name not in args and name != "abs":
|
320 |
+
msg = f"'{name}' not allowed"
|
321 |
+
raise ValueError(msg)
|
322 |
+
|
323 |
+
scan(compiled_code)
|
324 |
+
out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
|
325 |
+
try:
|
326 |
+
return out.im
|
327 |
+
except AttributeError:
|
328 |
+
return out
|
329 |
+
|
330 |
+
|
331 |
+
def eval(
|
332 |
+
expression: str,
|
333 |
+
_dict: dict[str, Any] = {},
|
334 |
+
**kw: Any,
|
335 |
+
) -> Any:
|
336 |
+
"""
|
337 |
+
Evaluates an image expression.
|
338 |
+
|
339 |
+
Deprecated. Use lambda_eval() or unsafe_eval() instead.
|
340 |
+
|
341 |
+
:param expression: A string containing a Python-style expression.
|
342 |
+
:param _dict: Values to add to the evaluation context. You
|
343 |
+
can either use a dictionary, or one or more keyword
|
344 |
+
arguments.
|
345 |
+
:return: The evaluated expression. This is usually an image object, but can
|
346 |
+
also be an integer, a floating point value, or a pixel tuple,
|
347 |
+
depending on the expression.
|
348 |
+
|
349 |
+
.. deprecated:: 10.3.0
|
350 |
+
"""
|
351 |
+
|
352 |
+
deprecate(
|
353 |
+
"ImageMath.eval",
|
354 |
+
12,
|
355 |
+
"ImageMath.lambda_eval or ImageMath.unsafe_eval",
|
356 |
+
)
|
357 |
+
return unsafe_eval(expression, _dict, **kw)
|
MLPY/Lib/site-packages/PIL/ImageMode.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# standard mode descriptors
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2006-03-20 fl Added
|
9 |
+
#
|
10 |
+
# Copyright (c) 2006 by Secret Labs AB.
|
11 |
+
# Copyright (c) 2006 by Fredrik Lundh.
|
12 |
+
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
from __future__ import annotations
|
16 |
+
|
17 |
+
import sys
|
18 |
+
from functools import lru_cache
|
19 |
+
from typing import NamedTuple
|
20 |
+
|
21 |
+
from ._deprecate import deprecate
|
22 |
+
|
23 |
+
|
24 |
+
class ModeDescriptor(NamedTuple):
|
25 |
+
"""Wrapper for mode strings."""
|
26 |
+
|
27 |
+
mode: str
|
28 |
+
bands: tuple[str, ...]
|
29 |
+
basemode: str
|
30 |
+
basetype: str
|
31 |
+
typestr: str
|
32 |
+
|
33 |
+
def __str__(self) -> str:
|
34 |
+
return self.mode
|
35 |
+
|
36 |
+
|
37 |
+
@lru_cache
|
38 |
+
def getmode(mode: str) -> ModeDescriptor:
|
39 |
+
"""Gets a mode descriptor for the given mode."""
|
40 |
+
endian = "<" if sys.byteorder == "little" else ">"
|
41 |
+
|
42 |
+
modes = {
|
43 |
+
# core modes
|
44 |
+
# Bits need to be extended to bytes
|
45 |
+
"1": ("L", "L", ("1",), "|b1"),
|
46 |
+
"L": ("L", "L", ("L",), "|u1"),
|
47 |
+
"I": ("L", "I", ("I",), f"{endian}i4"),
|
48 |
+
"F": ("L", "F", ("F",), f"{endian}f4"),
|
49 |
+
"P": ("P", "L", ("P",), "|u1"),
|
50 |
+
"RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
|
51 |
+
"RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
|
52 |
+
"RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
|
53 |
+
"CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
|
54 |
+
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
|
55 |
+
# UNDONE - unsigned |u1i1i1
|
56 |
+
"LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
|
57 |
+
"HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
|
58 |
+
# extra experimental modes
|
59 |
+
"RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
|
60 |
+
"BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
61 |
+
"BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
62 |
+
"BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
63 |
+
"LA": ("L", "L", ("L", "A"), "|u1"),
|
64 |
+
"La": ("L", "L", ("L", "a"), "|u1"),
|
65 |
+
"PA": ("RGB", "L", ("P", "A"), "|u1"),
|
66 |
+
}
|
67 |
+
if mode in modes:
|
68 |
+
if mode in ("BGR;15", "BGR;16", "BGR;24"):
|
69 |
+
deprecate(mode, 12)
|
70 |
+
base_mode, base_type, bands, type_str = modes[mode]
|
71 |
+
return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
|
72 |
+
|
73 |
+
mapping_modes = {
|
74 |
+
# I;16 == I;16L, and I;32 == I;32L
|
75 |
+
"I;16": "<u2",
|
76 |
+
"I;16S": "<i2",
|
77 |
+
"I;16L": "<u2",
|
78 |
+
"I;16LS": "<i2",
|
79 |
+
"I;16B": ">u2",
|
80 |
+
"I;16BS": ">i2",
|
81 |
+
"I;16N": f"{endian}u2",
|
82 |
+
"I;16NS": f"{endian}i2",
|
83 |
+
"I;32": "<u4",
|
84 |
+
"I;32B": ">u4",
|
85 |
+
"I;32L": "<u4",
|
86 |
+
"I;32S": "<i4",
|
87 |
+
"I;32BS": ">i4",
|
88 |
+
"I;32LS": "<i4",
|
89 |
+
}
|
90 |
+
|
91 |
+
type_str = mapping_modes[mode]
|
92 |
+
return ModeDescriptor(mode, ("I",), "L", "L", type_str)
|
MLPY/Lib/site-packages/PIL/ImageMorph.py
ADDED
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# A binary morphology add-on for the Python Imaging Library
|
2 |
+
#
|
3 |
+
# History:
|
4 |
+
# 2014-06-04 Initial version.
|
5 |
+
#
|
6 |
+
# Copyright (c) 2014 Dov Grobgeld <[email protected]>
|
7 |
+
from __future__ import annotations
|
8 |
+
|
9 |
+
import re
|
10 |
+
|
11 |
+
from . import Image, _imagingmorph
|
12 |
+
|
13 |
+
LUT_SIZE = 1 << 9
|
14 |
+
|
15 |
+
# fmt: off
|
16 |
+
ROTATION_MATRIX = [
|
17 |
+
6, 3, 0,
|
18 |
+
7, 4, 1,
|
19 |
+
8, 5, 2,
|
20 |
+
]
|
21 |
+
MIRROR_MATRIX = [
|
22 |
+
2, 1, 0,
|
23 |
+
5, 4, 3,
|
24 |
+
8, 7, 6,
|
25 |
+
]
|
26 |
+
# fmt: on
|
27 |
+
|
28 |
+
|
29 |
+
class LutBuilder:
|
30 |
+
"""A class for building a MorphLut from a descriptive language
|
31 |
+
|
32 |
+
The input patterns is a list of a strings sequences like these::
|
33 |
+
|
34 |
+
4:(...
|
35 |
+
.1.
|
36 |
+
111)->1
|
37 |
+
|
38 |
+
(whitespaces including linebreaks are ignored). The option 4
|
39 |
+
describes a series of symmetry operations (in this case a
|
40 |
+
4-rotation), the pattern is described by:
|
41 |
+
|
42 |
+
- . or X - Ignore
|
43 |
+
- 1 - Pixel is on
|
44 |
+
- 0 - Pixel is off
|
45 |
+
|
46 |
+
The result of the operation is described after "->" string.
|
47 |
+
|
48 |
+
The default is to return the current pixel value, which is
|
49 |
+
returned if no other match is found.
|
50 |
+
|
51 |
+
Operations:
|
52 |
+
|
53 |
+
- 4 - 4 way rotation
|
54 |
+
- N - Negate
|
55 |
+
- 1 - Dummy op for no other operation (an op must always be given)
|
56 |
+
- M - Mirroring
|
57 |
+
|
58 |
+
Example::
|
59 |
+
|
60 |
+
lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
|
61 |
+
lut = lb.build_lut()
|
62 |
+
|
63 |
+
"""
|
64 |
+
|
65 |
+
def __init__(
|
66 |
+
self, patterns: list[str] | None = None, op_name: str | None = None
|
67 |
+
) -> None:
|
68 |
+
if patterns is not None:
|
69 |
+
self.patterns = patterns
|
70 |
+
else:
|
71 |
+
self.patterns = []
|
72 |
+
self.lut: bytearray | None = None
|
73 |
+
if op_name is not None:
|
74 |
+
known_patterns = {
|
75 |
+
"corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
|
76 |
+
"dilation4": ["4:(... .0. .1.)->1"],
|
77 |
+
"dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
|
78 |
+
"erosion4": ["4:(... .1. .0.)->0"],
|
79 |
+
"erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
|
80 |
+
"edge": [
|
81 |
+
"1:(... ... ...)->0",
|
82 |
+
"4:(.0. .1. ...)->1",
|
83 |
+
"4:(01. .1. ...)->1",
|
84 |
+
],
|
85 |
+
}
|
86 |
+
if op_name not in known_patterns:
|
87 |
+
msg = f"Unknown pattern {op_name}!"
|
88 |
+
raise Exception(msg)
|
89 |
+
|
90 |
+
self.patterns = known_patterns[op_name]
|
91 |
+
|
92 |
+
def add_patterns(self, patterns: list[str]) -> None:
|
93 |
+
self.patterns += patterns
|
94 |
+
|
95 |
+
def build_default_lut(self) -> None:
|
96 |
+
symbols = [0, 1]
|
97 |
+
m = 1 << 4 # pos of current pixel
|
98 |
+
self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
|
99 |
+
|
100 |
+
def get_lut(self) -> bytearray | None:
|
101 |
+
return self.lut
|
102 |
+
|
103 |
+
def _string_permute(self, pattern: str, permutation: list[int]) -> str:
|
104 |
+
"""string_permute takes a pattern and a permutation and returns the
|
105 |
+
string permuted according to the permutation list.
|
106 |
+
"""
|
107 |
+
assert len(permutation) == 9
|
108 |
+
return "".join(pattern[p] for p in permutation)
|
109 |
+
|
110 |
+
def _pattern_permute(
|
111 |
+
self, basic_pattern: str, options: str, basic_result: int
|
112 |
+
) -> list[tuple[str, int]]:
|
113 |
+
"""pattern_permute takes a basic pattern and its result and clones
|
114 |
+
the pattern according to the modifications described in the $options
|
115 |
+
parameter. It returns a list of all cloned patterns."""
|
116 |
+
patterns = [(basic_pattern, basic_result)]
|
117 |
+
|
118 |
+
# rotations
|
119 |
+
if "4" in options:
|
120 |
+
res = patterns[-1][1]
|
121 |
+
for i in range(4):
|
122 |
+
patterns.append(
|
123 |
+
(self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
|
124 |
+
)
|
125 |
+
# mirror
|
126 |
+
if "M" in options:
|
127 |
+
n = len(patterns)
|
128 |
+
for pattern, res in patterns[:n]:
|
129 |
+
patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
|
130 |
+
|
131 |
+
# negate
|
132 |
+
if "N" in options:
|
133 |
+
n = len(patterns)
|
134 |
+
for pattern, res in patterns[:n]:
|
135 |
+
# Swap 0 and 1
|
136 |
+
pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
|
137 |
+
res = 1 - int(res)
|
138 |
+
patterns.append((pattern, res))
|
139 |
+
|
140 |
+
return patterns
|
141 |
+
|
142 |
+
def build_lut(self) -> bytearray:
|
143 |
+
"""Compile all patterns into a morphology lut.
|
144 |
+
|
145 |
+
TBD :Build based on (file) morphlut:modify_lut
|
146 |
+
"""
|
147 |
+
self.build_default_lut()
|
148 |
+
assert self.lut is not None
|
149 |
+
patterns = []
|
150 |
+
|
151 |
+
# Parse and create symmetries of the patterns strings
|
152 |
+
for p in self.patterns:
|
153 |
+
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
|
154 |
+
if not m:
|
155 |
+
msg = 'Syntax error in pattern "' + p + '"'
|
156 |
+
raise Exception(msg)
|
157 |
+
options = m.group(1)
|
158 |
+
pattern = m.group(2)
|
159 |
+
result = int(m.group(3))
|
160 |
+
|
161 |
+
# Get rid of spaces
|
162 |
+
pattern = pattern.replace(" ", "").replace("\n", "")
|
163 |
+
|
164 |
+
patterns += self._pattern_permute(pattern, options, result)
|
165 |
+
|
166 |
+
# compile the patterns into regular expressions for speed
|
167 |
+
compiled_patterns = []
|
168 |
+
for pattern in patterns:
|
169 |
+
p = pattern[0].replace(".", "X").replace("X", "[01]")
|
170 |
+
compiled_patterns.append((re.compile(p), pattern[1]))
|
171 |
+
|
172 |
+
# Step through table and find patterns that match.
|
173 |
+
# Note that all the patterns are searched. The last one
|
174 |
+
# caught overrides
|
175 |
+
for i in range(LUT_SIZE):
|
176 |
+
# Build the bit pattern
|
177 |
+
bitpattern = bin(i)[2:]
|
178 |
+
bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
|
179 |
+
|
180 |
+
for pattern, r in compiled_patterns:
|
181 |
+
if pattern.match(bitpattern):
|
182 |
+
self.lut[i] = [0, 1][r]
|
183 |
+
|
184 |
+
return self.lut
|
185 |
+
|
186 |
+
|
187 |
+
class MorphOp:
|
188 |
+
"""A class for binary morphological operators"""
|
189 |
+
|
190 |
+
def __init__(
|
191 |
+
self,
|
192 |
+
lut: bytearray | None = None,
|
193 |
+
op_name: str | None = None,
|
194 |
+
patterns: list[str] | None = None,
|
195 |
+
) -> None:
|
196 |
+
"""Create a binary morphological operator"""
|
197 |
+
self.lut = lut
|
198 |
+
if op_name is not None:
|
199 |
+
self.lut = LutBuilder(op_name=op_name).build_lut()
|
200 |
+
elif patterns is not None:
|
201 |
+
self.lut = LutBuilder(patterns=patterns).build_lut()
|
202 |
+
|
203 |
+
def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
|
204 |
+
"""Run a single morphological operation on an image
|
205 |
+
|
206 |
+
Returns a tuple of the number of changed pixels and the
|
207 |
+
morphed image"""
|
208 |
+
if self.lut is None:
|
209 |
+
msg = "No operator loaded"
|
210 |
+
raise Exception(msg)
|
211 |
+
|
212 |
+
if image.mode != "L":
|
213 |
+
msg = "Image mode must be L"
|
214 |
+
raise ValueError(msg)
|
215 |
+
outimage = Image.new(image.mode, image.size, None)
|
216 |
+
count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
|
217 |
+
return count, outimage
|
218 |
+
|
219 |
+
def match(self, image: Image.Image) -> list[tuple[int, int]]:
|
220 |
+
"""Get a list of coordinates matching the morphological operation on
|
221 |
+
an image.
|
222 |
+
|
223 |
+
Returns a list of tuples of (x,y) coordinates
|
224 |
+
of all matching pixels. See :ref:`coordinate-system`."""
|
225 |
+
if self.lut is None:
|
226 |
+
msg = "No operator loaded"
|
227 |
+
raise Exception(msg)
|
228 |
+
|
229 |
+
if image.mode != "L":
|
230 |
+
msg = "Image mode must be L"
|
231 |
+
raise ValueError(msg)
|
232 |
+
return _imagingmorph.match(bytes(self.lut), image.im.id)
|
233 |
+
|
234 |
+
def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
|
235 |
+
"""Get a list of all turned on pixels in a binary image
|
236 |
+
|
237 |
+
Returns a list of tuples of (x,y) coordinates
|
238 |
+
of all matching pixels. See :ref:`coordinate-system`."""
|
239 |
+
|
240 |
+
if image.mode != "L":
|
241 |
+
msg = "Image mode must be L"
|
242 |
+
raise ValueError(msg)
|
243 |
+
return _imagingmorph.get_on_pixels(image.im.id)
|
244 |
+
|
245 |
+
def load_lut(self, filename: str) -> None:
|
246 |
+
"""Load an operator from an mrl file"""
|
247 |
+
with open(filename, "rb") as f:
|
248 |
+
self.lut = bytearray(f.read())
|
249 |
+
|
250 |
+
if len(self.lut) != LUT_SIZE:
|
251 |
+
self.lut = None
|
252 |
+
msg = "Wrong size operator file!"
|
253 |
+
raise Exception(msg)
|
254 |
+
|
255 |
+
def save_lut(self, filename: str) -> None:
|
256 |
+
"""Save an operator to an mrl file"""
|
257 |
+
if self.lut is None:
|
258 |
+
msg = "No operator loaded"
|
259 |
+
raise Exception(msg)
|
260 |
+
with open(filename, "wb") as f:
|
261 |
+
f.write(self.lut)
|
262 |
+
|
263 |
+
def set_lut(self, lut: bytearray | None) -> None:
|
264 |
+
"""Set the lut from an external source"""
|
265 |
+
self.lut = lut
|
MLPY/Lib/site-packages/PIL/ImageOps.py
ADDED
@@ -0,0 +1,728 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# standard image operations
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2001-10-20 fl Created
|
9 |
+
# 2001-10-23 fl Added autocontrast operator
|
10 |
+
# 2001-12-18 fl Added Kevin's fit operator
|
11 |
+
# 2004-03-14 fl Fixed potential division by zero in equalize
|
12 |
+
# 2005-05-05 fl Fixed equalize for low number of values
|
13 |
+
#
|
14 |
+
# Copyright (c) 2001-2004 by Secret Labs AB
|
15 |
+
# Copyright (c) 2001-2004 by Fredrik Lundh
|
16 |
+
#
|
17 |
+
# See the README file for information on usage and redistribution.
|
18 |
+
#
|
19 |
+
from __future__ import annotations
|
20 |
+
|
21 |
+
import functools
|
22 |
+
import operator
|
23 |
+
import re
|
24 |
+
from typing import Protocol, Sequence, cast
|
25 |
+
|
26 |
+
from . import ExifTags, Image, ImagePalette
|
27 |
+
|
28 |
+
#
|
29 |
+
# helpers
|
30 |
+
|
31 |
+
|
32 |
+
def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
|
33 |
+
if isinstance(border, tuple):
|
34 |
+
if len(border) == 2:
|
35 |
+
left, top = right, bottom = border
|
36 |
+
elif len(border) == 4:
|
37 |
+
left, top, right, bottom = border
|
38 |
+
else:
|
39 |
+
left = top = right = bottom = border
|
40 |
+
return left, top, right, bottom
|
41 |
+
|
42 |
+
|
43 |
+
def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
|
44 |
+
if isinstance(color, str):
|
45 |
+
from . import ImageColor
|
46 |
+
|
47 |
+
color = ImageColor.getcolor(color, mode)
|
48 |
+
return color
|
49 |
+
|
50 |
+
|
51 |
+
def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
|
52 |
+
if image.mode == "P":
|
53 |
+
# FIXME: apply to lookup table, not image data
|
54 |
+
msg = "mode P support coming soon"
|
55 |
+
raise NotImplementedError(msg)
|
56 |
+
elif image.mode in ("L", "RGB"):
|
57 |
+
if image.mode == "RGB" and len(lut) == 256:
|
58 |
+
lut = lut + lut + lut
|
59 |
+
return image.point(lut)
|
60 |
+
else:
|
61 |
+
msg = f"not supported for mode {image.mode}"
|
62 |
+
raise OSError(msg)
|
63 |
+
|
64 |
+
|
65 |
+
#
|
66 |
+
# actions
|
67 |
+
|
68 |
+
|
69 |
+
def autocontrast(
|
70 |
+
image: Image.Image,
|
71 |
+
cutoff: float | tuple[float, float] = 0,
|
72 |
+
ignore: int | Sequence[int] | None = None,
|
73 |
+
mask: Image.Image | None = None,
|
74 |
+
preserve_tone: bool = False,
|
75 |
+
) -> Image.Image:
|
76 |
+
"""
|
77 |
+
Maximize (normalize) image contrast. This function calculates a
|
78 |
+
histogram of the input image (or mask region), removes ``cutoff`` percent of the
|
79 |
+
lightest and darkest pixels from the histogram, and remaps the image
|
80 |
+
so that the darkest pixel becomes black (0), and the lightest
|
81 |
+
becomes white (255).
|
82 |
+
|
83 |
+
:param image: The image to process.
|
84 |
+
:param cutoff: The percent to cut off from the histogram on the low and
|
85 |
+
high ends. Either a tuple of (low, high), or a single
|
86 |
+
number for both.
|
87 |
+
:param ignore: The background pixel value (use None for no background).
|
88 |
+
:param mask: Histogram used in contrast operation is computed using pixels
|
89 |
+
within the mask. If no mask is given the entire image is used
|
90 |
+
for histogram computation.
|
91 |
+
:param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
|
92 |
+
|
93 |
+
.. versionadded:: 8.2.0
|
94 |
+
|
95 |
+
:return: An image.
|
96 |
+
"""
|
97 |
+
if preserve_tone:
|
98 |
+
histogram = image.convert("L").histogram(mask)
|
99 |
+
else:
|
100 |
+
histogram = image.histogram(mask)
|
101 |
+
|
102 |
+
lut = []
|
103 |
+
for layer in range(0, len(histogram), 256):
|
104 |
+
h = histogram[layer : layer + 256]
|
105 |
+
if ignore is not None:
|
106 |
+
# get rid of outliers
|
107 |
+
if isinstance(ignore, int):
|
108 |
+
h[ignore] = 0
|
109 |
+
else:
|
110 |
+
for ix in ignore:
|
111 |
+
h[ix] = 0
|
112 |
+
if cutoff:
|
113 |
+
# cut off pixels from both ends of the histogram
|
114 |
+
if not isinstance(cutoff, tuple):
|
115 |
+
cutoff = (cutoff, cutoff)
|
116 |
+
# get number of pixels
|
117 |
+
n = 0
|
118 |
+
for ix in range(256):
|
119 |
+
n = n + h[ix]
|
120 |
+
# remove cutoff% pixels from the low end
|
121 |
+
cut = int(n * cutoff[0] // 100)
|
122 |
+
for lo in range(256):
|
123 |
+
if cut > h[lo]:
|
124 |
+
cut = cut - h[lo]
|
125 |
+
h[lo] = 0
|
126 |
+
else:
|
127 |
+
h[lo] -= cut
|
128 |
+
cut = 0
|
129 |
+
if cut <= 0:
|
130 |
+
break
|
131 |
+
# remove cutoff% samples from the high end
|
132 |
+
cut = int(n * cutoff[1] // 100)
|
133 |
+
for hi in range(255, -1, -1):
|
134 |
+
if cut > h[hi]:
|
135 |
+
cut = cut - h[hi]
|
136 |
+
h[hi] = 0
|
137 |
+
else:
|
138 |
+
h[hi] -= cut
|
139 |
+
cut = 0
|
140 |
+
if cut <= 0:
|
141 |
+
break
|
142 |
+
# find lowest/highest samples after preprocessing
|
143 |
+
for lo in range(256):
|
144 |
+
if h[lo]:
|
145 |
+
break
|
146 |
+
for hi in range(255, -1, -1):
|
147 |
+
if h[hi]:
|
148 |
+
break
|
149 |
+
if hi <= lo:
|
150 |
+
# don't bother
|
151 |
+
lut.extend(list(range(256)))
|
152 |
+
else:
|
153 |
+
scale = 255.0 / (hi - lo)
|
154 |
+
offset = -lo * scale
|
155 |
+
for ix in range(256):
|
156 |
+
ix = int(ix * scale + offset)
|
157 |
+
if ix < 0:
|
158 |
+
ix = 0
|
159 |
+
elif ix > 255:
|
160 |
+
ix = 255
|
161 |
+
lut.append(ix)
|
162 |
+
return _lut(image, lut)
|
163 |
+
|
164 |
+
|
165 |
+
def colorize(
|
166 |
+
image: Image.Image,
|
167 |
+
black: str | tuple[int, ...],
|
168 |
+
white: str | tuple[int, ...],
|
169 |
+
mid: str | int | tuple[int, ...] | None = None,
|
170 |
+
blackpoint: int = 0,
|
171 |
+
whitepoint: int = 255,
|
172 |
+
midpoint: int = 127,
|
173 |
+
) -> Image.Image:
|
174 |
+
"""
|
175 |
+
Colorize grayscale image.
|
176 |
+
This function calculates a color wedge which maps all black pixels in
|
177 |
+
the source image to the first color and all white pixels to the
|
178 |
+
second color. If ``mid`` is specified, it uses three-color mapping.
|
179 |
+
The ``black`` and ``white`` arguments should be RGB tuples or color names;
|
180 |
+
optionally you can use three-color mapping by also specifying ``mid``.
|
181 |
+
Mapping positions for any of the colors can be specified
|
182 |
+
(e.g. ``blackpoint``), where these parameters are the integer
|
183 |
+
value corresponding to where the corresponding color should be mapped.
|
184 |
+
These parameters must have logical order, such that
|
185 |
+
``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
|
186 |
+
|
187 |
+
:param image: The image to colorize.
|
188 |
+
:param black: The color to use for black input pixels.
|
189 |
+
:param white: The color to use for white input pixels.
|
190 |
+
:param mid: The color to use for midtone input pixels.
|
191 |
+
:param blackpoint: an int value [0, 255] for the black mapping.
|
192 |
+
:param whitepoint: an int value [0, 255] for the white mapping.
|
193 |
+
:param midpoint: an int value [0, 255] for the midtone mapping.
|
194 |
+
:return: An image.
|
195 |
+
"""
|
196 |
+
|
197 |
+
# Initial asserts
|
198 |
+
assert image.mode == "L"
|
199 |
+
if mid is None:
|
200 |
+
assert 0 <= blackpoint <= whitepoint <= 255
|
201 |
+
else:
|
202 |
+
assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
|
203 |
+
|
204 |
+
# Define colors from arguments
|
205 |
+
rgb_black = cast(Sequence[int], _color(black, "RGB"))
|
206 |
+
rgb_white = cast(Sequence[int], _color(white, "RGB"))
|
207 |
+
rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
|
208 |
+
|
209 |
+
# Empty lists for the mapping
|
210 |
+
red = []
|
211 |
+
green = []
|
212 |
+
blue = []
|
213 |
+
|
214 |
+
# Create the low-end values
|
215 |
+
for i in range(0, blackpoint):
|
216 |
+
red.append(rgb_black[0])
|
217 |
+
green.append(rgb_black[1])
|
218 |
+
blue.append(rgb_black[2])
|
219 |
+
|
220 |
+
# Create the mapping (2-color)
|
221 |
+
if rgb_mid is None:
|
222 |
+
range_map = range(0, whitepoint - blackpoint)
|
223 |
+
|
224 |
+
for i in range_map:
|
225 |
+
red.append(
|
226 |
+
rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
|
227 |
+
)
|
228 |
+
green.append(
|
229 |
+
rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
|
230 |
+
)
|
231 |
+
blue.append(
|
232 |
+
rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
|
233 |
+
)
|
234 |
+
|
235 |
+
# Create the mapping (3-color)
|
236 |
+
else:
|
237 |
+
range_map1 = range(0, midpoint - blackpoint)
|
238 |
+
range_map2 = range(0, whitepoint - midpoint)
|
239 |
+
|
240 |
+
for i in range_map1:
|
241 |
+
red.append(
|
242 |
+
rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
|
243 |
+
)
|
244 |
+
green.append(
|
245 |
+
rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
|
246 |
+
)
|
247 |
+
blue.append(
|
248 |
+
rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
|
249 |
+
)
|
250 |
+
for i in range_map2:
|
251 |
+
red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
|
252 |
+
green.append(
|
253 |
+
rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
|
254 |
+
)
|
255 |
+
blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
|
256 |
+
|
257 |
+
# Create the high-end values
|
258 |
+
for i in range(0, 256 - whitepoint):
|
259 |
+
red.append(rgb_white[0])
|
260 |
+
green.append(rgb_white[1])
|
261 |
+
blue.append(rgb_white[2])
|
262 |
+
|
263 |
+
# Return converted image
|
264 |
+
image = image.convert("RGB")
|
265 |
+
return _lut(image, red + green + blue)
|
266 |
+
|
267 |
+
|
268 |
+
def contain(
|
269 |
+
image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
|
270 |
+
) -> Image.Image:
|
271 |
+
"""
|
272 |
+
Returns a resized version of the image, set to the maximum width and height
|
273 |
+
within the requested size, while maintaining the original aspect ratio.
|
274 |
+
|
275 |
+
:param image: The image to resize.
|
276 |
+
:param size: The requested output size in pixels, given as a
|
277 |
+
(width, height) tuple.
|
278 |
+
:param method: Resampling method to use. Default is
|
279 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
280 |
+
See :ref:`concept-filters`.
|
281 |
+
:return: An image.
|
282 |
+
"""
|
283 |
+
|
284 |
+
im_ratio = image.width / image.height
|
285 |
+
dest_ratio = size[0] / size[1]
|
286 |
+
|
287 |
+
if im_ratio != dest_ratio:
|
288 |
+
if im_ratio > dest_ratio:
|
289 |
+
new_height = round(image.height / image.width * size[0])
|
290 |
+
if new_height != size[1]:
|
291 |
+
size = (size[0], new_height)
|
292 |
+
else:
|
293 |
+
new_width = round(image.width / image.height * size[1])
|
294 |
+
if new_width != size[0]:
|
295 |
+
size = (new_width, size[1])
|
296 |
+
return image.resize(size, resample=method)
|
297 |
+
|
298 |
+
|
299 |
+
def cover(
|
300 |
+
image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
|
301 |
+
) -> Image.Image:
|
302 |
+
"""
|
303 |
+
Returns a resized version of the image, so that the requested size is
|
304 |
+
covered, while maintaining the original aspect ratio.
|
305 |
+
|
306 |
+
:param image: The image to resize.
|
307 |
+
:param size: The requested output size in pixels, given as a
|
308 |
+
(width, height) tuple.
|
309 |
+
:param method: Resampling method to use. Default is
|
310 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
311 |
+
See :ref:`concept-filters`.
|
312 |
+
:return: An image.
|
313 |
+
"""
|
314 |
+
|
315 |
+
im_ratio = image.width / image.height
|
316 |
+
dest_ratio = size[0] / size[1]
|
317 |
+
|
318 |
+
if im_ratio != dest_ratio:
|
319 |
+
if im_ratio < dest_ratio:
|
320 |
+
new_height = round(image.height / image.width * size[0])
|
321 |
+
if new_height != size[1]:
|
322 |
+
size = (size[0], new_height)
|
323 |
+
else:
|
324 |
+
new_width = round(image.width / image.height * size[1])
|
325 |
+
if new_width != size[0]:
|
326 |
+
size = (new_width, size[1])
|
327 |
+
return image.resize(size, resample=method)
|
328 |
+
|
329 |
+
|
330 |
+
def pad(
|
331 |
+
image: Image.Image,
|
332 |
+
size: tuple[int, int],
|
333 |
+
method: int = Image.Resampling.BICUBIC,
|
334 |
+
color: str | int | tuple[int, ...] | None = None,
|
335 |
+
centering: tuple[float, float] = (0.5, 0.5),
|
336 |
+
) -> Image.Image:
|
337 |
+
"""
|
338 |
+
Returns a resized and padded version of the image, expanded to fill the
|
339 |
+
requested aspect ratio and size.
|
340 |
+
|
341 |
+
:param image: The image to resize and crop.
|
342 |
+
:param size: The requested output size in pixels, given as a
|
343 |
+
(width, height) tuple.
|
344 |
+
:param method: Resampling method to use. Default is
|
345 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
346 |
+
See :ref:`concept-filters`.
|
347 |
+
:param color: The background color of the padded image.
|
348 |
+
:param centering: Control the position of the original image within the
|
349 |
+
padded version.
|
350 |
+
|
351 |
+
(0.5, 0.5) will keep the image centered
|
352 |
+
(0, 0) will keep the image aligned to the top left
|
353 |
+
(1, 1) will keep the image aligned to the bottom
|
354 |
+
right
|
355 |
+
:return: An image.
|
356 |
+
"""
|
357 |
+
|
358 |
+
resized = contain(image, size, method)
|
359 |
+
if resized.size == size:
|
360 |
+
out = resized
|
361 |
+
else:
|
362 |
+
out = Image.new(image.mode, size, color)
|
363 |
+
if resized.palette:
|
364 |
+
out.putpalette(resized.getpalette())
|
365 |
+
if resized.width != size[0]:
|
366 |
+
x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
|
367 |
+
out.paste(resized, (x, 0))
|
368 |
+
else:
|
369 |
+
y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
|
370 |
+
out.paste(resized, (0, y))
|
371 |
+
return out
|
372 |
+
|
373 |
+
|
374 |
+
def crop(image: Image.Image, border: int = 0) -> Image.Image:
|
375 |
+
"""
|
376 |
+
Remove border from image. The same amount of pixels are removed
|
377 |
+
from all four sides. This function works on all image modes.
|
378 |
+
|
379 |
+
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
|
380 |
+
|
381 |
+
:param image: The image to crop.
|
382 |
+
:param border: The number of pixels to remove.
|
383 |
+
:return: An image.
|
384 |
+
"""
|
385 |
+
left, top, right, bottom = _border(border)
|
386 |
+
return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
|
387 |
+
|
388 |
+
|
389 |
+
def scale(
|
390 |
+
image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
|
391 |
+
) -> Image.Image:
|
392 |
+
"""
|
393 |
+
Returns a rescaled image by a specific factor given in parameter.
|
394 |
+
A factor greater than 1 expands the image, between 0 and 1 contracts the
|
395 |
+
image.
|
396 |
+
|
397 |
+
:param image: The image to rescale.
|
398 |
+
:param factor: The expansion factor, as a float.
|
399 |
+
:param resample: Resampling method to use. Default is
|
400 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
401 |
+
See :ref:`concept-filters`.
|
402 |
+
:returns: An :py:class:`~PIL.Image.Image` object.
|
403 |
+
"""
|
404 |
+
if factor == 1:
|
405 |
+
return image.copy()
|
406 |
+
elif factor <= 0:
|
407 |
+
msg = "the factor must be greater than 0"
|
408 |
+
raise ValueError(msg)
|
409 |
+
else:
|
410 |
+
size = (round(factor * image.width), round(factor * image.height))
|
411 |
+
return image.resize(size, resample)
|
412 |
+
|
413 |
+
|
414 |
+
class SupportsGetMesh(Protocol):
|
415 |
+
"""
|
416 |
+
An object that supports the ``getmesh`` method, taking an image as an
|
417 |
+
argument, and returning a list of tuples. Each tuple contains two tuples,
|
418 |
+
the source box as a tuple of 4 integers, and a tuple of 8 integers for the
|
419 |
+
final quadrilateral, in order of top left, bottom left, bottom right, top
|
420 |
+
right.
|
421 |
+
"""
|
422 |
+
|
423 |
+
def getmesh(
|
424 |
+
self, image: Image.Image
|
425 |
+
) -> list[
|
426 |
+
tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
|
427 |
+
]: ...
|
428 |
+
|
429 |
+
|
430 |
+
def deform(
|
431 |
+
image: Image.Image,
|
432 |
+
deformer: SupportsGetMesh,
|
433 |
+
resample: int = Image.Resampling.BILINEAR,
|
434 |
+
) -> Image.Image:
|
435 |
+
"""
|
436 |
+
Deform the image.
|
437 |
+
|
438 |
+
:param image: The image to deform.
|
439 |
+
:param deformer: A deformer object. Any object that implements a
|
440 |
+
``getmesh`` method can be used.
|
441 |
+
:param resample: An optional resampling filter. Same values possible as
|
442 |
+
in the PIL.Image.transform function.
|
443 |
+
:return: An image.
|
444 |
+
"""
|
445 |
+
return image.transform(
|
446 |
+
image.size, Image.Transform.MESH, deformer.getmesh(image), resample
|
447 |
+
)
|
448 |
+
|
449 |
+
|
450 |
+
def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
|
451 |
+
"""
|
452 |
+
Equalize the image histogram. This function applies a non-linear
|
453 |
+
mapping to the input image, in order to create a uniform
|
454 |
+
distribution of grayscale values in the output image.
|
455 |
+
|
456 |
+
:param image: The image to equalize.
|
457 |
+
:param mask: An optional mask. If given, only the pixels selected by
|
458 |
+
the mask are included in the analysis.
|
459 |
+
:return: An image.
|
460 |
+
"""
|
461 |
+
if image.mode == "P":
|
462 |
+
image = image.convert("RGB")
|
463 |
+
h = image.histogram(mask)
|
464 |
+
lut = []
|
465 |
+
for b in range(0, len(h), 256):
|
466 |
+
histo = [_f for _f in h[b : b + 256] if _f]
|
467 |
+
if len(histo) <= 1:
|
468 |
+
lut.extend(list(range(256)))
|
469 |
+
else:
|
470 |
+
step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
|
471 |
+
if not step:
|
472 |
+
lut.extend(list(range(256)))
|
473 |
+
else:
|
474 |
+
n = step // 2
|
475 |
+
for i in range(256):
|
476 |
+
lut.append(n // step)
|
477 |
+
n = n + h[i + b]
|
478 |
+
return _lut(image, lut)
|
479 |
+
|
480 |
+
|
481 |
+
def expand(
|
482 |
+
image: Image.Image,
|
483 |
+
border: int | tuple[int, ...] = 0,
|
484 |
+
fill: str | int | tuple[int, ...] = 0,
|
485 |
+
) -> Image.Image:
|
486 |
+
"""
|
487 |
+
Add border to the image
|
488 |
+
|
489 |
+
:param image: The image to expand.
|
490 |
+
:param border: Border width, in pixels.
|
491 |
+
:param fill: Pixel fill value (a color value). Default is 0 (black).
|
492 |
+
:return: An image.
|
493 |
+
"""
|
494 |
+
left, top, right, bottom = _border(border)
|
495 |
+
width = left + image.size[0] + right
|
496 |
+
height = top + image.size[1] + bottom
|
497 |
+
color = _color(fill, image.mode)
|
498 |
+
if image.palette:
|
499 |
+
palette = ImagePalette.ImagePalette(palette=image.getpalette())
|
500 |
+
if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
|
501 |
+
color = palette.getcolor(color)
|
502 |
+
else:
|
503 |
+
palette = None
|
504 |
+
out = Image.new(image.mode, (width, height), color)
|
505 |
+
if palette:
|
506 |
+
out.putpalette(palette.palette)
|
507 |
+
out.paste(image, (left, top))
|
508 |
+
return out
|
509 |
+
|
510 |
+
|
511 |
+
def fit(
|
512 |
+
image: Image.Image,
|
513 |
+
size: tuple[int, int],
|
514 |
+
method: int = Image.Resampling.BICUBIC,
|
515 |
+
bleed: float = 0.0,
|
516 |
+
centering: tuple[float, float] = (0.5, 0.5),
|
517 |
+
) -> Image.Image:
|
518 |
+
"""
|
519 |
+
Returns a resized and cropped version of the image, cropped to the
|
520 |
+
requested aspect ratio and size.
|
521 |
+
|
522 |
+
This function was contributed by Kevin Cazabon.
|
523 |
+
|
524 |
+
:param image: The image to resize and crop.
|
525 |
+
:param size: The requested output size in pixels, given as a
|
526 |
+
(width, height) tuple.
|
527 |
+
:param method: Resampling method to use. Default is
|
528 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
529 |
+
See :ref:`concept-filters`.
|
530 |
+
:param bleed: Remove a border around the outside of the image from all
|
531 |
+
four edges. The value is a decimal percentage (use 0.01 for
|
532 |
+
one percent). The default value is 0 (no border).
|
533 |
+
Cannot be greater than or equal to 0.5.
|
534 |
+
:param centering: Control the cropping position. Use (0.5, 0.5) for
|
535 |
+
center cropping (e.g. if cropping the width, take 50% off
|
536 |
+
of the left side, and therefore 50% off the right side).
|
537 |
+
(0.0, 0.0) will crop from the top left corner (i.e. if
|
538 |
+
cropping the width, take all of the crop off of the right
|
539 |
+
side, and if cropping the height, take all of it off the
|
540 |
+
bottom). (1.0, 0.0) will crop from the bottom left
|
541 |
+
corner, etc. (i.e. if cropping the width, take all of the
|
542 |
+
crop off the left side, and if cropping the height take
|
543 |
+
none from the top, and therefore all off the bottom).
|
544 |
+
:return: An image.
|
545 |
+
"""
|
546 |
+
|
547 |
+
# by Kevin Cazabon, Feb 17/2000
|
548 | |
549 |
+
# https://www.cazabon.com
|
550 |
+
|
551 |
+
centering_x, centering_y = centering
|
552 |
+
|
553 |
+
if not 0.0 <= centering_x <= 1.0:
|
554 |
+
centering_x = 0.5
|
555 |
+
if not 0.0 <= centering_y <= 1.0:
|
556 |
+
centering_y = 0.5
|
557 |
+
|
558 |
+
if not 0.0 <= bleed < 0.5:
|
559 |
+
bleed = 0.0
|
560 |
+
|
561 |
+
# calculate the area to use for resizing and cropping, subtracting
|
562 |
+
# the 'bleed' around the edges
|
563 |
+
|
564 |
+
# number of pixels to trim off on Top and Bottom, Left and Right
|
565 |
+
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
|
566 |
+
|
567 |
+
live_size = (
|
568 |
+
image.size[0] - bleed_pixels[0] * 2,
|
569 |
+
image.size[1] - bleed_pixels[1] * 2,
|
570 |
+
)
|
571 |
+
|
572 |
+
# calculate the aspect ratio of the live_size
|
573 |
+
live_size_ratio = live_size[0] / live_size[1]
|
574 |
+
|
575 |
+
# calculate the aspect ratio of the output image
|
576 |
+
output_ratio = size[0] / size[1]
|
577 |
+
|
578 |
+
# figure out if the sides or top/bottom will be cropped off
|
579 |
+
if live_size_ratio == output_ratio:
|
580 |
+
# live_size is already the needed ratio
|
581 |
+
crop_width = live_size[0]
|
582 |
+
crop_height = live_size[1]
|
583 |
+
elif live_size_ratio >= output_ratio:
|
584 |
+
# live_size is wider than what's needed, crop the sides
|
585 |
+
crop_width = output_ratio * live_size[1]
|
586 |
+
crop_height = live_size[1]
|
587 |
+
else:
|
588 |
+
# live_size is taller than what's needed, crop the top and bottom
|
589 |
+
crop_width = live_size[0]
|
590 |
+
crop_height = live_size[0] / output_ratio
|
591 |
+
|
592 |
+
# make the crop
|
593 |
+
crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
|
594 |
+
crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
|
595 |
+
|
596 |
+
crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
|
597 |
+
|
598 |
+
# resize the image and return it
|
599 |
+
return image.resize(size, method, box=crop)
|
600 |
+
|
601 |
+
|
602 |
+
def flip(image: Image.Image) -> Image.Image:
|
603 |
+
"""
|
604 |
+
Flip the image vertically (top to bottom).
|
605 |
+
|
606 |
+
:param image: The image to flip.
|
607 |
+
:return: An image.
|
608 |
+
"""
|
609 |
+
return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
|
610 |
+
|
611 |
+
|
612 |
+
def grayscale(image: Image.Image) -> Image.Image:
|
613 |
+
"""
|
614 |
+
Convert the image to grayscale.
|
615 |
+
|
616 |
+
:param image: The image to convert.
|
617 |
+
:return: An image.
|
618 |
+
"""
|
619 |
+
return image.convert("L")
|
620 |
+
|
621 |
+
|
622 |
+
def invert(image: Image.Image) -> Image.Image:
|
623 |
+
"""
|
624 |
+
Invert (negate) the image.
|
625 |
+
|
626 |
+
:param image: The image to invert.
|
627 |
+
:return: An image.
|
628 |
+
"""
|
629 |
+
lut = list(range(255, -1, -1))
|
630 |
+
return image.point(lut) if image.mode == "1" else _lut(image, lut)
|
631 |
+
|
632 |
+
|
633 |
+
def mirror(image: Image.Image) -> Image.Image:
|
634 |
+
"""
|
635 |
+
Flip image horizontally (left to right).
|
636 |
+
|
637 |
+
:param image: The image to mirror.
|
638 |
+
:return: An image.
|
639 |
+
"""
|
640 |
+
return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
641 |
+
|
642 |
+
|
643 |
+
def posterize(image: Image.Image, bits: int) -> Image.Image:
|
644 |
+
"""
|
645 |
+
Reduce the number of bits for each color channel.
|
646 |
+
|
647 |
+
:param image: The image to posterize.
|
648 |
+
:param bits: The number of bits to keep for each channel (1-8).
|
649 |
+
:return: An image.
|
650 |
+
"""
|
651 |
+
mask = ~(2 ** (8 - bits) - 1)
|
652 |
+
lut = [i & mask for i in range(256)]
|
653 |
+
return _lut(image, lut)
|
654 |
+
|
655 |
+
|
656 |
+
def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
|
657 |
+
"""
|
658 |
+
Invert all pixel values above a threshold.
|
659 |
+
|
660 |
+
:param image: The image to solarize.
|
661 |
+
:param threshold: All pixels above this grayscale level are inverted.
|
662 |
+
:return: An image.
|
663 |
+
"""
|
664 |
+
lut = []
|
665 |
+
for i in range(256):
|
666 |
+
if i < threshold:
|
667 |
+
lut.append(i)
|
668 |
+
else:
|
669 |
+
lut.append(255 - i)
|
670 |
+
return _lut(image, lut)
|
671 |
+
|
672 |
+
|
673 |
+
def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
|
674 |
+
"""
|
675 |
+
If an image has an EXIF Orientation tag, other than 1, transpose the image
|
676 |
+
accordingly, and remove the orientation data.
|
677 |
+
|
678 |
+
:param image: The image to transpose.
|
679 |
+
:param in_place: Boolean. Keyword-only argument.
|
680 |
+
If ``True``, the original image is modified in-place, and ``None`` is returned.
|
681 |
+
If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
|
682 |
+
with the transposition applied. If there is no transposition, a copy of the
|
683 |
+
image will be returned.
|
684 |
+
"""
|
685 |
+
image.load()
|
686 |
+
image_exif = image.getexif()
|
687 |
+
orientation = image_exif.get(ExifTags.Base.Orientation, 1)
|
688 |
+
method = {
|
689 |
+
2: Image.Transpose.FLIP_LEFT_RIGHT,
|
690 |
+
3: Image.Transpose.ROTATE_180,
|
691 |
+
4: Image.Transpose.FLIP_TOP_BOTTOM,
|
692 |
+
5: Image.Transpose.TRANSPOSE,
|
693 |
+
6: Image.Transpose.ROTATE_270,
|
694 |
+
7: Image.Transpose.TRANSVERSE,
|
695 |
+
8: Image.Transpose.ROTATE_90,
|
696 |
+
}.get(orientation)
|
697 |
+
if method is not None:
|
698 |
+
transposed_image = image.transpose(method)
|
699 |
+
if in_place:
|
700 |
+
image.im = transposed_image.im
|
701 |
+
image.pyaccess = None
|
702 |
+
image._size = transposed_image._size
|
703 |
+
exif_image = image if in_place else transposed_image
|
704 |
+
|
705 |
+
exif = exif_image.getexif()
|
706 |
+
if ExifTags.Base.Orientation in exif:
|
707 |
+
del exif[ExifTags.Base.Orientation]
|
708 |
+
if "exif" in exif_image.info:
|
709 |
+
exif_image.info["exif"] = exif.tobytes()
|
710 |
+
elif "Raw profile type exif" in exif_image.info:
|
711 |
+
exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
|
712 |
+
for key in ("XML:com.adobe.xmp", "xmp"):
|
713 |
+
if key in exif_image.info:
|
714 |
+
for pattern in (
|
715 |
+
r'tiff:Orientation="([0-9])"',
|
716 |
+
r"<tiff:Orientation>([0-9])</tiff:Orientation>",
|
717 |
+
):
|
718 |
+
value = exif_image.info[key]
|
719 |
+
exif_image.info[key] = (
|
720 |
+
re.sub(pattern, "", value)
|
721 |
+
if isinstance(value, str)
|
722 |
+
else re.sub(pattern.encode(), b"", value)
|
723 |
+
)
|
724 |
+
if not in_place:
|
725 |
+
return transposed_image
|
726 |
+
elif not in_place:
|
727 |
+
return image.copy()
|
728 |
+
return None
|
MLPY/Lib/site-packages/PIL/ImagePalette.py
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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running.
|
10 |
+
# 1997-08-23 fl Added load hack
|
11 |
+
# 2001-04-16 fl Fixed randint shadow bug in random()
|
12 |
+
#
|
13 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
14 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh
|
15 |
+
#
|
16 |
+
# See the README file for information on usage and redistribution.
|
17 |
+
#
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
import array
|
21 |
+
from typing import IO, TYPE_CHECKING, Sequence
|
22 |
+
|
23 |
+
from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
|
24 |
+
|
25 |
+
if TYPE_CHECKING:
|
26 |
+
from . import Image
|
27 |
+
|
28 |
+
|
29 |
+
class ImagePalette:
|
30 |
+
"""
|
31 |
+
Color palette for palette mapped images
|
32 |
+
|
33 |
+
:param mode: The mode to use for the palette. See:
|
34 |
+
:ref:`concept-modes`. Defaults to "RGB"
|
35 |
+
:param palette: An optional palette. If given, it must be a bytearray,
|
36 |
+
an array or a list of ints between 0-255. The list must consist of
|
37 |
+
all channels for one color followed by the next color (e.g. RGBRGBRGB).
|
38 |
+
Defaults to an empty palette.
|
39 |
+
"""
|
40 |
+
|
41 |
+
def __init__(
|
42 |
+
self,
|
43 |
+
mode: str = "RGB",
|
44 |
+
palette: Sequence[int] | bytes | bytearray | None = None,
|
45 |
+
) -> None:
|
46 |
+
self.mode = mode
|
47 |
+
self.rawmode: str | None = None # if set, palette contains raw data
|
48 |
+
self.palette = palette or bytearray()
|
49 |
+
self.dirty: int | None = None
|
50 |
+
|
51 |
+
@property
|
52 |
+
def palette(self) -> Sequence[int] | bytes | bytearray:
|
53 |
+
return self._palette
|
54 |
+
|
55 |
+
@palette.setter
|
56 |
+
def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
|
57 |
+
self._colors: dict[tuple[int, ...], int] | None = None
|
58 |
+
self._palette = palette
|
59 |
+
|
60 |
+
@property
|
61 |
+
def colors(self) -> dict[tuple[int, ...], int]:
|
62 |
+
if self._colors is None:
|
63 |
+
mode_len = len(self.mode)
|
64 |
+
self._colors = {}
|
65 |
+
for i in range(0, len(self.palette), mode_len):
|
66 |
+
color = tuple(self.palette[i : i + mode_len])
|
67 |
+
if color in self._colors:
|
68 |
+
continue
|
69 |
+
self._colors[color] = i // mode_len
|
70 |
+
return self._colors
|
71 |
+
|
72 |
+
@colors.setter
|
73 |
+
def colors(self, colors: dict[tuple[int, ...], int]) -> None:
|
74 |
+
self._colors = colors
|
75 |
+
|
76 |
+
def copy(self) -> ImagePalette:
|
77 |
+
new = ImagePalette()
|
78 |
+
|
79 |
+
new.mode = self.mode
|
80 |
+
new.rawmode = self.rawmode
|
81 |
+
if self.palette is not None:
|
82 |
+
new.palette = self.palette[:]
|
83 |
+
new.dirty = self.dirty
|
84 |
+
|
85 |
+
return new
|
86 |
+
|
87 |
+
def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
|
88 |
+
"""
|
89 |
+
Get palette contents in format suitable for the low-level
|
90 |
+
``im.putpalette`` primitive.
|
91 |
+
|
92 |
+
.. warning:: This method is experimental.
|
93 |
+
"""
|
94 |
+
if self.rawmode:
|
95 |
+
return self.rawmode, self.palette
|
96 |
+
return self.mode, self.tobytes()
|
97 |
+
|
98 |
+
def tobytes(self) -> bytes:
|
99 |
+
"""Convert palette to bytes.
|
100 |
+
|
101 |
+
.. warning:: This method is experimental.
|
102 |
+
"""
|
103 |
+
if self.rawmode:
|
104 |
+
msg = "palette contains raw palette data"
|
105 |
+
raise ValueError(msg)
|
106 |
+
if isinstance(self.palette, bytes):
|
107 |
+
return self.palette
|
108 |
+
arr = array.array("B", self.palette)
|
109 |
+
return arr.tobytes()
|
110 |
+
|
111 |
+
# Declare tostring as an alias for tobytes
|
112 |
+
tostring = tobytes
|
113 |
+
|
114 |
+
def _new_color_index(
|
115 |
+
self, image: Image.Image | None = None, e: Exception | None = None
|
116 |
+
) -> int:
|
117 |
+
if not isinstance(self.palette, bytearray):
|
118 |
+
self._palette = bytearray(self.palette)
|
119 |
+
index = len(self.palette) // 3
|
120 |
+
special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
|
121 |
+
if image:
|
122 |
+
special_colors = (
|
123 |
+
image.info.get("background"),
|
124 |
+
image.info.get("transparency"),
|
125 |
+
)
|
126 |
+
while index in special_colors:
|
127 |
+
index += 1
|
128 |
+
if index >= 256:
|
129 |
+
if image:
|
130 |
+
# Search for an unused index
|
131 |
+
for i, count in reversed(list(enumerate(image.histogram()))):
|
132 |
+
if count == 0 and i not in special_colors:
|
133 |
+
index = i
|
134 |
+
break
|
135 |
+
if index >= 256:
|
136 |
+
msg = "cannot allocate more than 256 colors"
|
137 |
+
raise ValueError(msg) from e
|
138 |
+
return index
|
139 |
+
|
140 |
+
def getcolor(
|
141 |
+
self,
|
142 |
+
color: tuple[int, ...],
|
143 |
+
image: Image.Image | None = None,
|
144 |
+
) -> int:
|
145 |
+
"""Given an rgb tuple, allocate palette entry.
|
146 |
+
|
147 |
+
.. warning:: This method is experimental.
|
148 |
+
"""
|
149 |
+
if self.rawmode:
|
150 |
+
msg = "palette contains raw palette data"
|
151 |
+
raise ValueError(msg)
|
152 |
+
if isinstance(color, tuple):
|
153 |
+
if self.mode == "RGB":
|
154 |
+
if len(color) == 4:
|
155 |
+
if color[3] != 255:
|
156 |
+
msg = "cannot add non-opaque RGBA color to RGB palette"
|
157 |
+
raise ValueError(msg)
|
158 |
+
color = color[:3]
|
159 |
+
elif self.mode == "RGBA":
|
160 |
+
if len(color) == 3:
|
161 |
+
color += (255,)
|
162 |
+
try:
|
163 |
+
return self.colors[color]
|
164 |
+
except KeyError as e:
|
165 |
+
# allocate new color slot
|
166 |
+
index = self._new_color_index(image, e)
|
167 |
+
assert isinstance(self._palette, bytearray)
|
168 |
+
self.colors[color] = index
|
169 |
+
if index * 3 < len(self.palette):
|
170 |
+
self._palette = (
|
171 |
+
self._palette[: index * 3]
|
172 |
+
+ bytes(color)
|
173 |
+
+ self._palette[index * 3 + 3 :]
|
174 |
+
)
|
175 |
+
else:
|
176 |
+
self._palette += bytes(color)
|
177 |
+
self.dirty = 1
|
178 |
+
return index
|
179 |
+
else:
|
180 |
+
msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
|
181 |
+
raise ValueError(msg)
|
182 |
+
|
183 |
+
def save(self, fp: str | IO[str]) -> None:
|
184 |
+
"""Save palette to text file.
|
185 |
+
|
186 |
+
.. warning:: This method is experimental.
|
187 |
+
"""
|
188 |
+
if self.rawmode:
|
189 |
+
msg = "palette contains raw palette data"
|
190 |
+
raise ValueError(msg)
|
191 |
+
if isinstance(fp, str):
|
192 |
+
fp = open(fp, "w")
|
193 |
+
fp.write("# Palette\n")
|
194 |
+
fp.write(f"# Mode: {self.mode}\n")
|
195 |
+
for i in range(256):
|
196 |
+
fp.write(f"{i}")
|
197 |
+
for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
|
198 |
+
try:
|
199 |
+
fp.write(f" {self.palette[j]}")
|
200 |
+
except IndexError:
|
201 |
+
fp.write(" 0")
|
202 |
+
fp.write("\n")
|
203 |
+
fp.close()
|
204 |
+
|
205 |
+
|
206 |
+
# --------------------------------------------------------------------
|
207 |
+
# Internal
|
208 |
+
|
209 |
+
|
210 |
+
def raw(rawmode, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
|
211 |
+
palette = ImagePalette()
|
212 |
+
palette.rawmode = rawmode
|
213 |
+
palette.palette = data
|
214 |
+
palette.dirty = 1
|
215 |
+
return palette
|
216 |
+
|
217 |
+
|
218 |
+
# --------------------------------------------------------------------
|
219 |
+
# Factories
|
220 |
+
|
221 |
+
|
222 |
+
def make_linear_lut(black: int, white: float) -> list[int]:
|
223 |
+
if black == 0:
|
224 |
+
return [int(white * i // 255) for i in range(256)]
|
225 |
+
|
226 |
+
msg = "unavailable when black is non-zero"
|
227 |
+
raise NotImplementedError(msg) # FIXME
|
228 |
+
|
229 |
+
|
230 |
+
def make_gamma_lut(exp: float) -> list[int]:
|
231 |
+
return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
|
232 |
+
|
233 |
+
|
234 |
+
def negative(mode: str = "RGB") -> ImagePalette:
|
235 |
+
palette = list(range(256 * len(mode)))
|
236 |
+
palette.reverse()
|
237 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
238 |
+
|
239 |
+
|
240 |
+
def random(mode: str = "RGB") -> ImagePalette:
|
241 |
+
from random import randint
|
242 |
+
|
243 |
+
palette = [randint(0, 255) for _ in range(256 * len(mode))]
|
244 |
+
return ImagePalette(mode, palette)
|
245 |
+
|
246 |
+
|
247 |
+
def sepia(white: str = "#fff0c0") -> ImagePalette:
|
248 |
+
bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
|
249 |
+
return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
|
250 |
+
|
251 |
+
|
252 |
+
def wedge(mode: str = "RGB") -> ImagePalette:
|
253 |
+
palette = list(range(256 * len(mode)))
|
254 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
255 |
+
|
256 |
+
|
257 |
+
def load(filename: str) -> tuple[bytes, str]:
|
258 |
+
# FIXME: supports GIMP gradients only
|
259 |
+
|
260 |
+
with open(filename, "rb") as fp:
|
261 |
+
paletteHandlers: list[
|
262 |
+
type[
|
263 |
+
GimpPaletteFile.GimpPaletteFile
|
264 |
+
| GimpGradientFile.GimpGradientFile
|
265 |
+
| PaletteFile.PaletteFile
|
266 |
+
]
|
267 |
+
] = [
|
268 |
+
GimpPaletteFile.GimpPaletteFile,
|
269 |
+
GimpGradientFile.GimpGradientFile,
|
270 |
+
PaletteFile.PaletteFile,
|
271 |
+
]
|
272 |
+
for paletteHandler in paletteHandlers:
|
273 |
+
try:
|
274 |
+
fp.seek(0)
|
275 |
+
lut = paletteHandler(fp).getpalette()
|
276 |
+
if lut:
|
277 |
+
break
|
278 |
+
except (SyntaxError, ValueError):
|
279 |
+
pass
|
280 |
+
else:
|
281 |
+
msg = "cannot load palette"
|
282 |
+
raise OSError(msg)
|
283 |
+
|
284 |
+
return lut # data, rawmode
|
MLPY/Lib/site-packages/PIL/ImagePath.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# path interface
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-11-04 fl Created
|
9 |
+
# 2002-04-14 fl Added documentation stub class
|
10 |
+
#
|
11 |
+
# Copyright (c) Secret Labs AB 1997.
|
12 |
+
# Copyright (c) Fredrik Lundh 1996.
|
13 |
+
#
|
14 |
+
# See the README file for information on usage and redistribution.
|
15 |
+
#
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
from . import Image
|
19 |
+
|
20 |
+
Path = Image.core.path
|
MLPY/Lib/site-packages/PIL/ImageQt.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# a simple Qt image interface.
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 2006-06-03 fl: created
|
9 |
+
# 2006-06-04 fl: inherit from QImage instead of wrapping it
|
10 |
+
# 2006-06-05 fl: removed toimage helper; move string support to ImageQt
|
11 |
+
# 2013-11-13 fl: add support for Qt5 ([email protected])
|
12 |
+
#
|
13 |
+
# Copyright (c) 2006 by Secret Labs AB
|
14 |
+
# Copyright (c) 2006 by Fredrik Lundh
|
15 |
+
#
|
16 |
+
# See the README file for information on usage and redistribution.
|
17 |
+
#
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
import sys
|
21 |
+
from io import BytesIO
|
22 |
+
from typing import Callable
|
23 |
+
|
24 |
+
from . import Image
|
25 |
+
from ._util import is_path
|
26 |
+
|
27 |
+
qt_version: str | None
|
28 |
+
qt_versions = [
|
29 |
+
["6", "PyQt6"],
|
30 |
+
["side6", "PySide6"],
|
31 |
+
]
|
32 |
+
|
33 |
+
# If a version has already been imported, attempt it first
|
34 |
+
qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
|
35 |
+
for version, qt_module in qt_versions:
|
36 |
+
try:
|
37 |
+
QBuffer: type
|
38 |
+
QIODevice: type
|
39 |
+
QImage: type
|
40 |
+
QPixmap: type
|
41 |
+
qRgba: Callable[[int, int, int, int], int]
|
42 |
+
if qt_module == "PyQt6":
|
43 |
+
from PyQt6.QtCore import QBuffer, QIODevice
|
44 |
+
from PyQt6.QtGui import QImage, QPixmap, qRgba
|
45 |
+
elif qt_module == "PySide6":
|
46 |
+
from PySide6.QtCore import QBuffer, QIODevice
|
47 |
+
from PySide6.QtGui import QImage, QPixmap, qRgba
|
48 |
+
except (ImportError, RuntimeError):
|
49 |
+
continue
|
50 |
+
qt_is_installed = True
|
51 |
+
qt_version = version
|
52 |
+
break
|
53 |
+
else:
|
54 |
+
qt_is_installed = False
|
55 |
+
qt_version = None
|
56 |
+
|
57 |
+
|
58 |
+
def rgb(r, g, b, a=255):
|
59 |
+
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
|
60 |
+
# use qRgb to pack the colors, and then turn the resulting long
|
61 |
+
# into a negative integer with the same bitpattern.
|
62 |
+
return qRgba(r, g, b, a) & 0xFFFFFFFF
|
63 |
+
|
64 |
+
|
65 |
+
def fromqimage(im):
|
66 |
+
"""
|
67 |
+
:param im: QImage or PIL ImageQt object
|
68 |
+
"""
|
69 |
+
buffer = QBuffer()
|
70 |
+
if qt_version == "6":
|
71 |
+
try:
|
72 |
+
qt_openmode = QIODevice.OpenModeFlag
|
73 |
+
except AttributeError:
|
74 |
+
qt_openmode = QIODevice.OpenMode
|
75 |
+
else:
|
76 |
+
qt_openmode = QIODevice
|
77 |
+
buffer.open(qt_openmode.ReadWrite)
|
78 |
+
# preserve alpha channel with png
|
79 |
+
# otherwise ppm is more friendly with Image.open
|
80 |
+
if im.hasAlphaChannel():
|
81 |
+
im.save(buffer, "png")
|
82 |
+
else:
|
83 |
+
im.save(buffer, "ppm")
|
84 |
+
|
85 |
+
b = BytesIO()
|
86 |
+
b.write(buffer.data())
|
87 |
+
buffer.close()
|
88 |
+
b.seek(0)
|
89 |
+
|
90 |
+
return Image.open(b)
|
91 |
+
|
92 |
+
|
93 |
+
def fromqpixmap(im):
|
94 |
+
return fromqimage(im)
|
95 |
+
|
96 |
+
|
97 |
+
def align8to32(bytes, width, mode):
|
98 |
+
"""
|
99 |
+
converts each scanline of data from 8 bit to 32 bit aligned
|
100 |
+
"""
|
101 |
+
|
102 |
+
bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
|
103 |
+
|
104 |
+
# calculate bytes per line and the extra padding if needed
|
105 |
+
bits_per_line = bits_per_pixel * width
|
106 |
+
full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
|
107 |
+
bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
|
108 |
+
|
109 |
+
extra_padding = -bytes_per_line % 4
|
110 |
+
|
111 |
+
# already 32 bit aligned by luck
|
112 |
+
if not extra_padding:
|
113 |
+
return bytes
|
114 |
+
|
115 |
+
new_data = [
|
116 |
+
bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
|
117 |
+
for i in range(len(bytes) // bytes_per_line)
|
118 |
+
]
|
119 |
+
|
120 |
+
return b"".join(new_data)
|
121 |
+
|
122 |
+
|
123 |
+
def _toqclass_helper(im):
|
124 |
+
data = None
|
125 |
+
colortable = None
|
126 |
+
exclusive_fp = False
|
127 |
+
|
128 |
+
# handle filename, if given instead of image name
|
129 |
+
if hasattr(im, "toUtf8"):
|
130 |
+
# FIXME - is this really the best way to do this?
|
131 |
+
im = str(im.toUtf8(), "utf-8")
|
132 |
+
if is_path(im):
|
133 |
+
im = Image.open(im)
|
134 |
+
exclusive_fp = True
|
135 |
+
|
136 |
+
qt_format = QImage.Format if qt_version == "6" else QImage
|
137 |
+
if im.mode == "1":
|
138 |
+
format = qt_format.Format_Mono
|
139 |
+
elif im.mode == "L":
|
140 |
+
format = qt_format.Format_Indexed8
|
141 |
+
colortable = [rgb(i, i, i) for i in range(256)]
|
142 |
+
elif im.mode == "P":
|
143 |
+
format = qt_format.Format_Indexed8
|
144 |
+
palette = im.getpalette()
|
145 |
+
colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
|
146 |
+
elif im.mode == "RGB":
|
147 |
+
# Populate the 4th channel with 255
|
148 |
+
im = im.convert("RGBA")
|
149 |
+
|
150 |
+
data = im.tobytes("raw", "BGRA")
|
151 |
+
format = qt_format.Format_RGB32
|
152 |
+
elif im.mode == "RGBA":
|
153 |
+
data = im.tobytes("raw", "BGRA")
|
154 |
+
format = qt_format.Format_ARGB32
|
155 |
+
elif im.mode == "I;16":
|
156 |
+
im = im.point(lambda i: i * 256)
|
157 |
+
|
158 |
+
format = qt_format.Format_Grayscale16
|
159 |
+
else:
|
160 |
+
if exclusive_fp:
|
161 |
+
im.close()
|
162 |
+
msg = f"unsupported image mode {repr(im.mode)}"
|
163 |
+
raise ValueError(msg)
|
164 |
+
|
165 |
+
size = im.size
|
166 |
+
__data = data or align8to32(im.tobytes(), size[0], im.mode)
|
167 |
+
if exclusive_fp:
|
168 |
+
im.close()
|
169 |
+
return {"data": __data, "size": size, "format": format, "colortable": colortable}
|
170 |
+
|
171 |
+
|
172 |
+
if qt_is_installed:
|
173 |
+
|
174 |
+
class ImageQt(QImage):
|
175 |
+
def __init__(self, im):
|
176 |
+
"""
|
177 |
+
An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
|
178 |
+
class.
|
179 |
+
|
180 |
+
:param im: A PIL Image object, or a file name (given either as
|
181 |
+
Python string or a PyQt string object).
|
182 |
+
"""
|
183 |
+
im_data = _toqclass_helper(im)
|
184 |
+
# must keep a reference, or Qt will crash!
|
185 |
+
# All QImage constructors that take data operate on an existing
|
186 |
+
# buffer, so this buffer has to hang on for the life of the image.
|
187 |
+
# Fixes https://github.com/python-pillow/Pillow/issues/1370
|
188 |
+
self.__data = im_data["data"]
|
189 |
+
super().__init__(
|
190 |
+
self.__data,
|
191 |
+
im_data["size"][0],
|
192 |
+
im_data["size"][1],
|
193 |
+
im_data["format"],
|
194 |
+
)
|
195 |
+
if im_data["colortable"]:
|
196 |
+
self.setColorTable(im_data["colortable"])
|
197 |
+
|
198 |
+
|
199 |
+
def toqimage(im) -> ImageQt:
|
200 |
+
return ImageQt(im)
|
201 |
+
|
202 |
+
|
203 |
+
def toqpixmap(im):
|
204 |
+
qimage = toqimage(im)
|
205 |
+
return QPixmap.fromImage(qimage)
|
MLPY/Lib/site-packages/PIL/ImageSequence.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# sequence support classes
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 1997-02-20 fl Created
|
9 |
+
#
|
10 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
11 |
+
# Copyright (c) 1997 by Fredrik Lundh.
|
12 |
+
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
|
16 |
+
##
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
from typing import Callable
|
20 |
+
|
21 |
+
from . import Image
|
22 |
+
|
23 |
+
|
24 |
+
class Iterator:
|
25 |
+
"""
|
26 |
+
This class implements an iterator object that can be used to loop
|
27 |
+
over an image sequence.
|
28 |
+
|
29 |
+
You can use the ``[]`` operator to access elements by index. This operator
|
30 |
+
will raise an :py:exc:`IndexError` if you try to access a nonexistent
|
31 |
+
frame.
|
32 |
+
|
33 |
+
:param im: An image object.
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(self, im: Image.Image):
|
37 |
+
if not hasattr(im, "seek"):
|
38 |
+
msg = "im must have seek method"
|
39 |
+
raise AttributeError(msg)
|
40 |
+
self.im = im
|
41 |
+
self.position = getattr(self.im, "_min_frame", 0)
|
42 |
+
|
43 |
+
def __getitem__(self, ix: int) -> Image.Image:
|
44 |
+
try:
|
45 |
+
self.im.seek(ix)
|
46 |
+
return self.im
|
47 |
+
except EOFError as e:
|
48 |
+
msg = "end of sequence"
|
49 |
+
raise IndexError(msg) from e
|
50 |
+
|
51 |
+
def __iter__(self) -> Iterator:
|
52 |
+
return self
|
53 |
+
|
54 |
+
def __next__(self) -> Image.Image:
|
55 |
+
try:
|
56 |
+
self.im.seek(self.position)
|
57 |
+
self.position += 1
|
58 |
+
return self.im
|
59 |
+
except EOFError as e:
|
60 |
+
msg = "end of sequence"
|
61 |
+
raise StopIteration(msg) from e
|
62 |
+
|
63 |
+
|
64 |
+
def all_frames(
|
65 |
+
im: Image.Image | list[Image.Image],
|
66 |
+
func: Callable[[Image.Image], Image.Image] | None = None,
|
67 |
+
) -> list[Image.Image]:
|
68 |
+
"""
|
69 |
+
Applies a given function to all frames in an image or a list of images.
|
70 |
+
The frames are returned as a list of separate images.
|
71 |
+
|
72 |
+
:param im: An image, or a list of images.
|
73 |
+
:param func: The function to apply to all of the image frames.
|
74 |
+
:returns: A list of images.
|
75 |
+
"""
|
76 |
+
if not isinstance(im, list):
|
77 |
+
im = [im]
|
78 |
+
|
79 |
+
ims = []
|
80 |
+
for imSequence in im:
|
81 |
+
current = imSequence.tell()
|
82 |
+
|
83 |
+
ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
|
84 |
+
|
85 |
+
imSequence.seek(current)
|
86 |
+
return [func(im) for im in ims] if func else ims
|
MLPY/Lib/site-packages/PIL/ImageShow.py
ADDED
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# im.show() drivers
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2008-04-06 fl Created
|
9 |
+
#
|
10 |
+
# Copyright (c) Secret Labs AB 2008.
|
11 |
+
#
|
12 |
+
# See the README file for information on usage and redistribution.
|
13 |
+
#
|
14 |
+
from __future__ import annotations
|
15 |
+
|
16 |
+
import abc
|
17 |
+
import os
|
18 |
+
import shutil
|
19 |
+
import subprocess
|
20 |
+
import sys
|
21 |
+
from shlex import quote
|
22 |
+
from typing import Any
|
23 |
+
|
24 |
+
from . import Image
|
25 |
+
|
26 |
+
_viewers = []
|
27 |
+
|
28 |
+
|
29 |
+
def register(viewer, order: int = 1) -> None:
|
30 |
+
"""
|
31 |
+
The :py:func:`register` function is used to register additional viewers::
|
32 |
+
|
33 |
+
from PIL import ImageShow
|
34 |
+
ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
|
35 |
+
ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
|
36 |
+
ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
|
37 |
+
|
38 |
+
:param viewer: The viewer to be registered.
|
39 |
+
:param order:
|
40 |
+
Zero or a negative integer to prepend this viewer to the list,
|
41 |
+
a positive integer to append it.
|
42 |
+
"""
|
43 |
+
try:
|
44 |
+
if issubclass(viewer, Viewer):
|
45 |
+
viewer = viewer()
|
46 |
+
except TypeError:
|
47 |
+
pass # raised if viewer wasn't a class
|
48 |
+
if order > 0:
|
49 |
+
_viewers.append(viewer)
|
50 |
+
else:
|
51 |
+
_viewers.insert(0, viewer)
|
52 |
+
|
53 |
+
|
54 |
+
def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
|
55 |
+
r"""
|
56 |
+
Display a given image.
|
57 |
+
|
58 |
+
:param image: An image object.
|
59 |
+
:param title: Optional title. Not all viewers can display the title.
|
60 |
+
:param \**options: Additional viewer options.
|
61 |
+
:returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
|
62 |
+
"""
|
63 |
+
for viewer in _viewers:
|
64 |
+
if viewer.show(image, title=title, **options):
|
65 |
+
return True
|
66 |
+
return False
|
67 |
+
|
68 |
+
|
69 |
+
class Viewer:
|
70 |
+
"""Base class for viewers."""
|
71 |
+
|
72 |
+
# main api
|
73 |
+
|
74 |
+
def show(self, image: Image.Image, **options: Any) -> int:
|
75 |
+
"""
|
76 |
+
The main function for displaying an image.
|
77 |
+
Converts the given image to the target format and displays it.
|
78 |
+
"""
|
79 |
+
|
80 |
+
if not (
|
81 |
+
image.mode in ("1", "RGBA")
|
82 |
+
or (self.format == "PNG" and image.mode in ("I;16", "LA"))
|
83 |
+
):
|
84 |
+
base = Image.getmodebase(image.mode)
|
85 |
+
if image.mode != base:
|
86 |
+
image = image.convert(base)
|
87 |
+
|
88 |
+
return self.show_image(image, **options)
|
89 |
+
|
90 |
+
# hook methods
|
91 |
+
|
92 |
+
format: str | None = None
|
93 |
+
"""The format to convert the image into."""
|
94 |
+
options: dict[str, Any] = {}
|
95 |
+
"""Additional options used to convert the image."""
|
96 |
+
|
97 |
+
def get_format(self, image: Image.Image) -> str | None:
|
98 |
+
"""Return format name, or ``None`` to save as PGM/PPM."""
|
99 |
+
return self.format
|
100 |
+
|
101 |
+
def get_command(self, file: str, **options: Any) -> str:
|
102 |
+
"""
|
103 |
+
Returns the command used to display the file.
|
104 |
+
Not implemented in the base class.
|
105 |
+
"""
|
106 |
+
msg = "unavailable in base viewer"
|
107 |
+
raise NotImplementedError(msg)
|
108 |
+
|
109 |
+
def save_image(self, image: Image.Image) -> str:
|
110 |
+
"""Save to temporary file and return filename."""
|
111 |
+
return image._dump(format=self.get_format(image), **self.options)
|
112 |
+
|
113 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
114 |
+
"""Display the given image."""
|
115 |
+
return self.show_file(self.save_image(image), **options)
|
116 |
+
|
117 |
+
def show_file(self, path: str, **options: Any) -> int:
|
118 |
+
"""
|
119 |
+
Display given file.
|
120 |
+
"""
|
121 |
+
if not os.path.exists(path):
|
122 |
+
raise FileNotFoundError
|
123 |
+
os.system(self.get_command(path, **options)) # nosec
|
124 |
+
return 1
|
125 |
+
|
126 |
+
|
127 |
+
# --------------------------------------------------------------------
|
128 |
+
|
129 |
+
|
130 |
+
class WindowsViewer(Viewer):
|
131 |
+
"""The default viewer on Windows is the default system application for PNG files."""
|
132 |
+
|
133 |
+
format = "PNG"
|
134 |
+
options = {"compress_level": 1, "save_all": True}
|
135 |
+
|
136 |
+
def get_command(self, file: str, **options: Any) -> str:
|
137 |
+
return (
|
138 |
+
f'start "Pillow" /WAIT "{file}" '
|
139 |
+
"&& ping -n 4 127.0.0.1 >NUL "
|
140 |
+
f'&& del /f "{file}"'
|
141 |
+
)
|
142 |
+
|
143 |
+
def show_file(self, path: str, **options: Any) -> int:
|
144 |
+
"""
|
145 |
+
Display given file.
|
146 |
+
"""
|
147 |
+
if not os.path.exists(path):
|
148 |
+
raise FileNotFoundError
|
149 |
+
subprocess.Popen(
|
150 |
+
self.get_command(path, **options),
|
151 |
+
shell=True,
|
152 |
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
|
153 |
+
) # nosec
|
154 |
+
return 1
|
155 |
+
|
156 |
+
|
157 |
+
if sys.platform == "win32":
|
158 |
+
register(WindowsViewer)
|
159 |
+
|
160 |
+
|
161 |
+
class MacViewer(Viewer):
|
162 |
+
"""The default viewer on macOS using ``Preview.app``."""
|
163 |
+
|
164 |
+
format = "PNG"
|
165 |
+
options = {"compress_level": 1, "save_all": True}
|
166 |
+
|
167 |
+
def get_command(self, file: str, **options: Any) -> str:
|
168 |
+
# on darwin open returns immediately resulting in the temp
|
169 |
+
# file removal while app is opening
|
170 |
+
command = "open -a Preview.app"
|
171 |
+
command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
|
172 |
+
return command
|
173 |
+
|
174 |
+
def show_file(self, path: str, **options: Any) -> int:
|
175 |
+
"""
|
176 |
+
Display given file.
|
177 |
+
"""
|
178 |
+
if not os.path.exists(path):
|
179 |
+
raise FileNotFoundError
|
180 |
+
subprocess.call(["open", "-a", "Preview.app", path])
|
181 |
+
executable = sys.executable or shutil.which("python3")
|
182 |
+
if executable:
|
183 |
+
subprocess.Popen(
|
184 |
+
[
|
185 |
+
executable,
|
186 |
+
"-c",
|
187 |
+
"import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
|
188 |
+
path,
|
189 |
+
]
|
190 |
+
)
|
191 |
+
return 1
|
192 |
+
|
193 |
+
|
194 |
+
if sys.platform == "darwin":
|
195 |
+
register(MacViewer)
|
196 |
+
|
197 |
+
|
198 |
+
class UnixViewer(Viewer):
|
199 |
+
format = "PNG"
|
200 |
+
options = {"compress_level": 1, "save_all": True}
|
201 |
+
|
202 |
+
@abc.abstractmethod
|
203 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
204 |
+
pass
|
205 |
+
|
206 |
+
def get_command(self, file: str, **options: Any) -> str:
|
207 |
+
command = self.get_command_ex(file, **options)[0]
|
208 |
+
return f"{command} {quote(file)}"
|
209 |
+
|
210 |
+
|
211 |
+
class XDGViewer(UnixViewer):
|
212 |
+
"""
|
213 |
+
The freedesktop.org ``xdg-open`` command.
|
214 |
+
"""
|
215 |
+
|
216 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
217 |
+
command = executable = "xdg-open"
|
218 |
+
return command, executable
|
219 |
+
|
220 |
+
def show_file(self, path: str, **options: Any) -> int:
|
221 |
+
"""
|
222 |
+
Display given file.
|
223 |
+
"""
|
224 |
+
if not os.path.exists(path):
|
225 |
+
raise FileNotFoundError
|
226 |
+
subprocess.Popen(["xdg-open", path])
|
227 |
+
return 1
|
228 |
+
|
229 |
+
|
230 |
+
class DisplayViewer(UnixViewer):
|
231 |
+
"""
|
232 |
+
The ImageMagick ``display`` command.
|
233 |
+
This viewer supports the ``title`` parameter.
|
234 |
+
"""
|
235 |
+
|
236 |
+
def get_command_ex(
|
237 |
+
self, file: str, title: str | None = None, **options: Any
|
238 |
+
) -> tuple[str, str]:
|
239 |
+
command = executable = "display"
|
240 |
+
if title:
|
241 |
+
command += f" -title {quote(title)}"
|
242 |
+
return command, executable
|
243 |
+
|
244 |
+
def show_file(self, path: str, **options: Any) -> int:
|
245 |
+
"""
|
246 |
+
Display given file.
|
247 |
+
"""
|
248 |
+
if not os.path.exists(path):
|
249 |
+
raise FileNotFoundError
|
250 |
+
args = ["display"]
|
251 |
+
title = options.get("title")
|
252 |
+
if title:
|
253 |
+
args += ["-title", title]
|
254 |
+
args.append(path)
|
255 |
+
|
256 |
+
subprocess.Popen(args)
|
257 |
+
return 1
|
258 |
+
|
259 |
+
|
260 |
+
class GmDisplayViewer(UnixViewer):
|
261 |
+
"""The GraphicsMagick ``gm display`` command."""
|
262 |
+
|
263 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
264 |
+
executable = "gm"
|
265 |
+
command = "gm display"
|
266 |
+
return command, executable
|
267 |
+
|
268 |
+
def show_file(self, path: str, **options: Any) -> int:
|
269 |
+
"""
|
270 |
+
Display given file.
|
271 |
+
"""
|
272 |
+
if not os.path.exists(path):
|
273 |
+
raise FileNotFoundError
|
274 |
+
subprocess.Popen(["gm", "display", path])
|
275 |
+
return 1
|
276 |
+
|
277 |
+
|
278 |
+
class EogViewer(UnixViewer):
|
279 |
+
"""The GNOME Image Viewer ``eog`` command."""
|
280 |
+
|
281 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
282 |
+
executable = "eog"
|
283 |
+
command = "eog -n"
|
284 |
+
return command, executable
|
285 |
+
|
286 |
+
def show_file(self, path: str, **options: Any) -> int:
|
287 |
+
"""
|
288 |
+
Display given file.
|
289 |
+
"""
|
290 |
+
if not os.path.exists(path):
|
291 |
+
raise FileNotFoundError
|
292 |
+
subprocess.Popen(["eog", "-n", path])
|
293 |
+
return 1
|
294 |
+
|
295 |
+
|
296 |
+
class XVViewer(UnixViewer):
|
297 |
+
"""
|
298 |
+
The X Viewer ``xv`` command.
|
299 |
+
This viewer supports the ``title`` parameter.
|
300 |
+
"""
|
301 |
+
|
302 |
+
def get_command_ex(
|
303 |
+
self, file: str, title: str | None = None, **options: Any
|
304 |
+
) -> tuple[str, str]:
|
305 |
+
# note: xv is pretty outdated. most modern systems have
|
306 |
+
# imagemagick's display command instead.
|
307 |
+
command = executable = "xv"
|
308 |
+
if title:
|
309 |
+
command += f" -name {quote(title)}"
|
310 |
+
return command, executable
|
311 |
+
|
312 |
+
def show_file(self, path: str, **options: Any) -> int:
|
313 |
+
"""
|
314 |
+
Display given file.
|
315 |
+
"""
|
316 |
+
if not os.path.exists(path):
|
317 |
+
raise FileNotFoundError
|
318 |
+
args = ["xv"]
|
319 |
+
title = options.get("title")
|
320 |
+
if title:
|
321 |
+
args += ["-name", title]
|
322 |
+
args.append(path)
|
323 |
+
|
324 |
+
subprocess.Popen(args)
|
325 |
+
return 1
|
326 |
+
|
327 |
+
|
328 |
+
if sys.platform not in ("win32", "darwin"): # unixoids
|
329 |
+
if shutil.which("xdg-open"):
|
330 |
+
register(XDGViewer)
|
331 |
+
if shutil.which("display"):
|
332 |
+
register(DisplayViewer)
|
333 |
+
if shutil.which("gm"):
|
334 |
+
register(GmDisplayViewer)
|
335 |
+
if shutil.which("eog"):
|
336 |
+
register(EogViewer)
|
337 |
+
if shutil.which("xv"):
|
338 |
+
register(XVViewer)
|
339 |
+
|
340 |
+
|
341 |
+
class IPythonViewer(Viewer):
|
342 |
+
"""The viewer for IPython frontends."""
|
343 |
+
|
344 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
345 |
+
ipython_display(image)
|
346 |
+
return 1
|
347 |
+
|
348 |
+
|
349 |
+
try:
|
350 |
+
from IPython.display import display as ipython_display
|
351 |
+
except ImportError:
|
352 |
+
pass
|
353 |
+
else:
|
354 |
+
register(IPythonViewer)
|
355 |
+
|
356 |
+
|
357 |
+
if __name__ == "__main__":
|
358 |
+
if len(sys.argv) < 2:
|
359 |
+
print("Syntax: python3 ImageShow.py imagefile [title]")
|
360 |
+
sys.exit()
|
361 |
+
|
362 |
+
with Image.open(sys.argv[1]) as im:
|
363 |
+
print(show(im, *sys.argv[2:]))
|
MLPY/Lib/site-packages/PIL/ImageStat.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# global image statistics
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-04-05 fl Created
|
9 |
+
# 1997-05-21 fl Added mask; added rms, var, stddev attributes
|
10 |
+
# 1997-08-05 fl Added median
|
11 |
+
# 1998-07-05 hk Fixed integer overflow error
|
12 |
+
#
|
13 |
+
# Notes:
|
14 |
+
# This class shows how to implement delayed evaluation of attributes.
|
15 |
+
# To get a certain value, simply access the corresponding attribute.
|
16 |
+
# The __getattr__ dispatcher takes care of the rest.
|
17 |
+
#
|
18 |
+
# Copyright (c) Secret Labs AB 1997.
|
19 |
+
# Copyright (c) Fredrik Lundh 1996-97.
|
20 |
+
#
|
21 |
+
# See the README file for information on usage and redistribution.
|
22 |
+
#
|
23 |
+
from __future__ import annotations
|
24 |
+
|
25 |
+
import math
|
26 |
+
from functools import cached_property
|
27 |
+
|
28 |
+
from . import Image
|
29 |
+
|
30 |
+
|
31 |
+
class Stat:
|
32 |
+
def __init__(
|
33 |
+
self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
|
34 |
+
) -> None:
|
35 |
+
"""
|
36 |
+
Calculate statistics for the given image. If a mask is included,
|
37 |
+
only the regions covered by that mask are included in the
|
38 |
+
statistics. You can also pass in a previously calculated histogram.
|
39 |
+
|
40 |
+
:param image: A PIL image, or a precalculated histogram.
|
41 |
+
|
42 |
+
.. note::
|
43 |
+
|
44 |
+
For a PIL image, calculations rely on the
|
45 |
+
:py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
|
46 |
+
grouped into 256 bins, even if the image has more than 8 bits per
|
47 |
+
channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
|
48 |
+
``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
|
49 |
+
of more than 255.
|
50 |
+
|
51 |
+
:param mask: An optional mask.
|
52 |
+
"""
|
53 |
+
if isinstance(image_or_list, Image.Image):
|
54 |
+
self.h = image_or_list.histogram(mask)
|
55 |
+
elif isinstance(image_or_list, list):
|
56 |
+
self.h = image_or_list
|
57 |
+
else:
|
58 |
+
msg = "first argument must be image or list" # type: ignore[unreachable]
|
59 |
+
raise TypeError(msg)
|
60 |
+
self.bands = list(range(len(self.h) // 256))
|
61 |
+
|
62 |
+
@cached_property
|
63 |
+
def extrema(self) -> list[tuple[int, int]]:
|
64 |
+
"""
|
65 |
+
Min/max values for each band in the image.
|
66 |
+
|
67 |
+
.. note::
|
68 |
+
This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
|
69 |
+
simply returns the low and high bins used. This is correct for
|
70 |
+
images with 8 bits per channel, but fails for other modes such as
|
71 |
+
``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
|
72 |
+
return per-band extrema for the image. This is more correct and
|
73 |
+
efficient because, for non-8-bit modes, the histogram method uses
|
74 |
+
:py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
|
75 |
+
"""
|
76 |
+
|
77 |
+
def minmax(histogram: list[int]) -> tuple[int, int]:
|
78 |
+
res_min, res_max = 255, 0
|
79 |
+
for i in range(256):
|
80 |
+
if histogram[i]:
|
81 |
+
res_min = i
|
82 |
+
break
|
83 |
+
for i in range(255, -1, -1):
|
84 |
+
if histogram[i]:
|
85 |
+
res_max = i
|
86 |
+
break
|
87 |
+
return res_min, res_max
|
88 |
+
|
89 |
+
return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
|
90 |
+
|
91 |
+
@cached_property
|
92 |
+
def count(self) -> list[int]:
|
93 |
+
"""Total number of pixels for each band in the image."""
|
94 |
+
return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
|
95 |
+
|
96 |
+
@cached_property
|
97 |
+
def sum(self) -> list[float]:
|
98 |
+
"""Sum of all pixels for each band in the image."""
|
99 |
+
|
100 |
+
v = []
|
101 |
+
for i in range(0, len(self.h), 256):
|
102 |
+
layer_sum = 0.0
|
103 |
+
for j in range(256):
|
104 |
+
layer_sum += j * self.h[i + j]
|
105 |
+
v.append(layer_sum)
|
106 |
+
return v
|
107 |
+
|
108 |
+
@cached_property
|
109 |
+
def sum2(self) -> list[float]:
|
110 |
+
"""Squared sum of all pixels for each band in the image."""
|
111 |
+
|
112 |
+
v = []
|
113 |
+
for i in range(0, len(self.h), 256):
|
114 |
+
sum2 = 0.0
|
115 |
+
for j in range(256):
|
116 |
+
sum2 += (j**2) * float(self.h[i + j])
|
117 |
+
v.append(sum2)
|
118 |
+
return v
|
119 |
+
|
120 |
+
@cached_property
|
121 |
+
def mean(self) -> list[float]:
|
122 |
+
"""Average (arithmetic mean) pixel level for each band in the image."""
|
123 |
+
return [self.sum[i] / self.count[i] for i in self.bands]
|
124 |
+
|
125 |
+
@cached_property
|
126 |
+
def median(self) -> list[int]:
|
127 |
+
"""Median pixel level for each band in the image."""
|
128 |
+
|
129 |
+
v = []
|
130 |
+
for i in self.bands:
|
131 |
+
s = 0
|
132 |
+
half = self.count[i] // 2
|
133 |
+
b = i * 256
|
134 |
+
for j in range(256):
|
135 |
+
s = s + self.h[b + j]
|
136 |
+
if s > half:
|
137 |
+
break
|
138 |
+
v.append(j)
|
139 |
+
return v
|
140 |
+
|
141 |
+
@cached_property
|
142 |
+
def rms(self) -> list[float]:
|
143 |
+
"""RMS (root-mean-square) for each band in the image."""
|
144 |
+
return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands]
|
145 |
+
|
146 |
+
@cached_property
|
147 |
+
def var(self) -> list[float]:
|
148 |
+
"""Variance for each band in the image."""
|
149 |
+
return [
|
150 |
+
(self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
|
151 |
+
for i in self.bands
|
152 |
+
]
|
153 |
+
|
154 |
+
@cached_property
|
155 |
+
def stddev(self) -> list[float]:
|
156 |
+
"""Standard deviation for each band in the image."""
|
157 |
+
return [math.sqrt(self.var[i]) for i in self.bands]
|
158 |
+
|
159 |
+
|
160 |
+
Global = Stat # compatibility
|
MLPY/Lib/site-packages/PIL/ImageTk.py
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# a Tk display interface
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 96-04-08 fl Created
|
9 |
+
# 96-09-06 fl Added getimage method
|
10 |
+
# 96-11-01 fl Rewritten, removed image attribute and crop method
|
11 |
+
# 97-05-09 fl Use PyImagingPaste method instead of image type
|
12 |
+
# 97-05-12 fl Minor tweaks to match the IFUNC95 interface
|
13 |
+
# 97-05-17 fl Support the "pilbitmap" booster patch
|
14 |
+
# 97-06-05 fl Added file= and data= argument to image constructors
|
15 |
+
# 98-03-09 fl Added width and height methods to Image classes
|
16 |
+
# 98-07-02 fl Use default mode for "P" images without palette attribute
|
17 |
+
# 98-07-02 fl Explicitly destroy Tkinter image objects
|
18 |
+
# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
|
19 |
+
# 99-07-26 fl Automatically hook into Tkinter (if possible)
|
20 |
+
# 99-08-15 fl Hook uses _imagingtk instead of _imaging
|
21 |
+
#
|
22 |
+
# Copyright (c) 1997-1999 by Secret Labs AB
|
23 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh
|
24 |
+
#
|
25 |
+
# See the README file for information on usage and redistribution.
|
26 |
+
#
|
27 |
+
from __future__ import annotations
|
28 |
+
|
29 |
+
import tkinter
|
30 |
+
from io import BytesIO
|
31 |
+
|
32 |
+
from . import Image
|
33 |
+
|
34 |
+
# --------------------------------------------------------------------
|
35 |
+
# Check for Tkinter interface hooks
|
36 |
+
|
37 |
+
_pilbitmap_ok = None
|
38 |
+
|
39 |
+
|
40 |
+
def _pilbitmap_check() -> int:
|
41 |
+
global _pilbitmap_ok
|
42 |
+
if _pilbitmap_ok is None:
|
43 |
+
try:
|
44 |
+
im = Image.new("1", (1, 1))
|
45 |
+
tkinter.BitmapImage(data=f"PIL:{im.im.id}")
|
46 |
+
_pilbitmap_ok = 1
|
47 |
+
except tkinter.TclError:
|
48 |
+
_pilbitmap_ok = 0
|
49 |
+
return _pilbitmap_ok
|
50 |
+
|
51 |
+
|
52 |
+
def _get_image_from_kw(kw):
|
53 |
+
source = None
|
54 |
+
if "file" in kw:
|
55 |
+
source = kw.pop("file")
|
56 |
+
elif "data" in kw:
|
57 |
+
source = BytesIO(kw.pop("data"))
|
58 |
+
if source:
|
59 |
+
return Image.open(source)
|
60 |
+
|
61 |
+
|
62 |
+
def _pyimagingtkcall(command, photo, id):
|
63 |
+
tk = photo.tk
|
64 |
+
try:
|
65 |
+
tk.call(command, photo, id)
|
66 |
+
except tkinter.TclError:
|
67 |
+
# activate Tkinter hook
|
68 |
+
# may raise an error if it cannot attach to Tkinter
|
69 |
+
from . import _imagingtk
|
70 |
+
|
71 |
+
_imagingtk.tkinit(tk.interpaddr())
|
72 |
+
tk.call(command, photo, id)
|
73 |
+
|
74 |
+
|
75 |
+
# --------------------------------------------------------------------
|
76 |
+
# PhotoImage
|
77 |
+
|
78 |
+
|
79 |
+
class PhotoImage:
|
80 |
+
"""
|
81 |
+
A Tkinter-compatible photo image. This can be used
|
82 |
+
everywhere Tkinter expects an image object. If the image is an RGBA
|
83 |
+
image, pixels having alpha 0 are treated as transparent.
|
84 |
+
|
85 |
+
The constructor takes either a PIL image, or a mode and a size.
|
86 |
+
Alternatively, you can use the ``file`` or ``data`` options to initialize
|
87 |
+
the photo image object.
|
88 |
+
|
89 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
90 |
+
used, a size must also be given.
|
91 |
+
:param size: If the first argument is a mode string, this defines the size
|
92 |
+
of the image.
|
93 |
+
:keyword file: A filename to load the image from (using
|
94 |
+
``Image.open(file)``).
|
95 |
+
:keyword data: An 8-bit string containing image data (as loaded from an
|
96 |
+
image file).
|
97 |
+
"""
|
98 |
+
|
99 |
+
def __init__(self, image=None, size=None, **kw):
|
100 |
+
# Tk compatibility: file or data
|
101 |
+
if image is None:
|
102 |
+
image = _get_image_from_kw(kw)
|
103 |
+
|
104 |
+
if hasattr(image, "mode") and hasattr(image, "size"):
|
105 |
+
# got an image instead of a mode
|
106 |
+
mode = image.mode
|
107 |
+
if mode == "P":
|
108 |
+
# palette mapped data
|
109 |
+
image.apply_transparency()
|
110 |
+
image.load()
|
111 |
+
try:
|
112 |
+
mode = image.palette.mode
|
113 |
+
except AttributeError:
|
114 |
+
mode = "RGB" # default
|
115 |
+
size = image.size
|
116 |
+
kw["width"], kw["height"] = size
|
117 |
+
else:
|
118 |
+
mode = image
|
119 |
+
image = None
|
120 |
+
|
121 |
+
if mode not in ["1", "L", "RGB", "RGBA"]:
|
122 |
+
mode = Image.getmodebase(mode)
|
123 |
+
|
124 |
+
self.__mode = mode
|
125 |
+
self.__size = size
|
126 |
+
self.__photo = tkinter.PhotoImage(**kw)
|
127 |
+
self.tk = self.__photo.tk
|
128 |
+
if image:
|
129 |
+
self.paste(image)
|
130 |
+
|
131 |
+
def __del__(self) -> None:
|
132 |
+
name = self.__photo.name
|
133 |
+
self.__photo.name = None
|
134 |
+
try:
|
135 |
+
self.__photo.tk.call("image", "delete", name)
|
136 |
+
except Exception:
|
137 |
+
pass # ignore internal errors
|
138 |
+
|
139 |
+
def __str__(self) -> str:
|
140 |
+
"""
|
141 |
+
Get the Tkinter photo image identifier. This method is automatically
|
142 |
+
called by Tkinter whenever a PhotoImage object is passed to a Tkinter
|
143 |
+
method.
|
144 |
+
|
145 |
+
:return: A Tkinter photo image identifier (a string).
|
146 |
+
"""
|
147 |
+
return str(self.__photo)
|
148 |
+
|
149 |
+
def width(self) -> int:
|
150 |
+
"""
|
151 |
+
Get the width of the image.
|
152 |
+
|
153 |
+
:return: The width, in pixels.
|
154 |
+
"""
|
155 |
+
return self.__size[0]
|
156 |
+
|
157 |
+
def height(self) -> int:
|
158 |
+
"""
|
159 |
+
Get the height of the image.
|
160 |
+
|
161 |
+
:return: The height, in pixels.
|
162 |
+
"""
|
163 |
+
return self.__size[1]
|
164 |
+
|
165 |
+
def paste(self, im: Image.Image) -> None:
|
166 |
+
"""
|
167 |
+
Paste a PIL image into the photo image. Note that this can
|
168 |
+
be very slow if the photo image is displayed.
|
169 |
+
|
170 |
+
:param im: A PIL image. The size must match the target region. If the
|
171 |
+
mode does not match, the image is converted to the mode of
|
172 |
+
the bitmap image.
|
173 |
+
"""
|
174 |
+
# convert to blittable
|
175 |
+
im.load()
|
176 |
+
image = im.im
|
177 |
+
if image.isblock() and im.mode == self.__mode:
|
178 |
+
block = image
|
179 |
+
else:
|
180 |
+
block = image.new_block(self.__mode, im.size)
|
181 |
+
image.convert2(block, image) # convert directly between buffers
|
182 |
+
|
183 |
+
_pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
|
184 |
+
|
185 |
+
|
186 |
+
# --------------------------------------------------------------------
|
187 |
+
# BitmapImage
|
188 |
+
|
189 |
+
|
190 |
+
class BitmapImage:
|
191 |
+
"""
|
192 |
+
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
|
193 |
+
expects an image object.
|
194 |
+
|
195 |
+
The given image must have mode "1". Pixels having value 0 are treated as
|
196 |
+
transparent. Options, if any, are passed on to Tkinter. The most commonly
|
197 |
+
used option is ``foreground``, which is used to specify the color for the
|
198 |
+
non-transparent parts. See the Tkinter documentation for information on
|
199 |
+
how to specify colours.
|
200 |
+
|
201 |
+
:param image: A PIL image.
|
202 |
+
"""
|
203 |
+
|
204 |
+
def __init__(self, image=None, **kw):
|
205 |
+
# Tk compatibility: file or data
|
206 |
+
if image is None:
|
207 |
+
image = _get_image_from_kw(kw)
|
208 |
+
|
209 |
+
self.__mode = image.mode
|
210 |
+
self.__size = image.size
|
211 |
+
|
212 |
+
if _pilbitmap_check():
|
213 |
+
# fast way (requires the pilbitmap booster patch)
|
214 |
+
image.load()
|
215 |
+
kw["data"] = f"PIL:{image.im.id}"
|
216 |
+
self.__im = image # must keep a reference
|
217 |
+
else:
|
218 |
+
# slow but safe way
|
219 |
+
kw["data"] = image.tobitmap()
|
220 |
+
self.__photo = tkinter.BitmapImage(**kw)
|
221 |
+
|
222 |
+
def __del__(self) -> None:
|
223 |
+
name = self.__photo.name
|
224 |
+
self.__photo.name = None
|
225 |
+
try:
|
226 |
+
self.__photo.tk.call("image", "delete", name)
|
227 |
+
except Exception:
|
228 |
+
pass # ignore internal errors
|
229 |
+
|
230 |
+
def width(self) -> int:
|
231 |
+
"""
|
232 |
+
Get the width of the image.
|
233 |
+
|
234 |
+
:return: The width, in pixels.
|
235 |
+
"""
|
236 |
+
return self.__size[0]
|
237 |
+
|
238 |
+
def height(self) -> int:
|
239 |
+
"""
|
240 |
+
Get the height of the image.
|
241 |
+
|
242 |
+
:return: The height, in pixels.
|
243 |
+
"""
|
244 |
+
return self.__size[1]
|
245 |
+
|
246 |
+
def __str__(self) -> str:
|
247 |
+
"""
|
248 |
+
Get the Tkinter bitmap image identifier. This method is automatically
|
249 |
+
called by Tkinter whenever a BitmapImage object is passed to a Tkinter
|
250 |
+
method.
|
251 |
+
|
252 |
+
:return: A Tkinter bitmap image identifier (a string).
|
253 |
+
"""
|
254 |
+
return str(self.__photo)
|
255 |
+
|
256 |
+
|
257 |
+
def getimage(photo: PhotoImage) -> Image.Image:
|
258 |
+
"""Copies the contents of a PhotoImage to a PIL image memory."""
|
259 |
+
im = Image.new("RGBA", (photo.width(), photo.height()))
|
260 |
+
block = im.im
|
261 |
+
|
262 |
+
_pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
|
263 |
+
|
264 |
+
return im
|
265 |
+
|
266 |
+
|
267 |
+
def _show(image, title):
|
268 |
+
"""Helper for the Image.show method."""
|
269 |
+
|
270 |
+
class UI(tkinter.Label):
|
271 |
+
def __init__(self, master, im):
|
272 |
+
if im.mode == "1":
|
273 |
+
self.image = BitmapImage(im, foreground="white", master=master)
|
274 |
+
else:
|
275 |
+
self.image = PhotoImage(im, master=master)
|
276 |
+
super().__init__(master, image=self.image, bg="black", bd=0)
|
277 |
+
|
278 |
+
if not tkinter._default_root:
|
279 |
+
msg = "tkinter not initialized"
|
280 |
+
raise OSError(msg)
|
281 |
+
top = tkinter.Toplevel()
|
282 |
+
if title:
|
283 |
+
top.title(title)
|
284 |
+
UI(top, image).pack()
|
MLPY/Lib/site-packages/PIL/ImageTransform.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# transform wrappers
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 2002-04-08 fl Created
|
9 |
+
#
|
10 |
+
# Copyright (c) 2002 by Secret Labs AB
|
11 |
+
# Copyright (c) 2002 by Fredrik Lundh
|
12 |
+
#
|
13 |
+
# See the README file for information on usage and redistribution.
|
14 |
+
#
|
15 |
+
from __future__ import annotations
|
16 |
+
|
17 |
+
from typing import Any, Sequence
|
18 |
+
|
19 |
+
from . import Image
|
20 |
+
|
21 |
+
|
22 |
+
class Transform(Image.ImageTransformHandler):
|
23 |
+
"""Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
|
24 |
+
|
25 |
+
method: Image.Transform
|
26 |
+
|
27 |
+
def __init__(self, data: Sequence[Any]) -> None:
|
28 |
+
self.data = data
|
29 |
+
|
30 |
+
def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
|
31 |
+
return self.method, self.data
|
32 |
+
|
33 |
+
def transform(
|
34 |
+
self,
|
35 |
+
size: tuple[int, int],
|
36 |
+
image: Image.Image,
|
37 |
+
**options: Any,
|
38 |
+
) -> Image.Image:
|
39 |
+
"""Perform the transform. Called from :py:meth:`.Image.transform`."""
|
40 |
+
# can be overridden
|
41 |
+
method, data = self.getdata()
|
42 |
+
return image.transform(size, method, data, **options)
|
43 |
+
|
44 |
+
|
45 |
+
class AffineTransform(Transform):
|
46 |
+
"""
|
47 |
+
Define an affine image transform.
|
48 |
+
|
49 |
+
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
|
50 |
+
two rows from an affine transform matrix. For each pixel (x, y) in the
|
51 |
+
output image, the new value is taken from a position (a x + b y + c,
|
52 |
+
d x + e y + f) in the input image, rounded to nearest pixel.
|
53 |
+
|
54 |
+
This function can be used to scale, translate, rotate, and shear the
|
55 |
+
original image.
|
56 |
+
|
57 |
+
See :py:meth:`.Image.transform`
|
58 |
+
|
59 |
+
:param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
|
60 |
+
from an affine transform matrix.
|
61 |
+
"""
|
62 |
+
|
63 |
+
method = Image.Transform.AFFINE
|
64 |
+
|
65 |
+
|
66 |
+
class PerspectiveTransform(Transform):
|
67 |
+
"""
|
68 |
+
Define a perspective image transform.
|
69 |
+
|
70 |
+
This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
|
71 |
+
(x, y) in the output image, the new value is taken from a position
|
72 |
+
((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
|
73 |
+
the input image, rounded to nearest pixel.
|
74 |
+
|
75 |
+
This function can be used to scale, translate, rotate, and shear the
|
76 |
+
original image.
|
77 |
+
|
78 |
+
See :py:meth:`.Image.transform`
|
79 |
+
|
80 |
+
:param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
|
81 |
+
"""
|
82 |
+
|
83 |
+
method = Image.Transform.PERSPECTIVE
|
84 |
+
|
85 |
+
|
86 |
+
class ExtentTransform(Transform):
|
87 |
+
"""
|
88 |
+
Define a transform to extract a subregion from an image.
|
89 |
+
|
90 |
+
Maps a rectangle (defined by two corners) from the image to a rectangle of
|
91 |
+
the given size. The resulting image will contain data sampled from between
|
92 |
+
the corners, such that (x0, y0) in the input image will end up at (0,0) in
|
93 |
+
the output image, and (x1, y1) at size.
|
94 |
+
|
95 |
+
This method can be used to crop, stretch, shrink, or mirror an arbitrary
|
96 |
+
rectangle in the current image. It is slightly slower than crop, but about
|
97 |
+
as fast as a corresponding resize operation.
|
98 |
+
|
99 |
+
See :py:meth:`.Image.transform`
|
100 |
+
|
101 |
+
:param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
|
102 |
+
input image's coordinate system. See :ref:`coordinate-system`.
|
103 |
+
"""
|
104 |
+
|
105 |
+
method = Image.Transform.EXTENT
|
106 |
+
|
107 |
+
|
108 |
+
class QuadTransform(Transform):
|
109 |
+
"""
|
110 |
+
Define a quad image transform.
|
111 |
+
|
112 |
+
Maps a quadrilateral (a region defined by four corners) from the image to a
|
113 |
+
rectangle of the given size.
|
114 |
+
|
115 |
+
See :py:meth:`.Image.transform`
|
116 |
+
|
117 |
+
:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
|
118 |
+
upper left, lower left, lower right, and upper right corner of the
|
119 |
+
source quadrilateral.
|
120 |
+
"""
|
121 |
+
|
122 |
+
method = Image.Transform.QUAD
|
123 |
+
|
124 |
+
|
125 |
+
class MeshTransform(Transform):
|
126 |
+
"""
|
127 |
+
Define a mesh image transform. A mesh transform consists of one or more
|
128 |
+
individual quad transforms.
|
129 |
+
|
130 |
+
See :py:meth:`.Image.transform`
|
131 |
+
|
132 |
+
:param data: A list of (bbox, quad) tuples.
|
133 |
+
"""
|
134 |
+
|
135 |
+
method = Image.Transform.MESH
|
MLPY/Lib/site-packages/PIL/ImageWin.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# The Python Imaging Library.
|
3 |
+
# $Id$
|
4 |
+
#
|
5 |
+
# a Windows DIB display interface
|
6 |
+
#
|
7 |
+
# History:
|
8 |
+
# 1996-05-20 fl Created
|
9 |
+
# 1996-09-20 fl Fixed subregion exposure
|
10 |
+
# 1997-09-21 fl Added draw primitive (for tzPrint)
|
11 |
+
# 2003-05-21 fl Added experimental Window/ImageWindow classes
|
12 |
+
# 2003-09-05 fl Added fromstring/tostring methods
|
13 |
+
#
|
14 |
+
# Copyright (c) Secret Labs AB 1997-2003.
|
15 |
+
# Copyright (c) Fredrik Lundh 1996-2003.
|
16 |
+
#
|
17 |
+
# See the README file for information on usage and redistribution.
|
18 |
+
#
|
19 |
+
from __future__ import annotations
|
20 |
+
|
21 |
+
from . import Image
|
22 |
+
|
23 |
+
|
24 |
+
class HDC:
|
25 |
+
"""
|
26 |
+
Wraps an HDC integer. The resulting object can be passed to the
|
27 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
28 |
+
methods.
|
29 |
+
"""
|
30 |
+
|
31 |
+
def __init__(self, dc: int) -> None:
|
32 |
+
self.dc = dc
|
33 |
+
|
34 |
+
def __int__(self) -> int:
|
35 |
+
return self.dc
|
36 |
+
|
37 |
+
|
38 |
+
class HWND:
|
39 |
+
"""
|
40 |
+
Wraps an HWND integer. The resulting object can be passed to the
|
41 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
42 |
+
methods, instead of a DC.
|
43 |
+
"""
|
44 |
+
|
45 |
+
def __init__(self, wnd: int) -> None:
|
46 |
+
self.wnd = wnd
|
47 |
+
|
48 |
+
def __int__(self) -> int:
|
49 |
+
return self.wnd
|
50 |
+
|
51 |
+
|
52 |
+
class Dib:
|
53 |
+
"""
|
54 |
+
A Windows bitmap with the given mode and size. The mode can be one of "1",
|
55 |
+
"L", "P", or "RGB".
|
56 |
+
|
57 |
+
If the display requires a palette, this constructor creates a suitable
|
58 |
+
palette and associates it with the image. For an "L" image, 128 graylevels
|
59 |
+
are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
|
60 |
+
with 20 graylevels.
|
61 |
+
|
62 |
+
To make sure that palettes work properly under Windows, you must call the
|
63 |
+
``palette`` method upon certain events from Windows.
|
64 |
+
|
65 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
66 |
+
used, a size must also be given. The mode can be one of "1",
|
67 |
+
"L", "P", or "RGB".
|
68 |
+
:param size: If the first argument is a mode string, this
|
69 |
+
defines the size of the image.
|
70 |
+
"""
|
71 |
+
|
72 |
+
def __init__(
|
73 |
+
self, image: Image.Image | str, size: tuple[int, int] | list[int] | None = None
|
74 |
+
) -> None:
|
75 |
+
if isinstance(image, str):
|
76 |
+
mode = image
|
77 |
+
image = ""
|
78 |
+
else:
|
79 |
+
mode = image.mode
|
80 |
+
size = image.size
|
81 |
+
if mode not in ["1", "L", "P", "RGB"]:
|
82 |
+
mode = Image.getmodebase(mode)
|
83 |
+
self.image = Image.core.display(mode, size)
|
84 |
+
self.mode = mode
|
85 |
+
self.size = size
|
86 |
+
if image:
|
87 |
+
assert not isinstance(image, str)
|
88 |
+
self.paste(image)
|
89 |
+
|
90 |
+
def expose(self, handle):
|
91 |
+
"""
|
92 |
+
Copy the bitmap contents to a device context.
|
93 |
+
|
94 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
95 |
+
HDC or HWND instance. In PythonWin, you can use
|
96 |
+
``CDC.GetHandleAttrib()`` to get a suitable handle.
|
97 |
+
"""
|
98 |
+
if isinstance(handle, HWND):
|
99 |
+
dc = self.image.getdc(handle)
|
100 |
+
try:
|
101 |
+
result = self.image.expose(dc)
|
102 |
+
finally:
|
103 |
+
self.image.releasedc(handle, dc)
|
104 |
+
else:
|
105 |
+
result = self.image.expose(handle)
|
106 |
+
return result
|
107 |
+
|
108 |
+
def draw(self, handle, dst, src=None):
|
109 |
+
"""
|
110 |
+
Same as expose, but allows you to specify where to draw the image, and
|
111 |
+
what part of it to draw.
|
112 |
+
|
113 |
+
The destination and source areas are given as 4-tuple rectangles. If
|
114 |
+
the source is omitted, the entire image is copied. If the source and
|
115 |
+
the destination have different sizes, the image is resized as
|
116 |
+
necessary.
|
117 |
+
"""
|
118 |
+
if not src:
|
119 |
+
src = (0, 0) + self.size
|
120 |
+
if isinstance(handle, HWND):
|
121 |
+
dc = self.image.getdc(handle)
|
122 |
+
try:
|
123 |
+
result = self.image.draw(dc, dst, src)
|
124 |
+
finally:
|
125 |
+
self.image.releasedc(handle, dc)
|
126 |
+
else:
|
127 |
+
result = self.image.draw(handle, dst, src)
|
128 |
+
return result
|
129 |
+
|
130 |
+
def query_palette(self, handle):
|
131 |
+
"""
|
132 |
+
Installs the palette associated with the image in the given device
|
133 |
+
context.
|
134 |
+
|
135 |
+
This method should be called upon **QUERYNEWPALETTE** and
|
136 |
+
**PALETTECHANGED** events from Windows. If this method returns a
|
137 |
+
non-zero value, one or more display palette entries were changed, and
|
138 |
+
the image should be redrawn.
|
139 |
+
|
140 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
141 |
+
HDC or HWND instance.
|
142 |
+
:return: A true value if one or more entries were changed (this
|
143 |
+
indicates that the image should be redrawn).
|
144 |
+
"""
|
145 |
+
if isinstance(handle, HWND):
|
146 |
+
handle = self.image.getdc(handle)
|
147 |
+
try:
|
148 |
+
result = self.image.query_palette(handle)
|
149 |
+
finally:
|
150 |
+
self.image.releasedc(handle, handle)
|
151 |
+
else:
|
152 |
+
result = self.image.query_palette(handle)
|
153 |
+
return result
|
154 |
+
|
155 |
+
def paste(
|
156 |
+
self, im: Image.Image, box: tuple[int, int, int, int] | None = None
|
157 |
+
) -> None:
|
158 |
+
"""
|
159 |
+
Paste a PIL image into the bitmap image.
|
160 |
+
|
161 |
+
:param im: A PIL image. The size must match the target region.
|
162 |
+
If the mode does not match, the image is converted to the
|
163 |
+
mode of the bitmap image.
|
164 |
+
:param box: A 4-tuple defining the left, upper, right, and
|
165 |
+
lower pixel coordinate. See :ref:`coordinate-system`. If
|
166 |
+
None is given instead of a tuple, all of the image is
|
167 |
+
assumed.
|
168 |
+
"""
|
169 |
+
im.load()
|
170 |
+
if self.mode != im.mode:
|
171 |
+
im = im.convert(self.mode)
|
172 |
+
if box:
|
173 |
+
self.image.paste(im.im, box)
|
174 |
+
else:
|
175 |
+
self.image.paste(im.im)
|
176 |
+
|
177 |
+
def frombytes(self, buffer: bytes) -> None:
|
178 |
+
"""
|
179 |
+
Load display memory contents from byte data.
|
180 |
+
|
181 |
+
:param buffer: A buffer containing display data (usually
|
182 |
+
data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
|
183 |
+
"""
|
184 |
+
self.image.frombytes(buffer)
|
185 |
+
|
186 |
+
def tobytes(self) -> bytes:
|
187 |
+
"""
|
188 |
+
Copy display memory contents to bytes object.
|
189 |
+
|
190 |
+
:return: A bytes object containing display data.
|
191 |
+
"""
|
192 |
+
return self.image.tobytes()
|
193 |
+
|
194 |
+
|
195 |
+
class Window:
|
196 |
+
"""Create a Window with the given title size."""
|
197 |
+
|
198 |
+
def __init__(
|
199 |
+
self, title: str = "PIL", width: int | None = None, height: int | None = None
|
200 |
+
) -> None:
|
201 |
+
self.hwnd = Image.core.createwindow(
|
202 |
+
title, self.__dispatcher, width or 0, height or 0
|
203 |
+
)
|
204 |
+
|
205 |
+
def __dispatcher(self, action, *args):
|
206 |
+
return getattr(self, f"ui_handle_{action}")(*args)
|
207 |
+
|
208 |
+
def ui_handle_clear(self, dc, x0, y0, x1, y1):
|
209 |
+
pass
|
210 |
+
|
211 |
+
def ui_handle_damage(self, x0, y0, x1, y1):
|
212 |
+
pass
|
213 |
+
|
214 |
+
def ui_handle_destroy(self) -> None:
|
215 |
+
pass
|
216 |
+
|
217 |
+
def ui_handle_repair(self, dc, x0, y0, x1, y1):
|
218 |
+
pass
|
219 |
+
|
220 |
+
def ui_handle_resize(self, width, height):
|
221 |
+
pass
|
222 |
+
|
223 |
+
def mainloop(self) -> None:
|
224 |
+
Image.core.eventloop()
|
225 |
+
|
226 |
+
|
227 |
+
class ImageWindow(Window):
|
228 |
+
"""Create an image window which displays the given image."""
|
229 |
+
|
230 |
+
def __init__(self, image, title="PIL"):
|
231 |
+
if not isinstance(image, Dib):
|
232 |
+
image = Dib(image)
|
233 |
+
self.image = image
|
234 |
+
width, height = image.size
|
235 |
+
super().__init__(title, width=width, height=height)
|
236 |
+
|
237 |
+
def ui_handle_repair(self, dc, x0, y0, x1, y1):
|
238 |
+
self.image.draw(dc, (x0, y0, x1, y1))
|