Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL +6 -0
- .venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py +291 -0
- .venv/lib/python3.12/site-packages/PIL/BdfFontFile.py +122 -0
- .venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py +497 -0
- .venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py +515 -0
- .venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py +75 -0
- .venv/lib/python3.12/site-packages/PIL/ContainerIO.py +173 -0
- .venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py +83 -0
- .venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py +479 -0
- .venv/lib/python3.12/site-packages/PIL/ExifTags.py +382 -0
- .venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py +152 -0
- .venv/lib/python3.12/site-packages/PIL/FliImagePlugin.py +184 -0
- .venv/lib/python3.12/site-packages/PIL/FontFile.py +134 -0
- .venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py +257 -0
- .venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py +101 -0
- .venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py +1215 -0
- .venv/lib/python3.12/site-packages/PIL/GimpPaletteFile.py +75 -0
- .venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py +75 -0
- .venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py +401 -0
- .venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py +389 -0
- .venv/lib/python3.12/site-packages/PIL/Image.py +0 -0
- .venv/lib/python3.12/site-packages/PIL/ImageCms.py +1076 -0
- .venv/lib/python3.12/site-packages/PIL/ImageDraw.py +1036 -0
- .venv/lib/python3.12/site-packages/PIL/ImageDraw2.py +243 -0
- .venv/lib/python3.12/site-packages/PIL/ImageEnhance.py +113 -0
- .venv/lib/python3.12/site-packages/PIL/ImageFilter.py +607 -0
- .venv/lib/python3.12/site-packages/PIL/ImageGrab.py +196 -0
- .venv/lib/python3.12/site-packages/PIL/ImageMath.py +314 -0
- .venv/lib/python3.12/site-packages/PIL/ImagePalette.py +286 -0
- .venv/lib/python3.12/site-packages/PIL/ImagePath.py +20 -0
- .venv/lib/python3.12/site-packages/PIL/ImageText.py +318 -0
- .venv/lib/python3.12/site-packages/PIL/ImageTk.py +266 -0
- .venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py +888 -0
- .venv/lib/python3.12/site-packages/PIL/JpegPresets.py +242 -0
- .venv/lib/python3.12/site-packages/PIL/PngImagePlugin.py +1553 -0
- .venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py +375 -0
- .venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py +83 -0
- .venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py +157 -0
- .venv/lib/python3.12/site-packages/PIL/__init__.py +87 -0
- .venv/lib/python3.12/site-packages/__pycache__/isympy.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/__pycache__/pylab.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/__pycache__/six.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/easydict-1.13.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/METADATA +42 -0
- .venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/RECORD +24 -0
- .venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/WHEEL +4 -0
- .venv/lib/python3.12/site-packages/filelock/__init__.py +70 -0
- .venv/lib/python3.12/site-packages/filelock/_error.py +30 -0
.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.2.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp312-cp312-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp312-cp312-manylinux2014_x86_64
|
| 6 |
+
|
.venv/lib/python3.12/site-packages/PIL/AvifImagePlugin.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from typing import IO
|
| 6 |
+
|
| 7 |
+
from . import ExifTags, Image, ImageFile
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from . import _avif
|
| 11 |
+
|
| 12 |
+
SUPPORTED = True
|
| 13 |
+
except ImportError:
|
| 14 |
+
SUPPORTED = False
|
| 15 |
+
|
| 16 |
+
# Decoder options as module globals, until there is a way to pass parameters
|
| 17 |
+
# to Image.open (see https://github.com/python-pillow/Pillow/issues/569)
|
| 18 |
+
DECODE_CODEC_CHOICE = "auto"
|
| 19 |
+
DEFAULT_MAX_THREADS = 0
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_codec_version(codec_name: str) -> str | None:
|
| 23 |
+
versions = _avif.codec_versions()
|
| 24 |
+
for version in versions.split(", "):
|
| 25 |
+
if version.split(" [")[0] == codec_name:
|
| 26 |
+
return version.split(":")[-1].split(" ")[0]
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _accept(prefix: bytes) -> bool | str:
|
| 31 |
+
if prefix[4:8] != b"ftyp":
|
| 32 |
+
return False
|
| 33 |
+
major_brand = prefix[8:12]
|
| 34 |
+
if major_brand in (
|
| 35 |
+
# coding brands
|
| 36 |
+
b"avif",
|
| 37 |
+
b"avis",
|
| 38 |
+
# We accept files with AVIF container brands; we can't yet know if
|
| 39 |
+
# the ftyp box has the correct compatible brands, but if it doesn't
|
| 40 |
+
# then the plugin will raise a SyntaxError which Pillow will catch
|
| 41 |
+
# before moving on to the next plugin that accepts the file.
|
| 42 |
+
#
|
| 43 |
+
# Also, because this file might not actually be an AVIF file, we
|
| 44 |
+
# don't raise an error if AVIF support isn't properly compiled.
|
| 45 |
+
b"mif1",
|
| 46 |
+
b"msf1",
|
| 47 |
+
):
|
| 48 |
+
if not SUPPORTED:
|
| 49 |
+
return (
|
| 50 |
+
"image file could not be identified because AVIF support not installed"
|
| 51 |
+
)
|
| 52 |
+
return True
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _get_default_max_threads() -> int:
|
| 57 |
+
if DEFAULT_MAX_THREADS:
|
| 58 |
+
return DEFAULT_MAX_THREADS
|
| 59 |
+
if hasattr(os, "sched_getaffinity"):
|
| 60 |
+
return len(os.sched_getaffinity(0))
|
| 61 |
+
else:
|
| 62 |
+
return os.cpu_count() or 1
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class AvifImageFile(ImageFile.ImageFile):
|
| 66 |
+
format = "AVIF"
|
| 67 |
+
format_description = "AVIF image"
|
| 68 |
+
__frame = -1
|
| 69 |
+
|
| 70 |
+
def _open(self) -> None:
|
| 71 |
+
if not SUPPORTED:
|
| 72 |
+
msg = "image file could not be opened because AVIF support not installed"
|
| 73 |
+
raise SyntaxError(msg)
|
| 74 |
+
|
| 75 |
+
if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available(
|
| 76 |
+
DECODE_CODEC_CHOICE
|
| 77 |
+
):
|
| 78 |
+
msg = "Invalid opening codec"
|
| 79 |
+
raise ValueError(msg)
|
| 80 |
+
self._decoder = _avif.AvifDecoder(
|
| 81 |
+
self.fp.read(),
|
| 82 |
+
DECODE_CODEC_CHOICE,
|
| 83 |
+
_get_default_max_threads(),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Get info from decoder
|
| 87 |
+
self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = (
|
| 88 |
+
self._decoder.get_info()
|
| 89 |
+
)
|
| 90 |
+
self.is_animated = self.n_frames > 1
|
| 91 |
+
|
| 92 |
+
if icc:
|
| 93 |
+
self.info["icc_profile"] = icc
|
| 94 |
+
if xmp:
|
| 95 |
+
self.info["xmp"] = xmp
|
| 96 |
+
|
| 97 |
+
if exif_orientation != 1 or exif:
|
| 98 |
+
exif_data = Image.Exif()
|
| 99 |
+
if exif:
|
| 100 |
+
exif_data.load(exif)
|
| 101 |
+
original_orientation = exif_data.get(ExifTags.Base.Orientation, 1)
|
| 102 |
+
else:
|
| 103 |
+
original_orientation = 1
|
| 104 |
+
if exif_orientation != original_orientation:
|
| 105 |
+
exif_data[ExifTags.Base.Orientation] = exif_orientation
|
| 106 |
+
exif = exif_data.tobytes()
|
| 107 |
+
if exif:
|
| 108 |
+
self.info["exif"] = exif
|
| 109 |
+
self.seek(0)
|
| 110 |
+
|
| 111 |
+
def seek(self, frame: int) -> None:
|
| 112 |
+
if not self._seek_check(frame):
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
# Set tile
|
| 116 |
+
self.__frame = frame
|
| 117 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)]
|
| 118 |
+
|
| 119 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 120 |
+
if self.tile:
|
| 121 |
+
# We need to load the image data for this frame
|
| 122 |
+
data, timescale, pts_in_timescales, duration_in_timescales = (
|
| 123 |
+
self._decoder.get_frame(self.__frame)
|
| 124 |
+
)
|
| 125 |
+
self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale))
|
| 126 |
+
self.info["duration"] = round(1000 * (duration_in_timescales / timescale))
|
| 127 |
+
|
| 128 |
+
if self.fp and self._exclusive_fp:
|
| 129 |
+
self.fp.close()
|
| 130 |
+
self.fp = BytesIO(data)
|
| 131 |
+
|
| 132 |
+
return super().load()
|
| 133 |
+
|
| 134 |
+
def load_seek(self, pos: int) -> None:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
def tell(self) -> int:
|
| 138 |
+
return self.__frame
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 142 |
+
_save(im, fp, filename, save_all=True)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _save(
|
| 146 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
|
| 147 |
+
) -> None:
|
| 148 |
+
info = im.encoderinfo.copy()
|
| 149 |
+
if save_all:
|
| 150 |
+
append_images = list(info.get("append_images", []))
|
| 151 |
+
else:
|
| 152 |
+
append_images = []
|
| 153 |
+
|
| 154 |
+
total = 0
|
| 155 |
+
for ims in [im] + append_images:
|
| 156 |
+
total += getattr(ims, "n_frames", 1)
|
| 157 |
+
|
| 158 |
+
quality = info.get("quality", 75)
|
| 159 |
+
if not isinstance(quality, int) or quality < 0 or quality > 100:
|
| 160 |
+
msg = "Invalid quality setting"
|
| 161 |
+
raise ValueError(msg)
|
| 162 |
+
|
| 163 |
+
duration = info.get("duration", 0)
|
| 164 |
+
subsampling = info.get("subsampling", "4:2:0")
|
| 165 |
+
speed = info.get("speed", 6)
|
| 166 |
+
max_threads = info.get("max_threads", _get_default_max_threads())
|
| 167 |
+
codec = info.get("codec", "auto")
|
| 168 |
+
if codec != "auto" and not _avif.encoder_codec_available(codec):
|
| 169 |
+
msg = "Invalid saving codec"
|
| 170 |
+
raise ValueError(msg)
|
| 171 |
+
range_ = info.get("range", "full")
|
| 172 |
+
tile_rows_log2 = info.get("tile_rows", 0)
|
| 173 |
+
tile_cols_log2 = info.get("tile_cols", 0)
|
| 174 |
+
alpha_premultiplied = bool(info.get("alpha_premultiplied", False))
|
| 175 |
+
autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0))
|
| 176 |
+
|
| 177 |
+
icc_profile = info.get("icc_profile", im.info.get("icc_profile"))
|
| 178 |
+
exif_orientation = 1
|
| 179 |
+
if exif := info.get("exif"):
|
| 180 |
+
if isinstance(exif, Image.Exif):
|
| 181 |
+
exif_data = exif
|
| 182 |
+
else:
|
| 183 |
+
exif_data = Image.Exif()
|
| 184 |
+
exif_data.load(exif)
|
| 185 |
+
if ExifTags.Base.Orientation in exif_data:
|
| 186 |
+
exif_orientation = exif_data.pop(ExifTags.Base.Orientation)
|
| 187 |
+
exif = exif_data.tobytes() if exif_data else b""
|
| 188 |
+
elif isinstance(exif, Image.Exif):
|
| 189 |
+
exif = exif_data.tobytes()
|
| 190 |
+
|
| 191 |
+
xmp = info.get("xmp")
|
| 192 |
+
|
| 193 |
+
if isinstance(xmp, str):
|
| 194 |
+
xmp = xmp.encode("utf-8")
|
| 195 |
+
|
| 196 |
+
advanced = info.get("advanced")
|
| 197 |
+
if advanced is not None:
|
| 198 |
+
if isinstance(advanced, dict):
|
| 199 |
+
advanced = advanced.items()
|
| 200 |
+
try:
|
| 201 |
+
advanced = tuple(advanced)
|
| 202 |
+
except TypeError:
|
| 203 |
+
invalid = True
|
| 204 |
+
else:
|
| 205 |
+
invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced)
|
| 206 |
+
if invalid:
|
| 207 |
+
msg = (
|
| 208 |
+
"advanced codec options must be a dict of key-value string "
|
| 209 |
+
"pairs or a series of key-value two-tuples"
|
| 210 |
+
)
|
| 211 |
+
raise ValueError(msg)
|
| 212 |
+
|
| 213 |
+
# Setup the AVIF encoder
|
| 214 |
+
enc = _avif.AvifEncoder(
|
| 215 |
+
im.size,
|
| 216 |
+
subsampling,
|
| 217 |
+
quality,
|
| 218 |
+
speed,
|
| 219 |
+
max_threads,
|
| 220 |
+
codec,
|
| 221 |
+
range_,
|
| 222 |
+
tile_rows_log2,
|
| 223 |
+
tile_cols_log2,
|
| 224 |
+
alpha_premultiplied,
|
| 225 |
+
autotiling,
|
| 226 |
+
icc_profile or b"",
|
| 227 |
+
exif or b"",
|
| 228 |
+
exif_orientation,
|
| 229 |
+
xmp or b"",
|
| 230 |
+
advanced,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# Add each frame
|
| 234 |
+
frame_idx = 0
|
| 235 |
+
frame_duration = 0
|
| 236 |
+
cur_idx = im.tell()
|
| 237 |
+
is_single_frame = total == 1
|
| 238 |
+
try:
|
| 239 |
+
for ims in [im] + append_images:
|
| 240 |
+
# Get number of frames in this image
|
| 241 |
+
nfr = getattr(ims, "n_frames", 1)
|
| 242 |
+
|
| 243 |
+
for idx in range(nfr):
|
| 244 |
+
ims.seek(idx)
|
| 245 |
+
|
| 246 |
+
# Make sure image mode is supported
|
| 247 |
+
frame = ims
|
| 248 |
+
rawmode = ims.mode
|
| 249 |
+
if ims.mode not in {"RGB", "RGBA"}:
|
| 250 |
+
rawmode = "RGBA" if ims.has_transparency_data else "RGB"
|
| 251 |
+
frame = ims.convert(rawmode)
|
| 252 |
+
|
| 253 |
+
# Update frame duration
|
| 254 |
+
if isinstance(duration, (list, tuple)):
|
| 255 |
+
frame_duration = duration[frame_idx]
|
| 256 |
+
else:
|
| 257 |
+
frame_duration = duration
|
| 258 |
+
|
| 259 |
+
# Append the frame to the animation encoder
|
| 260 |
+
enc.add(
|
| 261 |
+
frame.tobytes("raw", rawmode),
|
| 262 |
+
frame_duration,
|
| 263 |
+
frame.size,
|
| 264 |
+
rawmode,
|
| 265 |
+
is_single_frame,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# Update frame index
|
| 269 |
+
frame_idx += 1
|
| 270 |
+
|
| 271 |
+
if not save_all:
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
finally:
|
| 275 |
+
im.seek(cur_idx)
|
| 276 |
+
|
| 277 |
+
# Get the final output from the encoder
|
| 278 |
+
data = enc.finish()
|
| 279 |
+
if data is None:
|
| 280 |
+
msg = "cannot write file as AVIF (encoder returned None)"
|
| 281 |
+
raise OSError(msg)
|
| 282 |
+
|
| 283 |
+
fp.write(data)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
Image.register_open(AvifImageFile.format, AvifImageFile, _accept)
|
| 287 |
+
if SUPPORTED:
|
| 288 |
+
Image.register_save(AvifImageFile.format, _save)
|
| 289 |
+
Image.register_save_all(AvifImageFile.format, _save_all)
|
| 290 |
+
Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"])
|
| 291 |
+
Image.register_mime(AvifImageFile.format, "image/avif")
|
.venv/lib/python3.12/site-packages/PIL/BdfFontFile.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 30 |
+
def bdf_char(
|
| 31 |
+
f: BinaryIO,
|
| 32 |
+
) -> (
|
| 33 |
+
tuple[
|
| 34 |
+
str,
|
| 35 |
+
int,
|
| 36 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
|
| 37 |
+
Image.Image,
|
| 38 |
+
]
|
| 39 |
+
| None
|
| 40 |
+
):
|
| 41 |
+
# skip to STARTCHAR
|
| 42 |
+
while True:
|
| 43 |
+
s = f.readline()
|
| 44 |
+
if not s:
|
| 45 |
+
return None
|
| 46 |
+
if s.startswith(b"STARTCHAR"):
|
| 47 |
+
break
|
| 48 |
+
id = s[9:].strip().decode("ascii")
|
| 49 |
+
|
| 50 |
+
# load symbol properties
|
| 51 |
+
props = {}
|
| 52 |
+
while True:
|
| 53 |
+
s = f.readline()
|
| 54 |
+
if not s or s.startswith(b"BITMAP"):
|
| 55 |
+
break
|
| 56 |
+
i = s.find(b" ")
|
| 57 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
| 58 |
+
|
| 59 |
+
# load bitmap
|
| 60 |
+
bitmap = bytearray()
|
| 61 |
+
while True:
|
| 62 |
+
s = f.readline()
|
| 63 |
+
if not s or s.startswith(b"ENDCHAR"):
|
| 64 |
+
break
|
| 65 |
+
bitmap += s[:-1]
|
| 66 |
+
|
| 67 |
+
# The word BBX
|
| 68 |
+
# followed by the width in x (BBw), height in y (BBh),
|
| 69 |
+
# and x and y displacement (BBxoff0, BByoff0)
|
| 70 |
+
# of the lower left corner from the origin of the character.
|
| 71 |
+
width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
|
| 72 |
+
|
| 73 |
+
# The word DWIDTH
|
| 74 |
+
# followed by the width in x and y of the character in device pixels.
|
| 75 |
+
dwx, dwy = (int(p) for p in props["DWIDTH"].split())
|
| 76 |
+
|
| 77 |
+
bbox = (
|
| 78 |
+
(dwx, dwy),
|
| 79 |
+
(x_disp, -y_disp - height, width + x_disp, -y_disp),
|
| 80 |
+
(0, 0, width, height),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
|
| 85 |
+
except ValueError:
|
| 86 |
+
# deal with zero-width characters
|
| 87 |
+
im = Image.new("1", (width, height))
|
| 88 |
+
|
| 89 |
+
return id, int(props["ENCODING"]), bbox, im
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class BdfFontFile(FontFile.FontFile):
|
| 93 |
+
"""Font file plugin for the X11 BDF format."""
|
| 94 |
+
|
| 95 |
+
def __init__(self, fp: BinaryIO) -> None:
|
| 96 |
+
super().__init__()
|
| 97 |
+
|
| 98 |
+
s = fp.readline()
|
| 99 |
+
if not s.startswith(b"STARTFONT 2.1"):
|
| 100 |
+
msg = "not a valid BDF file"
|
| 101 |
+
raise SyntaxError(msg)
|
| 102 |
+
|
| 103 |
+
props = {}
|
| 104 |
+
comments = []
|
| 105 |
+
|
| 106 |
+
while True:
|
| 107 |
+
s = fp.readline()
|
| 108 |
+
if not s or s.startswith(b"ENDPROPERTIES"):
|
| 109 |
+
break
|
| 110 |
+
i = s.find(b" ")
|
| 111 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
| 112 |
+
if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
|
| 113 |
+
if s.find(b"LogicalFontDescription") < 0:
|
| 114 |
+
comments.append(s[i + 1 : -1].decode("ascii"))
|
| 115 |
+
|
| 116 |
+
while True:
|
| 117 |
+
c = bdf_char(fp)
|
| 118 |
+
if not c:
|
| 119 |
+
break
|
| 120 |
+
id, ch, (xy, dst, src), im = c
|
| 121 |
+
if 0 <= ch < len(self.glyph):
|
| 122 |
+
self.glyph[ch] = xy, dst, src, im
|
.venv/lib/python3.12/site-packages/PIL/BlpImagePlugin.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Blizzard Mipmap Format (.blp)
|
| 3 |
+
Jerome Leclanche <jerome@leclan.ch>
|
| 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.startswith((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 |
+
if not _accept(self.magic):
|
| 263 |
+
msg = f"Bad BLP magic {repr(self.magic)}"
|
| 264 |
+
raise BLPFormatError(msg)
|
| 265 |
+
|
| 266 |
+
compression = struct.unpack("<i", self.fp.read(4))[0]
|
| 267 |
+
if self.magic == b"BLP1":
|
| 268 |
+
alpha = struct.unpack("<I", self.fp.read(4))[0] != 0
|
| 269 |
+
else:
|
| 270 |
+
encoding = struct.unpack("<b", self.fp.read(1))[0]
|
| 271 |
+
alpha = struct.unpack("<b", self.fp.read(1))[0] != 0
|
| 272 |
+
alpha_encoding = struct.unpack("<b", self.fp.read(1))[0]
|
| 273 |
+
self.fp.seek(1, os.SEEK_CUR) # mips
|
| 274 |
+
|
| 275 |
+
self._size = struct.unpack("<II", self.fp.read(8))
|
| 276 |
+
|
| 277 |
+
args: tuple[int, int, bool] | tuple[int, int, bool, int]
|
| 278 |
+
if self.magic == b"BLP1":
|
| 279 |
+
encoding = struct.unpack("<i", self.fp.read(4))[0]
|
| 280 |
+
self.fp.seek(4, os.SEEK_CUR) # subtype
|
| 281 |
+
|
| 282 |
+
args = (compression, encoding, alpha)
|
| 283 |
+
offset = 28
|
| 284 |
+
else:
|
| 285 |
+
args = (compression, encoding, alpha, alpha_encoding)
|
| 286 |
+
offset = 20
|
| 287 |
+
|
| 288 |
+
decoder = self.magic.decode()
|
| 289 |
+
|
| 290 |
+
self._mode = "RGBA" if alpha else "RGB"
|
| 291 |
+
self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, offset, args)]
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder):
|
| 295 |
+
_pulls_fd = True
|
| 296 |
+
|
| 297 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 298 |
+
try:
|
| 299 |
+
self._read_header()
|
| 300 |
+
self._load()
|
| 301 |
+
except struct.error as e:
|
| 302 |
+
msg = "Truncated BLP file"
|
| 303 |
+
raise OSError(msg) from e
|
| 304 |
+
return -1, 0
|
| 305 |
+
|
| 306 |
+
@abc.abstractmethod
|
| 307 |
+
def _load(self) -> None:
|
| 308 |
+
pass
|
| 309 |
+
|
| 310 |
+
def _read_header(self) -> None:
|
| 311 |
+
self._offsets = struct.unpack("<16I", self._safe_read(16 * 4))
|
| 312 |
+
self._lengths = struct.unpack("<16I", self._safe_read(16 * 4))
|
| 313 |
+
|
| 314 |
+
def _safe_read(self, length: int) -> bytes:
|
| 315 |
+
assert self.fd is not None
|
| 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(
|
| 329 |
+
self, palette: list[tuple[int, int, int, int]], alpha: bool
|
| 330 |
+
) -> bytearray:
|
| 331 |
+
data = bytearray()
|
| 332 |
+
_data = BytesIO(self._safe_read(self._lengths[0]))
|
| 333 |
+
while True:
|
| 334 |
+
try:
|
| 335 |
+
(offset,) = struct.unpack("<B", _data.read(1))
|
| 336 |
+
except struct.error:
|
| 337 |
+
break
|
| 338 |
+
b, g, r, a = palette[offset]
|
| 339 |
+
d: tuple[int, ...] = (r, g, b)
|
| 340 |
+
if alpha:
|
| 341 |
+
d += (a,)
|
| 342 |
+
data.extend(d)
|
| 343 |
+
return data
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class BLP1Decoder(_BLPBaseDecoder):
|
| 347 |
+
def _load(self) -> None:
|
| 348 |
+
self._compression, self._encoding, alpha = self.args
|
| 349 |
+
|
| 350 |
+
if self._compression == Format.JPEG:
|
| 351 |
+
self._decode_jpeg_stream()
|
| 352 |
+
|
| 353 |
+
elif self._compression == 1:
|
| 354 |
+
if self._encoding in (4, 5):
|
| 355 |
+
palette = self._read_palette()
|
| 356 |
+
data = self._read_bgra(palette, alpha)
|
| 357 |
+
self.set_as_raw(data)
|
| 358 |
+
else:
|
| 359 |
+
msg = f"Unsupported BLP encoding {repr(self._encoding)}"
|
| 360 |
+
raise BLPFormatError(msg)
|
| 361 |
+
else:
|
| 362 |
+
msg = f"Unsupported BLP compression {repr(self._encoding)}"
|
| 363 |
+
raise BLPFormatError(msg)
|
| 364 |
+
|
| 365 |
+
def _decode_jpeg_stream(self) -> None:
|
| 366 |
+
from .JpegImagePlugin import JpegImageFile
|
| 367 |
+
|
| 368 |
+
(jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
|
| 369 |
+
jpeg_header = self._safe_read(jpeg_header_size)
|
| 370 |
+
assert self.fd is not None
|
| 371 |
+
self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this?
|
| 372 |
+
data = self._safe_read(self._lengths[0])
|
| 373 |
+
data = jpeg_header + data
|
| 374 |
+
image = JpegImageFile(BytesIO(data))
|
| 375 |
+
Image._decompression_bomb_check(image.size)
|
| 376 |
+
if image.mode == "CMYK":
|
| 377 |
+
args = image.tile[0].args
|
| 378 |
+
assert isinstance(args, tuple)
|
| 379 |
+
image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
|
| 380 |
+
self.set_as_raw(image.convert("RGB").tobytes(), "BGR")
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class BLP2Decoder(_BLPBaseDecoder):
|
| 384 |
+
def _load(self) -> None:
|
| 385 |
+
self._compression, self._encoding, alpha, self._alpha_encoding = self.args
|
| 386 |
+
|
| 387 |
+
palette = self._read_palette()
|
| 388 |
+
|
| 389 |
+
assert self.fd is not None
|
| 390 |
+
self.fd.seek(self._offsets[0])
|
| 391 |
+
|
| 392 |
+
if self._compression == 1:
|
| 393 |
+
# Uncompressed or DirectX compression
|
| 394 |
+
|
| 395 |
+
if self._encoding == Encoding.UNCOMPRESSED:
|
| 396 |
+
data = self._read_bgra(palette, alpha)
|
| 397 |
+
|
| 398 |
+
elif self._encoding == Encoding.DXT:
|
| 399 |
+
data = bytearray()
|
| 400 |
+
if self._alpha_encoding == AlphaEncoding.DXT1:
|
| 401 |
+
linesize = (self.state.xsize + 3) // 4 * 8
|
| 402 |
+
for yb in range((self.state.ysize + 3) // 4):
|
| 403 |
+
for d in decode_dxt1(self._safe_read(linesize), alpha):
|
| 404 |
+
data += d
|
| 405 |
+
|
| 406 |
+
elif self._alpha_encoding == AlphaEncoding.DXT3:
|
| 407 |
+
linesize = (self.state.xsize + 3) // 4 * 16
|
| 408 |
+
for yb in range((self.state.ysize + 3) // 4):
|
| 409 |
+
for d in decode_dxt3(self._safe_read(linesize)):
|
| 410 |
+
data += d
|
| 411 |
+
|
| 412 |
+
elif self._alpha_encoding == AlphaEncoding.DXT5:
|
| 413 |
+
linesize = (self.state.xsize + 3) // 4 * 16
|
| 414 |
+
for yb in range((self.state.ysize + 3) // 4):
|
| 415 |
+
for d in decode_dxt5(self._safe_read(linesize)):
|
| 416 |
+
data += d
|
| 417 |
+
else:
|
| 418 |
+
msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}"
|
| 419 |
+
raise BLPFormatError(msg)
|
| 420 |
+
else:
|
| 421 |
+
msg = f"Unknown BLP encoding {repr(self._encoding)}"
|
| 422 |
+
raise BLPFormatError(msg)
|
| 423 |
+
|
| 424 |
+
else:
|
| 425 |
+
msg = f"Unknown BLP compression {repr(self._compression)}"
|
| 426 |
+
raise BLPFormatError(msg)
|
| 427 |
+
|
| 428 |
+
self.set_as_raw(data)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class BLPEncoder(ImageFile.PyEncoder):
|
| 432 |
+
_pushes_fd = True
|
| 433 |
+
|
| 434 |
+
def _write_palette(self) -> bytes:
|
| 435 |
+
data = b""
|
| 436 |
+
assert self.im is not None
|
| 437 |
+
palette = self.im.getpalette("RGBA", "RGBA")
|
| 438 |
+
for i in range(len(palette) // 4):
|
| 439 |
+
r, g, b, a = palette[i * 4 : (i + 1) * 4]
|
| 440 |
+
data += struct.pack("<4B", b, g, r, a)
|
| 441 |
+
while len(data) < 256 * 4:
|
| 442 |
+
data += b"\x00" * 4
|
| 443 |
+
return data
|
| 444 |
+
|
| 445 |
+
def encode(self, bufsize: int) -> tuple[int, int, bytes]:
|
| 446 |
+
palette_data = self._write_palette()
|
| 447 |
+
|
| 448 |
+
offset = 20 + 16 * 4 * 2 + len(palette_data)
|
| 449 |
+
data = struct.pack("<16I", offset, *((0,) * 15))
|
| 450 |
+
|
| 451 |
+
assert self.im is not None
|
| 452 |
+
w, h = self.im.size
|
| 453 |
+
data += struct.pack("<16I", w * h, *((0,) * 15))
|
| 454 |
+
|
| 455 |
+
data += palette_data
|
| 456 |
+
|
| 457 |
+
for y in range(h):
|
| 458 |
+
for x in range(w):
|
| 459 |
+
data += struct.pack("<B", self.im.getpixel((x, y)))
|
| 460 |
+
|
| 461 |
+
return len(data), 0, data
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 465 |
+
if im.mode != "P":
|
| 466 |
+
msg = "Unsupported BLP image mode"
|
| 467 |
+
raise ValueError(msg)
|
| 468 |
+
|
| 469 |
+
magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
|
| 470 |
+
fp.write(magic)
|
| 471 |
+
|
| 472 |
+
assert im.palette is not None
|
| 473 |
+
fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
|
| 474 |
+
|
| 475 |
+
alpha_depth = 1 if im.palette.mode == "RGBA" else 0
|
| 476 |
+
if magic == b"BLP1":
|
| 477 |
+
fp.write(struct.pack("<L", alpha_depth))
|
| 478 |
+
else:
|
| 479 |
+
fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
|
| 480 |
+
fp.write(struct.pack("<b", alpha_depth))
|
| 481 |
+
fp.write(struct.pack("<b", 0)) # alpha encoding
|
| 482 |
+
fp.write(struct.pack("<b", 0)) # mips
|
| 483 |
+
fp.write(struct.pack("<II", *im.size))
|
| 484 |
+
if magic == b"BLP1":
|
| 485 |
+
fp.write(struct.pack("<i", 5))
|
| 486 |
+
fp.write(struct.pack("<i", 0))
|
| 487 |
+
|
| 488 |
+
ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0) + im.size, 0, im.mode)])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
|
| 492 |
+
Image.register_extension(BlpImageFile.format, ".blp")
|
| 493 |
+
Image.register_decoder("BLP1", BLP1Decoder)
|
| 494 |
+
Image.register_decoder("BLP2", BLP2Decoder)
|
| 495 |
+
|
| 496 |
+
Image.register_save(BlpImageFile.format, _save)
|
| 497 |
+
Image.register_encoder("BLP", BLPEncoder)
|
.venv/lib/python3.12/site-packages/PIL/BmpImagePlugin.py
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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, Any
|
| 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 |
+
USE_RAW_ALPHA = False
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _accept(prefix: bytes) -> bool:
|
| 55 |
+
return prefix.startswith(b"BM")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _dib_accept(prefix: bytes) -> bool:
|
| 59 |
+
return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# =============================================================================
|
| 63 |
+
# Image plugin for the Windows BMP format.
|
| 64 |
+
# =============================================================================
|
| 65 |
+
class BmpImageFile(ImageFile.ImageFile):
|
| 66 |
+
"""Image plugin for the Windows Bitmap format (BMP)"""
|
| 67 |
+
|
| 68 |
+
# ------------------------------------------------------------- Description
|
| 69 |
+
format_description = "Windows Bitmap"
|
| 70 |
+
format = "BMP"
|
| 71 |
+
|
| 72 |
+
# -------------------------------------------------- BMP Compression values
|
| 73 |
+
COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
|
| 74 |
+
for k, v in COMPRESSIONS.items():
|
| 75 |
+
vars()[k] = v
|
| 76 |
+
|
| 77 |
+
def _bitmap(self, header: int = 0, offset: int = 0) -> None:
|
| 78 |
+
"""Read relevant info about the BMP"""
|
| 79 |
+
read, seek = self.fp.read, self.fp.seek
|
| 80 |
+
if header:
|
| 81 |
+
seek(header)
|
| 82 |
+
# read bmp header size @offset 14 (this is part of the header size)
|
| 83 |
+
file_info: dict[str, bool | int | tuple[int, ...]] = {
|
| 84 |
+
"header_size": i32(read(4)),
|
| 85 |
+
"direction": -1,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# -------------------- If requested, read header at a specific position
|
| 89 |
+
# read the rest of the bmp header, without its size
|
| 90 |
+
assert isinstance(file_info["header_size"], int)
|
| 91 |
+
header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
|
| 92 |
+
|
| 93 |
+
# ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
|
| 94 |
+
# ----- This format has different offsets because of width/height types
|
| 95 |
+
# 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
|
| 96 |
+
if file_info["header_size"] == 12:
|
| 97 |
+
file_info["width"] = i16(header_data, 0)
|
| 98 |
+
file_info["height"] = i16(header_data, 2)
|
| 99 |
+
file_info["planes"] = i16(header_data, 4)
|
| 100 |
+
file_info["bits"] = i16(header_data, 6)
|
| 101 |
+
file_info["compression"] = self.COMPRESSIONS["RAW"]
|
| 102 |
+
file_info["palette_padding"] = 3
|
| 103 |
+
|
| 104 |
+
# --------------------------------------------- Windows Bitmap v3 to v5
|
| 105 |
+
# 40: BITMAPINFOHEADER
|
| 106 |
+
# 52: BITMAPV2HEADER
|
| 107 |
+
# 56: BITMAPV3HEADER
|
| 108 |
+
# 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
|
| 109 |
+
# 108: BITMAPV4HEADER
|
| 110 |
+
# 124: BITMAPV5HEADER
|
| 111 |
+
elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
|
| 112 |
+
file_info["y_flip"] = header_data[7] == 0xFF
|
| 113 |
+
file_info["direction"] = 1 if file_info["y_flip"] else -1
|
| 114 |
+
file_info["width"] = i32(header_data, 0)
|
| 115 |
+
file_info["height"] = (
|
| 116 |
+
i32(header_data, 4)
|
| 117 |
+
if not file_info["y_flip"]
|
| 118 |
+
else 2**32 - i32(header_data, 4)
|
| 119 |
+
)
|
| 120 |
+
file_info["planes"] = i16(header_data, 8)
|
| 121 |
+
file_info["bits"] = i16(header_data, 10)
|
| 122 |
+
file_info["compression"] = i32(header_data, 12)
|
| 123 |
+
# byte size of pixel data
|
| 124 |
+
file_info["data_size"] = i32(header_data, 16)
|
| 125 |
+
file_info["pixels_per_meter"] = (
|
| 126 |
+
i32(header_data, 20),
|
| 127 |
+
i32(header_data, 24),
|
| 128 |
+
)
|
| 129 |
+
file_info["colors"] = i32(header_data, 28)
|
| 130 |
+
file_info["palette_padding"] = 4
|
| 131 |
+
assert isinstance(file_info["pixels_per_meter"], tuple)
|
| 132 |
+
self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
|
| 133 |
+
if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
|
| 134 |
+
masks = ["r_mask", "g_mask", "b_mask"]
|
| 135 |
+
if len(header_data) >= 48:
|
| 136 |
+
if len(header_data) >= 52:
|
| 137 |
+
masks.append("a_mask")
|
| 138 |
+
else:
|
| 139 |
+
file_info["a_mask"] = 0x0
|
| 140 |
+
for idx, mask in enumerate(masks):
|
| 141 |
+
file_info[mask] = i32(header_data, 36 + idx * 4)
|
| 142 |
+
else:
|
| 143 |
+
# 40 byte headers only have the three components in the
|
| 144 |
+
# bitfields masks, ref:
|
| 145 |
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
|
| 146 |
+
# See also
|
| 147 |
+
# https://github.com/python-pillow/Pillow/issues/1293
|
| 148 |
+
# There is a 4th component in the RGBQuad, in the alpha
|
| 149 |
+
# location, but it is listed as a reserved component,
|
| 150 |
+
# and it is not generally an alpha channel
|
| 151 |
+
file_info["a_mask"] = 0x0
|
| 152 |
+
for mask in masks:
|
| 153 |
+
file_info[mask] = i32(read(4))
|
| 154 |
+
assert isinstance(file_info["r_mask"], int)
|
| 155 |
+
assert isinstance(file_info["g_mask"], int)
|
| 156 |
+
assert isinstance(file_info["b_mask"], int)
|
| 157 |
+
assert isinstance(file_info["a_mask"], int)
|
| 158 |
+
file_info["rgb_mask"] = (
|
| 159 |
+
file_info["r_mask"],
|
| 160 |
+
file_info["g_mask"],
|
| 161 |
+
file_info["b_mask"],
|
| 162 |
+
)
|
| 163 |
+
file_info["rgba_mask"] = (
|
| 164 |
+
file_info["r_mask"],
|
| 165 |
+
file_info["g_mask"],
|
| 166 |
+
file_info["b_mask"],
|
| 167 |
+
file_info["a_mask"],
|
| 168 |
+
)
|
| 169 |
+
else:
|
| 170 |
+
msg = f"Unsupported BMP header type ({file_info['header_size']})"
|
| 171 |
+
raise OSError(msg)
|
| 172 |
+
|
| 173 |
+
# ------------------ Special case : header is reported 40, which
|
| 174 |
+
# ---------------------- is shorter than real size for bpp >= 16
|
| 175 |
+
assert isinstance(file_info["width"], int)
|
| 176 |
+
assert isinstance(file_info["height"], int)
|
| 177 |
+
self._size = file_info["width"], file_info["height"]
|
| 178 |
+
|
| 179 |
+
# ------- If color count was not found in the header, compute from bits
|
| 180 |
+
assert isinstance(file_info["bits"], int)
|
| 181 |
+
file_info["colors"] = (
|
| 182 |
+
file_info["colors"]
|
| 183 |
+
if file_info.get("colors", 0)
|
| 184 |
+
else (1 << file_info["bits"])
|
| 185 |
+
)
|
| 186 |
+
assert isinstance(file_info["colors"], int)
|
| 187 |
+
if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
|
| 188 |
+
offset += 4 * file_info["colors"]
|
| 189 |
+
|
| 190 |
+
# ---------------------- Check bit depth for unusual unsupported values
|
| 191 |
+
self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
|
| 192 |
+
if not self.mode:
|
| 193 |
+
msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
|
| 194 |
+
raise OSError(msg)
|
| 195 |
+
|
| 196 |
+
# ---------------- Process BMP with Bitfields compression (not palette)
|
| 197 |
+
decoder_name = "raw"
|
| 198 |
+
if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
|
| 199 |
+
SUPPORTED: dict[int, list[tuple[int, ...]]] = {
|
| 200 |
+
32: [
|
| 201 |
+
(0xFF0000, 0xFF00, 0xFF, 0x0),
|
| 202 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0x0),
|
| 203 |
+
(0xFF000000, 0xFF00, 0xFF, 0x0),
|
| 204 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0xFF),
|
| 205 |
+
(0xFF, 0xFF00, 0xFF0000, 0xFF000000),
|
| 206 |
+
(0xFF0000, 0xFF00, 0xFF, 0xFF000000),
|
| 207 |
+
(0xFF000000, 0xFF00, 0xFF, 0xFF0000),
|
| 208 |
+
(0x0, 0x0, 0x0, 0x0),
|
| 209 |
+
],
|
| 210 |
+
24: [(0xFF0000, 0xFF00, 0xFF)],
|
| 211 |
+
16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
|
| 212 |
+
}
|
| 213 |
+
MASK_MODES = {
|
| 214 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
|
| 215 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
|
| 216 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
|
| 217 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
|
| 218 |
+
(32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
|
| 219 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
|
| 220 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
|
| 221 |
+
(32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
|
| 222 |
+
(24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
|
| 223 |
+
(16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
|
| 224 |
+
(16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
|
| 225 |
+
}
|
| 226 |
+
if file_info["bits"] in SUPPORTED:
|
| 227 |
+
if (
|
| 228 |
+
file_info["bits"] == 32
|
| 229 |
+
and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
|
| 230 |
+
):
|
| 231 |
+
assert isinstance(file_info["rgba_mask"], tuple)
|
| 232 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
|
| 233 |
+
self._mode = "RGBA" if "A" in raw_mode else self.mode
|
| 234 |
+
elif (
|
| 235 |
+
file_info["bits"] in (24, 16)
|
| 236 |
+
and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
|
| 237 |
+
):
|
| 238 |
+
assert isinstance(file_info["rgb_mask"], tuple)
|
| 239 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
|
| 240 |
+
else:
|
| 241 |
+
msg = "Unsupported BMP bitfields layout"
|
| 242 |
+
raise OSError(msg)
|
| 243 |
+
else:
|
| 244 |
+
msg = "Unsupported BMP bitfields layout"
|
| 245 |
+
raise OSError(msg)
|
| 246 |
+
elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
|
| 247 |
+
if file_info["bits"] == 32 and (
|
| 248 |
+
header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
|
| 249 |
+
):
|
| 250 |
+
raw_mode, self._mode = "BGRA", "RGBA"
|
| 251 |
+
elif file_info["compression"] in (
|
| 252 |
+
self.COMPRESSIONS["RLE8"],
|
| 253 |
+
self.COMPRESSIONS["RLE4"],
|
| 254 |
+
):
|
| 255 |
+
decoder_name = "bmp_rle"
|
| 256 |
+
else:
|
| 257 |
+
msg = f"Unsupported BMP compression ({file_info['compression']})"
|
| 258 |
+
raise OSError(msg)
|
| 259 |
+
|
| 260 |
+
# --------------- Once the header is processed, process the palette/LUT
|
| 261 |
+
if self.mode == "P": # Paletted for 1, 4 and 8 bit images
|
| 262 |
+
# ---------------------------------------------------- 1-bit images
|
| 263 |
+
if not (0 < file_info["colors"] <= 65536):
|
| 264 |
+
msg = f"Unsupported BMP Palette size ({file_info['colors']})"
|
| 265 |
+
raise OSError(msg)
|
| 266 |
+
else:
|
| 267 |
+
assert isinstance(file_info["palette_padding"], int)
|
| 268 |
+
padding = file_info["palette_padding"]
|
| 269 |
+
palette = read(padding * file_info["colors"])
|
| 270 |
+
grayscale = True
|
| 271 |
+
indices = (
|
| 272 |
+
(0, 255)
|
| 273 |
+
if file_info["colors"] == 2
|
| 274 |
+
else list(range(file_info["colors"]))
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
# ----------------- Check if grayscale and ignore palette if so
|
| 278 |
+
for ind, val in enumerate(indices):
|
| 279 |
+
rgb = palette[ind * padding : ind * padding + 3]
|
| 280 |
+
if rgb != o8(val) * 3:
|
| 281 |
+
grayscale = False
|
| 282 |
+
|
| 283 |
+
# ------- If all colors are gray, white or black, ditch palette
|
| 284 |
+
if grayscale:
|
| 285 |
+
self._mode = "1" if file_info["colors"] == 2 else "L"
|
| 286 |
+
raw_mode = self.mode
|
| 287 |
+
else:
|
| 288 |
+
self._mode = "P"
|
| 289 |
+
self.palette = ImagePalette.raw(
|
| 290 |
+
"BGRX" if padding == 4 else "BGR", palette
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
# ---------------------------- Finally set the tile data for the plugin
|
| 294 |
+
self.info["compression"] = file_info["compression"]
|
| 295 |
+
args: list[Any] = [raw_mode]
|
| 296 |
+
if decoder_name == "bmp_rle":
|
| 297 |
+
args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
|
| 298 |
+
else:
|
| 299 |
+
assert isinstance(file_info["width"], int)
|
| 300 |
+
args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
|
| 301 |
+
args.append(file_info["direction"])
|
| 302 |
+
self.tile = [
|
| 303 |
+
ImageFile._Tile(
|
| 304 |
+
decoder_name,
|
| 305 |
+
(0, 0, file_info["width"], file_info["height"]),
|
| 306 |
+
offset or self.fp.tell(),
|
| 307 |
+
tuple(args),
|
| 308 |
+
)
|
| 309 |
+
]
|
| 310 |
+
|
| 311 |
+
def _open(self) -> None:
|
| 312 |
+
"""Open file, check magic number and read header"""
|
| 313 |
+
# read 14 bytes: magic number, filesize, reserved, header final offset
|
| 314 |
+
head_data = self.fp.read(14)
|
| 315 |
+
# choke if the file does not have the required magic bytes
|
| 316 |
+
if not _accept(head_data):
|
| 317 |
+
msg = "Not a BMP file"
|
| 318 |
+
raise SyntaxError(msg)
|
| 319 |
+
# read the start position of the BMP image data (u32)
|
| 320 |
+
offset = i32(head_data, 10)
|
| 321 |
+
# load bitmap information (offset=raster info)
|
| 322 |
+
self._bitmap(offset=offset)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class BmpRleDecoder(ImageFile.PyDecoder):
|
| 326 |
+
_pulls_fd = True
|
| 327 |
+
|
| 328 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 329 |
+
assert self.fd is not None
|
| 330 |
+
rle4 = self.args[1]
|
| 331 |
+
data = bytearray()
|
| 332 |
+
x = 0
|
| 333 |
+
dest_length = self.state.xsize * self.state.ysize
|
| 334 |
+
while len(data) < dest_length:
|
| 335 |
+
pixels = self.fd.read(1)
|
| 336 |
+
byte = self.fd.read(1)
|
| 337 |
+
if not pixels or not byte:
|
| 338 |
+
break
|
| 339 |
+
num_pixels = pixels[0]
|
| 340 |
+
if num_pixels:
|
| 341 |
+
# encoded mode
|
| 342 |
+
if x + num_pixels > self.state.xsize:
|
| 343 |
+
# Too much data for row
|
| 344 |
+
num_pixels = max(0, self.state.xsize - x)
|
| 345 |
+
if rle4:
|
| 346 |
+
first_pixel = o8(byte[0] >> 4)
|
| 347 |
+
second_pixel = o8(byte[0] & 0x0F)
|
| 348 |
+
for index in range(num_pixels):
|
| 349 |
+
if index % 2 == 0:
|
| 350 |
+
data += first_pixel
|
| 351 |
+
else:
|
| 352 |
+
data += second_pixel
|
| 353 |
+
else:
|
| 354 |
+
data += byte * num_pixels
|
| 355 |
+
x += num_pixels
|
| 356 |
+
else:
|
| 357 |
+
if byte[0] == 0:
|
| 358 |
+
# end of line
|
| 359 |
+
while len(data) % self.state.xsize != 0:
|
| 360 |
+
data += b"\x00"
|
| 361 |
+
x = 0
|
| 362 |
+
elif byte[0] == 1:
|
| 363 |
+
# end of bitmap
|
| 364 |
+
break
|
| 365 |
+
elif byte[0] == 2:
|
| 366 |
+
# delta
|
| 367 |
+
bytes_read = self.fd.read(2)
|
| 368 |
+
if len(bytes_read) < 2:
|
| 369 |
+
break
|
| 370 |
+
right, up = self.fd.read(2)
|
| 371 |
+
data += b"\x00" * (right + up * self.state.xsize)
|
| 372 |
+
x = len(data) % self.state.xsize
|
| 373 |
+
else:
|
| 374 |
+
# absolute mode
|
| 375 |
+
if rle4:
|
| 376 |
+
# 2 pixels per byte
|
| 377 |
+
byte_count = byte[0] // 2
|
| 378 |
+
bytes_read = self.fd.read(byte_count)
|
| 379 |
+
for byte_read in bytes_read:
|
| 380 |
+
data += o8(byte_read >> 4)
|
| 381 |
+
data += o8(byte_read & 0x0F)
|
| 382 |
+
else:
|
| 383 |
+
byte_count = byte[0]
|
| 384 |
+
bytes_read = self.fd.read(byte_count)
|
| 385 |
+
data += bytes_read
|
| 386 |
+
if len(bytes_read) < byte_count:
|
| 387 |
+
break
|
| 388 |
+
x += byte[0]
|
| 389 |
+
|
| 390 |
+
# align to 16-bit word boundary
|
| 391 |
+
if self.fd.tell() % 2 != 0:
|
| 392 |
+
self.fd.seek(1, os.SEEK_CUR)
|
| 393 |
+
rawmode = "L" if self.mode == "L" else "P"
|
| 394 |
+
self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
|
| 395 |
+
return -1, 0
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
# =============================================================================
|
| 399 |
+
# Image plugin for the DIB format (BMP alias)
|
| 400 |
+
# =============================================================================
|
| 401 |
+
class DibImageFile(BmpImageFile):
|
| 402 |
+
format = "DIB"
|
| 403 |
+
format_description = "Windows Bitmap"
|
| 404 |
+
|
| 405 |
+
def _open(self) -> None:
|
| 406 |
+
self._bitmap()
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
#
|
| 410 |
+
# --------------------------------------------------------------------
|
| 411 |
+
# Write BMP file
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
SAVE = {
|
| 415 |
+
"1": ("1", 1, 2),
|
| 416 |
+
"L": ("L", 8, 256),
|
| 417 |
+
"P": ("P", 8, 256),
|
| 418 |
+
"RGB": ("BGR", 24, 0),
|
| 419 |
+
"RGBA": ("BGRA", 32, 0),
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 424 |
+
_save(im, fp, filename, False)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _save(
|
| 428 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
|
| 429 |
+
) -> None:
|
| 430 |
+
try:
|
| 431 |
+
rawmode, bits, colors = SAVE[im.mode]
|
| 432 |
+
except KeyError as e:
|
| 433 |
+
msg = f"cannot write mode {im.mode} as BMP"
|
| 434 |
+
raise OSError(msg) from e
|
| 435 |
+
|
| 436 |
+
info = im.encoderinfo
|
| 437 |
+
|
| 438 |
+
dpi = info.get("dpi", (96, 96))
|
| 439 |
+
|
| 440 |
+
# 1 meter == 39.3701 inches
|
| 441 |
+
ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
|
| 442 |
+
|
| 443 |
+
stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
|
| 444 |
+
header = 40 # or 64 for OS/2 version 2
|
| 445 |
+
image = stride * im.size[1]
|
| 446 |
+
|
| 447 |
+
if im.mode == "1":
|
| 448 |
+
palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
|
| 449 |
+
elif im.mode == "L":
|
| 450 |
+
palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
|
| 451 |
+
elif im.mode == "P":
|
| 452 |
+
palette = im.im.getpalette("RGB", "BGRX")
|
| 453 |
+
colors = len(palette) // 4
|
| 454 |
+
else:
|
| 455 |
+
palette = None
|
| 456 |
+
|
| 457 |
+
# bitmap header
|
| 458 |
+
if bitmap_header:
|
| 459 |
+
offset = 14 + header + colors * 4
|
| 460 |
+
file_size = offset + image
|
| 461 |
+
if file_size > 2**32 - 1:
|
| 462 |
+
msg = "File size is too large for the BMP format"
|
| 463 |
+
raise ValueError(msg)
|
| 464 |
+
fp.write(
|
| 465 |
+
b"BM" # file type (magic)
|
| 466 |
+
+ o32(file_size) # file size
|
| 467 |
+
+ o32(0) # reserved
|
| 468 |
+
+ o32(offset) # image data offset
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# bitmap info header
|
| 472 |
+
fp.write(
|
| 473 |
+
o32(header) # info header size
|
| 474 |
+
+ o32(im.size[0]) # width
|
| 475 |
+
+ o32(im.size[1]) # height
|
| 476 |
+
+ o16(1) # planes
|
| 477 |
+
+ o16(bits) # depth
|
| 478 |
+
+ o32(0) # compression (0=uncompressed)
|
| 479 |
+
+ o32(image) # size of bitmap
|
| 480 |
+
+ o32(ppm[0]) # resolution
|
| 481 |
+
+ o32(ppm[1]) # resolution
|
| 482 |
+
+ o32(colors) # colors used
|
| 483 |
+
+ o32(colors) # colors important
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
|
| 487 |
+
|
| 488 |
+
if palette:
|
| 489 |
+
fp.write(palette)
|
| 490 |
+
|
| 491 |
+
ImageFile._save(
|
| 492 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
#
|
| 497 |
+
# --------------------------------------------------------------------
|
| 498 |
+
# Registry
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
|
| 502 |
+
Image.register_save(BmpImageFile.format, _save)
|
| 503 |
+
|
| 504 |
+
Image.register_extension(BmpImageFile.format, ".bmp")
|
| 505 |
+
|
| 506 |
+
Image.register_mime(BmpImageFile.format, "image/bmp")
|
| 507 |
+
|
| 508 |
+
Image.register_decoder("bmp_rle", BmpRleDecoder)
|
| 509 |
+
|
| 510 |
+
Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
|
| 511 |
+
Image.register_save(DibImageFile.format, _dib_save)
|
| 512 |
+
|
| 513 |
+
Image.register_extension(DibImageFile.format, ".dib")
|
| 514 |
+
|
| 515 |
+
Image.register_mime(DibImageFile.format, "image/bmp")
|
.venv/lib/python3.12/site-packages/PIL/BufrStubImagePlugin.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 14 |
+
from typing import IO
|
| 15 |
+
|
| 16 |
+
from . import Image, ImageFile
|
| 17 |
+
|
| 18 |
+
_handler = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 22 |
+
"""
|
| 23 |
+
Install application-specific BUFR image handler.
|
| 24 |
+
|
| 25 |
+
:param handler: Handler object.
|
| 26 |
+
"""
|
| 27 |
+
global _handler
|
| 28 |
+
_handler = handler
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# --------------------------------------------------------------------
|
| 32 |
+
# Image adapter
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _accept(prefix: bytes) -> bool:
|
| 36 |
+
return prefix.startswith((b"BUFR", b"ZCZC"))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BufrStubImageFile(ImageFile.StubImageFile):
|
| 40 |
+
format = "BUFR"
|
| 41 |
+
format_description = "BUFR"
|
| 42 |
+
|
| 43 |
+
def _open(self) -> None:
|
| 44 |
+
if not _accept(self.fp.read(4)):
|
| 45 |
+
msg = "Not a BUFR file"
|
| 46 |
+
raise SyntaxError(msg)
|
| 47 |
+
|
| 48 |
+
self.fp.seek(-4, os.SEEK_CUR)
|
| 49 |
+
|
| 50 |
+
# make something up
|
| 51 |
+
self._mode = "F"
|
| 52 |
+
self._size = 1, 1
|
| 53 |
+
|
| 54 |
+
loader = self._load()
|
| 55 |
+
if loader:
|
| 56 |
+
loader.open(self)
|
| 57 |
+
|
| 58 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 59 |
+
return _handler
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 63 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 64 |
+
msg = "BUFR save handler not installed"
|
| 65 |
+
raise OSError(msg)
|
| 66 |
+
_handler.save(im, fp, filename)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# --------------------------------------------------------------------
|
| 70 |
+
# Registry
|
| 71 |
+
|
| 72 |
+
Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
|
| 73 |
+
Image.register_save(BufrStubImageFile.format, _save)
|
| 74 |
+
|
| 75 |
+
Image.register_extension(BufrStubImageFile.format, ".bufr")
|
.venv/lib/python3.12/site-packages/PIL/ContainerIO.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 collections.abc import Iterable
|
| 20 |
+
from typing import IO, AnyStr, NoReturn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ContainerIO(IO[AnyStr]):
|
| 24 |
+
"""
|
| 25 |
+
A file object that provides read access to a part of an existing
|
| 26 |
+
file (for example a TAR file).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
|
| 30 |
+
"""
|
| 31 |
+
Create file object.
|
| 32 |
+
|
| 33 |
+
:param file: Existing file.
|
| 34 |
+
:param offset: Start of region, in bytes.
|
| 35 |
+
:param length: Size of region, in bytes.
|
| 36 |
+
"""
|
| 37 |
+
self.fh: IO[AnyStr] = file
|
| 38 |
+
self.pos = 0
|
| 39 |
+
self.offset = offset
|
| 40 |
+
self.length = length
|
| 41 |
+
self.fh.seek(offset)
|
| 42 |
+
|
| 43 |
+
##
|
| 44 |
+
# Always false.
|
| 45 |
+
|
| 46 |
+
def isatty(self) -> bool:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
def seekable(self) -> bool:
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
def seek(self, offset: int, mode: int = io.SEEK_SET) -> int:
|
| 53 |
+
"""
|
| 54 |
+
Move file pointer.
|
| 55 |
+
|
| 56 |
+
:param offset: Offset in bytes.
|
| 57 |
+
:param mode: Starting position. Use 0 for beginning of region, 1
|
| 58 |
+
for current offset, and 2 for end of region. You cannot move
|
| 59 |
+
the pointer outside the defined region.
|
| 60 |
+
:returns: Offset from start of region, in bytes.
|
| 61 |
+
"""
|
| 62 |
+
if mode == 1:
|
| 63 |
+
self.pos = self.pos + offset
|
| 64 |
+
elif mode == 2:
|
| 65 |
+
self.pos = self.length + offset
|
| 66 |
+
else:
|
| 67 |
+
self.pos = offset
|
| 68 |
+
# clamp
|
| 69 |
+
self.pos = max(0, min(self.pos, self.length))
|
| 70 |
+
self.fh.seek(self.offset + self.pos)
|
| 71 |
+
return self.pos
|
| 72 |
+
|
| 73 |
+
def tell(self) -> int:
|
| 74 |
+
"""
|
| 75 |
+
Get current file pointer.
|
| 76 |
+
|
| 77 |
+
:returns: Offset from start of region, in bytes.
|
| 78 |
+
"""
|
| 79 |
+
return self.pos
|
| 80 |
+
|
| 81 |
+
def readable(self) -> bool:
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def read(self, n: int = -1) -> AnyStr:
|
| 85 |
+
"""
|
| 86 |
+
Read data.
|
| 87 |
+
|
| 88 |
+
:param n: Number of bytes to read. If omitted, zero or negative,
|
| 89 |
+
read until end of region.
|
| 90 |
+
:returns: An 8-bit string.
|
| 91 |
+
"""
|
| 92 |
+
if n > 0:
|
| 93 |
+
n = min(n, self.length - self.pos)
|
| 94 |
+
else:
|
| 95 |
+
n = self.length - self.pos
|
| 96 |
+
if n <= 0: # EOF
|
| 97 |
+
return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
|
| 98 |
+
self.pos = self.pos + n
|
| 99 |
+
return self.fh.read(n)
|
| 100 |
+
|
| 101 |
+
def readline(self, n: int = -1) -> AnyStr:
|
| 102 |
+
"""
|
| 103 |
+
Read a line of text.
|
| 104 |
+
|
| 105 |
+
:param n: Number of bytes to read. If omitted, zero or negative,
|
| 106 |
+
read until end of line.
|
| 107 |
+
:returns: An 8-bit string.
|
| 108 |
+
"""
|
| 109 |
+
s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
|
| 110 |
+
newline_character = b"\n" if "b" in self.fh.mode else "\n"
|
| 111 |
+
while True:
|
| 112 |
+
c = self.read(1)
|
| 113 |
+
if not c:
|
| 114 |
+
break
|
| 115 |
+
s = s + c
|
| 116 |
+
if c == newline_character or len(s) == n:
|
| 117 |
+
break
|
| 118 |
+
return s
|
| 119 |
+
|
| 120 |
+
def readlines(self, n: int | None = -1) -> list[AnyStr]:
|
| 121 |
+
"""
|
| 122 |
+
Read multiple lines of text.
|
| 123 |
+
|
| 124 |
+
:param n: Number of lines to read. If omitted, zero, negative or None,
|
| 125 |
+
read until end of region.
|
| 126 |
+
:returns: A list of 8-bit strings.
|
| 127 |
+
"""
|
| 128 |
+
lines = []
|
| 129 |
+
while True:
|
| 130 |
+
s = self.readline()
|
| 131 |
+
if not s:
|
| 132 |
+
break
|
| 133 |
+
lines.append(s)
|
| 134 |
+
if len(lines) == n:
|
| 135 |
+
break
|
| 136 |
+
return lines
|
| 137 |
+
|
| 138 |
+
def writable(self) -> bool:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
def write(self, b: AnyStr) -> NoReturn:
|
| 142 |
+
raise NotImplementedError()
|
| 143 |
+
|
| 144 |
+
def writelines(self, lines: Iterable[AnyStr]) -> NoReturn:
|
| 145 |
+
raise NotImplementedError()
|
| 146 |
+
|
| 147 |
+
def truncate(self, size: int | None = None) -> int:
|
| 148 |
+
raise NotImplementedError()
|
| 149 |
+
|
| 150 |
+
def __enter__(self) -> ContainerIO[AnyStr]:
|
| 151 |
+
return self
|
| 152 |
+
|
| 153 |
+
def __exit__(self, *args: object) -> None:
|
| 154 |
+
self.close()
|
| 155 |
+
|
| 156 |
+
def __iter__(self) -> ContainerIO[AnyStr]:
|
| 157 |
+
return self
|
| 158 |
+
|
| 159 |
+
def __next__(self) -> AnyStr:
|
| 160 |
+
line = self.readline()
|
| 161 |
+
if not line:
|
| 162 |
+
msg = "end of region"
|
| 163 |
+
raise StopIteration(msg)
|
| 164 |
+
return line
|
| 165 |
+
|
| 166 |
+
def fileno(self) -> int:
|
| 167 |
+
return self.fh.fileno()
|
| 168 |
+
|
| 169 |
+
def flush(self) -> None:
|
| 170 |
+
self.fh.flush()
|
| 171 |
+
|
| 172 |
+
def close(self) -> None:
|
| 173 |
+
self.fh.close()
|
.venv/lib/python3.12/site-packages/PIL/DcxImagePlugin.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ._util import DeferredError
|
| 28 |
+
from .PcxImagePlugin import PcxImageFile
|
| 29 |
+
|
| 30 |
+
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _accept(prefix: bytes) -> bool:
|
| 34 |
+
return len(prefix) >= 4 and i32(prefix) == MAGIC
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
##
|
| 38 |
+
# Image plugin for the Intel DCX format.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class DcxImageFile(PcxImageFile):
|
| 42 |
+
format = "DCX"
|
| 43 |
+
format_description = "Intel DCX"
|
| 44 |
+
_close_exclusive_fp_after_loading = False
|
| 45 |
+
|
| 46 |
+
def _open(self) -> None:
|
| 47 |
+
# Header
|
| 48 |
+
s = self.fp.read(4)
|
| 49 |
+
if not _accept(s):
|
| 50 |
+
msg = "not a DCX file"
|
| 51 |
+
raise SyntaxError(msg)
|
| 52 |
+
|
| 53 |
+
# Component directory
|
| 54 |
+
self._offset = []
|
| 55 |
+
for i in range(1024):
|
| 56 |
+
offset = i32(self.fp.read(4))
|
| 57 |
+
if not offset:
|
| 58 |
+
break
|
| 59 |
+
self._offset.append(offset)
|
| 60 |
+
|
| 61 |
+
self._fp = self.fp
|
| 62 |
+
self.frame = -1
|
| 63 |
+
self.n_frames = len(self._offset)
|
| 64 |
+
self.is_animated = self.n_frames > 1
|
| 65 |
+
self.seek(0)
|
| 66 |
+
|
| 67 |
+
def seek(self, frame: int) -> None:
|
| 68 |
+
if not self._seek_check(frame):
|
| 69 |
+
return
|
| 70 |
+
if isinstance(self._fp, DeferredError):
|
| 71 |
+
raise self._fp.ex
|
| 72 |
+
self.frame = frame
|
| 73 |
+
self.fp = self._fp
|
| 74 |
+
self.fp.seek(self._offset[frame])
|
| 75 |
+
PcxImageFile._open(self)
|
| 76 |
+
|
| 77 |
+
def tell(self) -> int:
|
| 78 |
+
return self.frame
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
|
| 82 |
+
|
| 83 |
+
Image.register_extension(DcxImageFile.format, ".dcx")
|
.venv/lib/python3.12/site-packages/PIL/EpsImagePlugin.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
|
| 35 |
+
# --------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
|
| 39 |
+
field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
|
| 40 |
+
|
| 41 |
+
gs_binary: str | bool | None = None
|
| 42 |
+
gs_windows_binary = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def has_ghostscript() -> bool:
|
| 46 |
+
global gs_binary, gs_windows_binary
|
| 47 |
+
if gs_binary is None:
|
| 48 |
+
if sys.platform.startswith("win"):
|
| 49 |
+
if gs_windows_binary is None:
|
| 50 |
+
import shutil
|
| 51 |
+
|
| 52 |
+
for binary in ("gswin32c", "gswin64c", "gs"):
|
| 53 |
+
if shutil.which(binary) is not None:
|
| 54 |
+
gs_windows_binary = binary
|
| 55 |
+
break
|
| 56 |
+
else:
|
| 57 |
+
gs_windows_binary = False
|
| 58 |
+
gs_binary = gs_windows_binary
|
| 59 |
+
else:
|
| 60 |
+
try:
|
| 61 |
+
subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
|
| 62 |
+
gs_binary = "gs"
|
| 63 |
+
except OSError:
|
| 64 |
+
gs_binary = False
|
| 65 |
+
return gs_binary is not False
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def Ghostscript(
|
| 69 |
+
tile: list[ImageFile._Tile],
|
| 70 |
+
size: tuple[int, int],
|
| 71 |
+
fp: IO[bytes],
|
| 72 |
+
scale: int = 1,
|
| 73 |
+
transparency: bool = False,
|
| 74 |
+
) -> Image.core.ImagingCore:
|
| 75 |
+
"""Render an image using Ghostscript"""
|
| 76 |
+
global gs_binary
|
| 77 |
+
if not has_ghostscript():
|
| 78 |
+
msg = "Unable to locate Ghostscript on paths"
|
| 79 |
+
raise OSError(msg)
|
| 80 |
+
assert isinstance(gs_binary, str)
|
| 81 |
+
|
| 82 |
+
# Unpack decoder tile
|
| 83 |
+
args = tile[0].args
|
| 84 |
+
assert isinstance(args, tuple)
|
| 85 |
+
length, bbox = args
|
| 86 |
+
|
| 87 |
+
# Hack to support hi-res rendering
|
| 88 |
+
scale = int(scale) or 1
|
| 89 |
+
width = size[0] * scale
|
| 90 |
+
height = size[1] * scale
|
| 91 |
+
# resolution is dependent on bbox and size
|
| 92 |
+
res_x = 72.0 * width / (bbox[2] - bbox[0])
|
| 93 |
+
res_y = 72.0 * height / (bbox[3] - bbox[1])
|
| 94 |
+
|
| 95 |
+
out_fd, outfile = tempfile.mkstemp()
|
| 96 |
+
os.close(out_fd)
|
| 97 |
+
|
| 98 |
+
infile_temp = None
|
| 99 |
+
if hasattr(fp, "name") and os.path.exists(fp.name):
|
| 100 |
+
infile = fp.name
|
| 101 |
+
else:
|
| 102 |
+
in_fd, infile_temp = tempfile.mkstemp()
|
| 103 |
+
os.close(in_fd)
|
| 104 |
+
infile = infile_temp
|
| 105 |
+
|
| 106 |
+
# Ignore length and offset!
|
| 107 |
+
# Ghostscript can read it
|
| 108 |
+
# Copy whole file to read in Ghostscript
|
| 109 |
+
with open(infile_temp, "wb") as f:
|
| 110 |
+
# fetch length of fp
|
| 111 |
+
fp.seek(0, io.SEEK_END)
|
| 112 |
+
fsize = fp.tell()
|
| 113 |
+
# ensure start position
|
| 114 |
+
# go back
|
| 115 |
+
fp.seek(0)
|
| 116 |
+
lengthfile = fsize
|
| 117 |
+
while lengthfile > 0:
|
| 118 |
+
s = fp.read(min(lengthfile, 100 * 1024))
|
| 119 |
+
if not s:
|
| 120 |
+
break
|
| 121 |
+
lengthfile -= len(s)
|
| 122 |
+
f.write(s)
|
| 123 |
+
|
| 124 |
+
if transparency:
|
| 125 |
+
# "RGBA"
|
| 126 |
+
device = "pngalpha"
|
| 127 |
+
else:
|
| 128 |
+
# "pnmraw" automatically chooses between
|
| 129 |
+
# PBM ("1"), PGM ("L"), and PPM ("RGB").
|
| 130 |
+
device = "pnmraw"
|
| 131 |
+
|
| 132 |
+
# Build Ghostscript command
|
| 133 |
+
command = [
|
| 134 |
+
gs_binary,
|
| 135 |
+
"-q", # quiet mode
|
| 136 |
+
f"-g{width:d}x{height:d}", # set output geometry (pixels)
|
| 137 |
+
f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
|
| 138 |
+
"-dBATCH", # exit after processing
|
| 139 |
+
"-dNOPAUSE", # don't pause between pages
|
| 140 |
+
"-dSAFER", # safe mode
|
| 141 |
+
f"-sDEVICE={device}",
|
| 142 |
+
f"-sOutputFile={outfile}", # output file
|
| 143 |
+
# adjust for image origin
|
| 144 |
+
"-c",
|
| 145 |
+
f"{-bbox[0]} {-bbox[1]} translate",
|
| 146 |
+
"-f",
|
| 147 |
+
infile, # input file
|
| 148 |
+
# showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
|
| 149 |
+
"-c",
|
| 150 |
+
"showpage",
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
# push data through Ghostscript
|
| 154 |
+
try:
|
| 155 |
+
startupinfo = None
|
| 156 |
+
if sys.platform.startswith("win"):
|
| 157 |
+
startupinfo = subprocess.STARTUPINFO()
|
| 158 |
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
| 159 |
+
subprocess.check_call(command, startupinfo=startupinfo)
|
| 160 |
+
with Image.open(outfile) as out_im:
|
| 161 |
+
out_im.load()
|
| 162 |
+
return out_im.im.copy()
|
| 163 |
+
finally:
|
| 164 |
+
try:
|
| 165 |
+
os.unlink(outfile)
|
| 166 |
+
if infile_temp:
|
| 167 |
+
os.unlink(infile_temp)
|
| 168 |
+
except OSError:
|
| 169 |
+
pass
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _accept(prefix: bytes) -> bool:
|
| 173 |
+
return prefix.startswith(b"%!PS") or (
|
| 174 |
+
len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
##
|
| 179 |
+
# Image plugin for Encapsulated PostScript. This plugin supports only
|
| 180 |
+
# a few variants of this format.
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class EpsImageFile(ImageFile.ImageFile):
|
| 184 |
+
"""EPS File Parser for the Python Imaging Library"""
|
| 185 |
+
|
| 186 |
+
format = "EPS"
|
| 187 |
+
format_description = "Encapsulated Postscript"
|
| 188 |
+
|
| 189 |
+
mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
|
| 190 |
+
|
| 191 |
+
def _open(self) -> None:
|
| 192 |
+
(length, offset) = self._find_offset(self.fp)
|
| 193 |
+
|
| 194 |
+
# go to offset - start of "%!PS"
|
| 195 |
+
self.fp.seek(offset)
|
| 196 |
+
|
| 197 |
+
self._mode = "RGB"
|
| 198 |
+
|
| 199 |
+
# When reading header comments, the first comment is used.
|
| 200 |
+
# When reading trailer comments, the last comment is used.
|
| 201 |
+
bounding_box: list[int] | None = None
|
| 202 |
+
imagedata_size: tuple[int, int] | None = None
|
| 203 |
+
|
| 204 |
+
byte_arr = bytearray(255)
|
| 205 |
+
bytes_mv = memoryview(byte_arr)
|
| 206 |
+
bytes_read = 0
|
| 207 |
+
reading_header_comments = True
|
| 208 |
+
reading_trailer_comments = False
|
| 209 |
+
trailer_reached = False
|
| 210 |
+
|
| 211 |
+
def check_required_header_comments() -> None:
|
| 212 |
+
"""
|
| 213 |
+
The EPS specification requires that some headers exist.
|
| 214 |
+
This should be checked when the header comments formally end,
|
| 215 |
+
when image data starts, or when the file ends, whichever comes first.
|
| 216 |
+
"""
|
| 217 |
+
if "PS-Adobe" not in self.info:
|
| 218 |
+
msg = 'EPS header missing "%!PS-Adobe" comment'
|
| 219 |
+
raise SyntaxError(msg)
|
| 220 |
+
if "BoundingBox" not in self.info:
|
| 221 |
+
msg = 'EPS header missing "%%BoundingBox" comment'
|
| 222 |
+
raise SyntaxError(msg)
|
| 223 |
+
|
| 224 |
+
def read_comment(s: str) -> bool:
|
| 225 |
+
nonlocal bounding_box, reading_trailer_comments
|
| 226 |
+
try:
|
| 227 |
+
m = split.match(s)
|
| 228 |
+
except re.error as e:
|
| 229 |
+
msg = "not an EPS file"
|
| 230 |
+
raise SyntaxError(msg) from e
|
| 231 |
+
|
| 232 |
+
if not m:
|
| 233 |
+
return False
|
| 234 |
+
|
| 235 |
+
k, v = m.group(1, 2)
|
| 236 |
+
self.info[k] = v
|
| 237 |
+
if k == "BoundingBox":
|
| 238 |
+
if v == "(atend)":
|
| 239 |
+
reading_trailer_comments = True
|
| 240 |
+
elif not bounding_box or (trailer_reached and reading_trailer_comments):
|
| 241 |
+
try:
|
| 242 |
+
# Note: The DSC spec says that BoundingBox
|
| 243 |
+
# fields should be integers, but some drivers
|
| 244 |
+
# put floating point values there anyway.
|
| 245 |
+
bounding_box = [int(float(i)) for i in v.split()]
|
| 246 |
+
except Exception:
|
| 247 |
+
pass
|
| 248 |
+
return True
|
| 249 |
+
|
| 250 |
+
while True:
|
| 251 |
+
byte = self.fp.read(1)
|
| 252 |
+
if byte == b"":
|
| 253 |
+
# if we didn't read a byte we must be at the end of the file
|
| 254 |
+
if bytes_read == 0:
|
| 255 |
+
if reading_header_comments:
|
| 256 |
+
check_required_header_comments()
|
| 257 |
+
break
|
| 258 |
+
elif byte in b"\r\n":
|
| 259 |
+
# if we read a line ending character, ignore it and parse what
|
| 260 |
+
# we have already read. if we haven't read any other characters,
|
| 261 |
+
# continue reading
|
| 262 |
+
if bytes_read == 0:
|
| 263 |
+
continue
|
| 264 |
+
else:
|
| 265 |
+
# ASCII/hexadecimal lines in an EPS file must not exceed
|
| 266 |
+
# 255 characters, not including line ending characters
|
| 267 |
+
if bytes_read >= 255:
|
| 268 |
+
# only enforce this for lines starting with a "%",
|
| 269 |
+
# otherwise assume it's binary data
|
| 270 |
+
if byte_arr[0] == ord("%"):
|
| 271 |
+
msg = "not an EPS file"
|
| 272 |
+
raise SyntaxError(msg)
|
| 273 |
+
else:
|
| 274 |
+
if reading_header_comments:
|
| 275 |
+
check_required_header_comments()
|
| 276 |
+
reading_header_comments = False
|
| 277 |
+
# reset bytes_read so we can keep reading
|
| 278 |
+
# data until the end of the line
|
| 279 |
+
bytes_read = 0
|
| 280 |
+
byte_arr[bytes_read] = byte[0]
|
| 281 |
+
bytes_read += 1
|
| 282 |
+
continue
|
| 283 |
+
|
| 284 |
+
if reading_header_comments:
|
| 285 |
+
# Load EPS header
|
| 286 |
+
|
| 287 |
+
# if this line doesn't start with a "%",
|
| 288 |
+
# or does start with "%%EndComments",
|
| 289 |
+
# then we've reached the end of the header/comments
|
| 290 |
+
if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
|
| 291 |
+
check_required_header_comments()
|
| 292 |
+
reading_header_comments = False
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
s = str(bytes_mv[:bytes_read], "latin-1")
|
| 296 |
+
if not read_comment(s):
|
| 297 |
+
m = field.match(s)
|
| 298 |
+
if m:
|
| 299 |
+
k = m.group(1)
|
| 300 |
+
if k.startswith("PS-Adobe"):
|
| 301 |
+
self.info["PS-Adobe"] = k[9:]
|
| 302 |
+
else:
|
| 303 |
+
self.info[k] = ""
|
| 304 |
+
elif s[0] == "%":
|
| 305 |
+
# handle non-DSC PostScript comments that some
|
| 306 |
+
# tools mistakenly put in the Comments section
|
| 307 |
+
pass
|
| 308 |
+
else:
|
| 309 |
+
msg = "bad EPS header"
|
| 310 |
+
raise OSError(msg)
|
| 311 |
+
elif bytes_mv[:11] == b"%ImageData:":
|
| 312 |
+
# Check for an "ImageData" descriptor
|
| 313 |
+
# https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
|
| 314 |
+
|
| 315 |
+
# If we've already read an "ImageData" descriptor,
|
| 316 |
+
# don't read another one.
|
| 317 |
+
if imagedata_size:
|
| 318 |
+
bytes_read = 0
|
| 319 |
+
continue
|
| 320 |
+
|
| 321 |
+
# Values:
|
| 322 |
+
# columns
|
| 323 |
+
# rows
|
| 324 |
+
# bit depth (1 or 8)
|
| 325 |
+
# mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
|
| 326 |
+
# number of padding channels
|
| 327 |
+
# block size (number of bytes per row per channel)
|
| 328 |
+
# binary/ascii (1: binary, 2: ascii)
|
| 329 |
+
# data start identifier (the image data follows after a single line
|
| 330 |
+
# consisting only of this quoted value)
|
| 331 |
+
image_data_values = byte_arr[11:bytes_read].split(None, 7)
|
| 332 |
+
columns, rows, bit_depth, mode_id = (
|
| 333 |
+
int(value) for value in image_data_values[:4]
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
if bit_depth == 1:
|
| 337 |
+
self._mode = "1"
|
| 338 |
+
elif bit_depth == 8:
|
| 339 |
+
try:
|
| 340 |
+
self._mode = self.mode_map[mode_id]
|
| 341 |
+
except ValueError:
|
| 342 |
+
break
|
| 343 |
+
else:
|
| 344 |
+
break
|
| 345 |
+
|
| 346 |
+
# Parse the columns and rows after checking the bit depth and mode
|
| 347 |
+
# in case the bit depth and/or mode are invalid.
|
| 348 |
+
imagedata_size = columns, rows
|
| 349 |
+
elif bytes_mv[:5] == b"%%EOF":
|
| 350 |
+
break
|
| 351 |
+
elif trailer_reached and reading_trailer_comments:
|
| 352 |
+
# Load EPS trailer
|
| 353 |
+
s = str(bytes_mv[:bytes_read], "latin-1")
|
| 354 |
+
read_comment(s)
|
| 355 |
+
elif bytes_mv[:9] == b"%%Trailer":
|
| 356 |
+
trailer_reached = True
|
| 357 |
+
elif bytes_mv[:14] == b"%%BeginBinary:":
|
| 358 |
+
bytecount = int(byte_arr[14:bytes_read])
|
| 359 |
+
self.fp.seek(bytecount, os.SEEK_CUR)
|
| 360 |
+
bytes_read = 0
|
| 361 |
+
|
| 362 |
+
# A "BoundingBox" is always required,
|
| 363 |
+
# even if an "ImageData" descriptor size exists.
|
| 364 |
+
if not bounding_box:
|
| 365 |
+
msg = "cannot determine EPS bounding box"
|
| 366 |
+
raise OSError(msg)
|
| 367 |
+
|
| 368 |
+
# An "ImageData" size takes precedence over the "BoundingBox".
|
| 369 |
+
self._size = imagedata_size or (
|
| 370 |
+
bounding_box[2] - bounding_box[0],
|
| 371 |
+
bounding_box[3] - bounding_box[1],
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
self.tile = [
|
| 375 |
+
ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box))
|
| 376 |
+
]
|
| 377 |
+
|
| 378 |
+
def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
|
| 379 |
+
s = fp.read(4)
|
| 380 |
+
|
| 381 |
+
if s == b"%!PS":
|
| 382 |
+
# for HEAD without binary preview
|
| 383 |
+
fp.seek(0, io.SEEK_END)
|
| 384 |
+
length = fp.tell()
|
| 385 |
+
offset = 0
|
| 386 |
+
elif i32(s) == 0xC6D3D0C5:
|
| 387 |
+
# FIX for: Some EPS file not handled correctly / issue #302
|
| 388 |
+
# EPS can contain binary data
|
| 389 |
+
# or start directly with latin coding
|
| 390 |
+
# more info see:
|
| 391 |
+
# https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
|
| 392 |
+
s = fp.read(8)
|
| 393 |
+
offset = i32(s)
|
| 394 |
+
length = i32(s, 4)
|
| 395 |
+
else:
|
| 396 |
+
msg = "not an EPS file"
|
| 397 |
+
raise SyntaxError(msg)
|
| 398 |
+
|
| 399 |
+
return length, offset
|
| 400 |
+
|
| 401 |
+
def load(
|
| 402 |
+
self, scale: int = 1, transparency: bool = False
|
| 403 |
+
) -> Image.core.PixelAccess | None:
|
| 404 |
+
# Load EPS via Ghostscript
|
| 405 |
+
if self.tile:
|
| 406 |
+
self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
|
| 407 |
+
self._mode = self.im.mode
|
| 408 |
+
self._size = self.im.size
|
| 409 |
+
self.tile = []
|
| 410 |
+
return Image.Image.load(self)
|
| 411 |
+
|
| 412 |
+
def load_seek(self, pos: int) -> None:
|
| 413 |
+
# we can't incrementally load, so force ImageFile.parser to
|
| 414 |
+
# use our custom load method by defining this method.
|
| 415 |
+
pass
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
# --------------------------------------------------------------------
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
|
| 422 |
+
"""EPS Writer for the Python Imaging Library."""
|
| 423 |
+
|
| 424 |
+
# make sure image data is available
|
| 425 |
+
im.load()
|
| 426 |
+
|
| 427 |
+
# determine PostScript image mode
|
| 428 |
+
if im.mode == "L":
|
| 429 |
+
operator = (8, 1, b"image")
|
| 430 |
+
elif im.mode == "RGB":
|
| 431 |
+
operator = (8, 3, b"false 3 colorimage")
|
| 432 |
+
elif im.mode == "CMYK":
|
| 433 |
+
operator = (8, 4, b"false 4 colorimage")
|
| 434 |
+
else:
|
| 435 |
+
msg = "image mode is not supported"
|
| 436 |
+
raise ValueError(msg)
|
| 437 |
+
|
| 438 |
+
if eps:
|
| 439 |
+
# write EPS header
|
| 440 |
+
fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
|
| 441 |
+
fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
|
| 442 |
+
# fp.write("%%CreationDate: %s"...)
|
| 443 |
+
fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
|
| 444 |
+
fp.write(b"%%Pages: 1\n")
|
| 445 |
+
fp.write(b"%%EndComments\n")
|
| 446 |
+
fp.write(b"%%Page: 1 1\n")
|
| 447 |
+
fp.write(b"%%ImageData: %d %d " % im.size)
|
| 448 |
+
fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
|
| 449 |
+
|
| 450 |
+
# image header
|
| 451 |
+
fp.write(b"gsave\n")
|
| 452 |
+
fp.write(b"10 dict begin\n")
|
| 453 |
+
fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
|
| 454 |
+
fp.write(b"%d %d scale\n" % im.size)
|
| 455 |
+
fp.write(b"%d %d 8\n" % im.size) # <= bits
|
| 456 |
+
fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
|
| 457 |
+
fp.write(b"{ currentfile buf readhexstring pop } bind\n")
|
| 458 |
+
fp.write(operator[2] + b"\n")
|
| 459 |
+
if hasattr(fp, "flush"):
|
| 460 |
+
fp.flush()
|
| 461 |
+
|
| 462 |
+
ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)])
|
| 463 |
+
|
| 464 |
+
fp.write(b"\n%%%%EndBinary\n")
|
| 465 |
+
fp.write(b"grestore end\n")
|
| 466 |
+
if hasattr(fp, "flush"):
|
| 467 |
+
fp.flush()
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# --------------------------------------------------------------------
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
|
| 474 |
+
|
| 475 |
+
Image.register_save(EpsImageFile.format, _save)
|
| 476 |
+
|
| 477 |
+
Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
|
| 478 |
+
|
| 479 |
+
Image.register_mime(EpsImageFile.format, "application/postscript")
|
.venv/lib/python3.12/site-packages/PIL/ExifTags.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 = 0x00
|
| 307 |
+
GPSLatitudeRef = 0x01
|
| 308 |
+
GPSLatitude = 0x02
|
| 309 |
+
GPSLongitudeRef = 0x03
|
| 310 |
+
GPSLongitude = 0x04
|
| 311 |
+
GPSAltitudeRef = 0x05
|
| 312 |
+
GPSAltitude = 0x06
|
| 313 |
+
GPSTimeStamp = 0x07
|
| 314 |
+
GPSSatellites = 0x08
|
| 315 |
+
GPSStatus = 0x09
|
| 316 |
+
GPSMeasureMode = 0x0A
|
| 317 |
+
GPSDOP = 0x0B
|
| 318 |
+
GPSSpeedRef = 0x0C
|
| 319 |
+
GPSSpeed = 0x0D
|
| 320 |
+
GPSTrackRef = 0x0E
|
| 321 |
+
GPSTrack = 0x0F
|
| 322 |
+
GPSImgDirectionRef = 0x10
|
| 323 |
+
GPSImgDirection = 0x11
|
| 324 |
+
GPSMapDatum = 0x12
|
| 325 |
+
GPSDestLatitudeRef = 0x13
|
| 326 |
+
GPSDestLatitude = 0x14
|
| 327 |
+
GPSDestLongitudeRef = 0x15
|
| 328 |
+
GPSDestLongitude = 0x16
|
| 329 |
+
GPSDestBearingRef = 0x17
|
| 330 |
+
GPSDestBearing = 0x18
|
| 331 |
+
GPSDestDistanceRef = 0x19
|
| 332 |
+
GPSDestDistance = 0x1A
|
| 333 |
+
GPSProcessingMethod = 0x1B
|
| 334 |
+
GPSAreaInformation = 0x1C
|
| 335 |
+
GPSDateStamp = 0x1D
|
| 336 |
+
GPSDifferential = 0x1E
|
| 337 |
+
GPSHPositioningError = 0x1F
|
| 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 = 0x0001
|
| 346 |
+
InteropVersion = 0x0002
|
| 347 |
+
RelatedImageFileFormat = 0x1000
|
| 348 |
+
RelatedImageWidth = 0x1001
|
| 349 |
+
RelatedImageHeight = 0x1002
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class IFD(IntEnum):
|
| 353 |
+
Exif = 0x8769
|
| 354 |
+
GPSInfo = 0x8825
|
| 355 |
+
MakerNote = 0x927C
|
| 356 |
+
Makernote = 0x927C # Deprecated
|
| 357 |
+
Interop = 0xA005
|
| 358 |
+
IFD1 = -1
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class LightSource(IntEnum):
|
| 362 |
+
Unknown = 0x00
|
| 363 |
+
Daylight = 0x01
|
| 364 |
+
Fluorescent = 0x02
|
| 365 |
+
Tungsten = 0x03
|
| 366 |
+
Flash = 0x04
|
| 367 |
+
Fine = 0x09
|
| 368 |
+
Cloudy = 0x0A
|
| 369 |
+
Shade = 0x0B
|
| 370 |
+
DaylightFluorescent = 0x0C
|
| 371 |
+
DayWhiteFluorescent = 0x0D
|
| 372 |
+
CoolWhiteFluorescent = 0x0E
|
| 373 |
+
WhiteFluorescent = 0x0F
|
| 374 |
+
StandardLightA = 0x11
|
| 375 |
+
StandardLightB = 0x12
|
| 376 |
+
StandardLightC = 0x13
|
| 377 |
+
D55 = 0x14
|
| 378 |
+
D65 = 0x15
|
| 379 |
+
D75 = 0x16
|
| 380 |
+
D50 = 0x17
|
| 381 |
+
ISO = 0x18
|
| 382 |
+
Other = 0xFF
|
.venv/lib/python3.12/site-packages/PIL/FitsImagePlugin.py
ADDED
|
@@ -0,0 +1,152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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.startswith(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 = [ImageFile._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 | Image.SupportsArrayInterface) -> 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 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from ._util import DeferredError
|
| 26 |
+
|
| 27 |
+
#
|
| 28 |
+
# decoder
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _accept(prefix: bytes) -> bool:
|
| 32 |
+
return (
|
| 33 |
+
len(prefix) >= 16
|
| 34 |
+
and i16(prefix, 4) in [0xAF11, 0xAF12]
|
| 35 |
+
and i16(prefix, 14) in [0, 3] # flags
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
##
|
| 40 |
+
# Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
|
| 41 |
+
# method to load individual frames.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class FliImageFile(ImageFile.ImageFile):
|
| 45 |
+
format = "FLI"
|
| 46 |
+
format_description = "Autodesk FLI/FLC Animation"
|
| 47 |
+
_close_exclusive_fp_after_loading = False
|
| 48 |
+
|
| 49 |
+
def _open(self) -> None:
|
| 50 |
+
# HEAD
|
| 51 |
+
assert self.fp is not None
|
| 52 |
+
s = self.fp.read(128)
|
| 53 |
+
if not (
|
| 54 |
+
_accept(s)
|
| 55 |
+
and s[20:22] == b"\x00" * 2
|
| 56 |
+
and s[42:80] == b"\x00" * 38
|
| 57 |
+
and s[88:] == b"\x00" * 40
|
| 58 |
+
):
|
| 59 |
+
msg = "not an FLI/FLC file"
|
| 60 |
+
raise SyntaxError(msg)
|
| 61 |
+
|
| 62 |
+
# frames
|
| 63 |
+
self.n_frames = i16(s, 6)
|
| 64 |
+
self.is_animated = self.n_frames > 1
|
| 65 |
+
|
| 66 |
+
# image characteristics
|
| 67 |
+
self._mode = "P"
|
| 68 |
+
self._size = i16(s, 8), i16(s, 10)
|
| 69 |
+
|
| 70 |
+
# animation speed
|
| 71 |
+
duration = i32(s, 16)
|
| 72 |
+
magic = i16(s, 4)
|
| 73 |
+
if magic == 0xAF11:
|
| 74 |
+
duration = (duration * 1000) // 70
|
| 75 |
+
self.info["duration"] = duration
|
| 76 |
+
|
| 77 |
+
# look for palette
|
| 78 |
+
palette = [(a, a, a) for a in range(256)]
|
| 79 |
+
|
| 80 |
+
s = self.fp.read(16)
|
| 81 |
+
|
| 82 |
+
self.__offset = 128
|
| 83 |
+
|
| 84 |
+
if i16(s, 4) == 0xF100:
|
| 85 |
+
# prefix chunk; ignore it
|
| 86 |
+
self.fp.seek(self.__offset + i32(s))
|
| 87 |
+
s = self.fp.read(16)
|
| 88 |
+
|
| 89 |
+
if i16(s, 4) == 0xF1FA:
|
| 90 |
+
# look for palette chunk
|
| 91 |
+
number_of_subchunks = i16(s, 6)
|
| 92 |
+
chunk_size: int | None = None
|
| 93 |
+
for _ in range(number_of_subchunks):
|
| 94 |
+
if chunk_size is not None:
|
| 95 |
+
self.fp.seek(chunk_size - 6, os.SEEK_CUR)
|
| 96 |
+
s = self.fp.read(6)
|
| 97 |
+
chunk_type = i16(s, 4)
|
| 98 |
+
if chunk_type in (4, 11):
|
| 99 |
+
self._palette(palette, 2 if chunk_type == 11 else 0)
|
| 100 |
+
break
|
| 101 |
+
chunk_size = i32(s)
|
| 102 |
+
if not chunk_size:
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
self.palette = ImagePalette.raw(
|
| 106 |
+
"RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette)
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# set things up to decode first frame
|
| 110 |
+
self.__frame = -1
|
| 111 |
+
self._fp = self.fp
|
| 112 |
+
self.__rewind = self.fp.tell()
|
| 113 |
+
self.seek(0)
|
| 114 |
+
|
| 115 |
+
def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None:
|
| 116 |
+
# load palette
|
| 117 |
+
|
| 118 |
+
i = 0
|
| 119 |
+
assert self.fp is not None
|
| 120 |
+
for e in range(i16(self.fp.read(2))):
|
| 121 |
+
s = self.fp.read(2)
|
| 122 |
+
i = i + s[0]
|
| 123 |
+
n = s[1]
|
| 124 |
+
if n == 0:
|
| 125 |
+
n = 256
|
| 126 |
+
s = self.fp.read(n * 3)
|
| 127 |
+
for n in range(0, len(s), 3):
|
| 128 |
+
r = s[n] << shift
|
| 129 |
+
g = s[n + 1] << shift
|
| 130 |
+
b = s[n + 2] << shift
|
| 131 |
+
palette[i] = (r, g, b)
|
| 132 |
+
i += 1
|
| 133 |
+
|
| 134 |
+
def seek(self, frame: int) -> None:
|
| 135 |
+
if not self._seek_check(frame):
|
| 136 |
+
return
|
| 137 |
+
if frame < self.__frame:
|
| 138 |
+
self._seek(0)
|
| 139 |
+
|
| 140 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 141 |
+
self._seek(f)
|
| 142 |
+
|
| 143 |
+
def _seek(self, frame: int) -> None:
|
| 144 |
+
if isinstance(self._fp, DeferredError):
|
| 145 |
+
raise self._fp.ex
|
| 146 |
+
if frame == 0:
|
| 147 |
+
self.__frame = -1
|
| 148 |
+
self._fp.seek(self.__rewind)
|
| 149 |
+
self.__offset = 128
|
| 150 |
+
else:
|
| 151 |
+
# ensure that the previous frame was loaded
|
| 152 |
+
self.load()
|
| 153 |
+
|
| 154 |
+
if frame != self.__frame + 1:
|
| 155 |
+
msg = f"cannot seek to frame {frame}"
|
| 156 |
+
raise ValueError(msg)
|
| 157 |
+
self.__frame = frame
|
| 158 |
+
|
| 159 |
+
# move to next frame
|
| 160 |
+
self.fp = self._fp
|
| 161 |
+
self.fp.seek(self.__offset)
|
| 162 |
+
|
| 163 |
+
s = self.fp.read(4)
|
| 164 |
+
if not s:
|
| 165 |
+
msg = "missing frame size"
|
| 166 |
+
raise EOFError(msg)
|
| 167 |
+
|
| 168 |
+
framesize = i32(s)
|
| 169 |
+
|
| 170 |
+
self.decodermaxblock = framesize
|
| 171 |
+
self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)]
|
| 172 |
+
|
| 173 |
+
self.__offset += framesize
|
| 174 |
+
|
| 175 |
+
def tell(self) -> int:
|
| 176 |
+
return self.__frame
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
#
|
| 180 |
+
# registry
|
| 181 |
+
|
| 182 |
+
Image.register_open(FliImageFile.format, FliImageFile, _accept)
|
| 183 |
+
|
| 184 |
+
Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
|
.venv/lib/python3.12/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[id]
|
| 131 |
+
if not m:
|
| 132 |
+
puti16(fp, (0,) * 10)
|
| 133 |
+
else:
|
| 134 |
+
puti16(fp, m[0] + m[1] + m[2])
|
.venv/lib/python3.12/site-packages/PIL/FpxImagePlugin.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.startswith(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) -> None:
|
| 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 |
+
root = self.ole.root
|
| 68 |
+
if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
|
| 69 |
+
msg = "not an FPX file; bad root CLSID"
|
| 70 |
+
raise SyntaxError(msg)
|
| 71 |
+
|
| 72 |
+
self._open_index(1)
|
| 73 |
+
|
| 74 |
+
def _open_index(self, index: int = 1) -> None:
|
| 75 |
+
#
|
| 76 |
+
# get the Image Contents Property Set
|
| 77 |
+
|
| 78 |
+
prop = self.ole.getproperties(
|
| 79 |
+
[f"Data Object Store {index:06d}", "\005Image Contents"]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# size (highest resolution)
|
| 83 |
+
|
| 84 |
+
assert isinstance(prop[0x1000002], int)
|
| 85 |
+
assert isinstance(prop[0x1000003], int)
|
| 86 |
+
self._size = prop[0x1000002], prop[0x1000003]
|
| 87 |
+
|
| 88 |
+
size = max(self.size)
|
| 89 |
+
i = 1
|
| 90 |
+
while size > 64:
|
| 91 |
+
size = size // 2
|
| 92 |
+
i += 1
|
| 93 |
+
self.maxid = i - 1
|
| 94 |
+
|
| 95 |
+
# mode. instead of using a single field for this, flashpix
|
| 96 |
+
# requires you to specify the mode for each channel in each
|
| 97 |
+
# resolution subimage, and leaves it to the decoder to make
|
| 98 |
+
# sure that they all match. for now, we'll cheat and assume
|
| 99 |
+
# that this is always the case.
|
| 100 |
+
|
| 101 |
+
id = self.maxid << 16
|
| 102 |
+
|
| 103 |
+
s = prop[0x2000002 | id]
|
| 104 |
+
|
| 105 |
+
if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4:
|
| 106 |
+
msg = "Invalid number of bands"
|
| 107 |
+
raise OSError(msg)
|
| 108 |
+
|
| 109 |
+
# note: for now, we ignore the "uncalibrated" flag
|
| 110 |
+
colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
|
| 111 |
+
|
| 112 |
+
self._mode, self.rawmode = MODES[colors]
|
| 113 |
+
|
| 114 |
+
# load JPEG tables, if any
|
| 115 |
+
self.jpeg = {}
|
| 116 |
+
for i in range(256):
|
| 117 |
+
id = 0x3000001 | (i << 16)
|
| 118 |
+
if id in prop:
|
| 119 |
+
self.jpeg[i] = prop[id]
|
| 120 |
+
|
| 121 |
+
self._open_subimage(1, self.maxid)
|
| 122 |
+
|
| 123 |
+
def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
|
| 124 |
+
#
|
| 125 |
+
# setup tile descriptors for a given subimage
|
| 126 |
+
|
| 127 |
+
stream = [
|
| 128 |
+
f"Data Object Store {index:06d}",
|
| 129 |
+
f"Resolution {subimage:04d}",
|
| 130 |
+
"Subimage 0000 Header",
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
fp = self.ole.openstream(stream)
|
| 134 |
+
|
| 135 |
+
# skip prefix
|
| 136 |
+
fp.read(28)
|
| 137 |
+
|
| 138 |
+
# header stream
|
| 139 |
+
s = fp.read(36)
|
| 140 |
+
|
| 141 |
+
size = i32(s, 4), i32(s, 8)
|
| 142 |
+
# tilecount = i32(s, 12)
|
| 143 |
+
tilesize = i32(s, 16), i32(s, 20)
|
| 144 |
+
# channels = i32(s, 24)
|
| 145 |
+
offset = i32(s, 28)
|
| 146 |
+
length = i32(s, 32)
|
| 147 |
+
|
| 148 |
+
if size != self.size:
|
| 149 |
+
msg = "subimage mismatch"
|
| 150 |
+
raise OSError(msg)
|
| 151 |
+
|
| 152 |
+
# get tile descriptors
|
| 153 |
+
fp.seek(28 + offset)
|
| 154 |
+
s = fp.read(i32(s, 12) * length)
|
| 155 |
+
|
| 156 |
+
x = y = 0
|
| 157 |
+
xsize, ysize = size
|
| 158 |
+
xtile, ytile = tilesize
|
| 159 |
+
self.tile = []
|
| 160 |
+
|
| 161 |
+
for i in range(0, len(s), length):
|
| 162 |
+
x1 = min(xsize, x + xtile)
|
| 163 |
+
y1 = min(ysize, y + ytile)
|
| 164 |
+
|
| 165 |
+
compression = i32(s, i + 8)
|
| 166 |
+
|
| 167 |
+
if compression == 0:
|
| 168 |
+
self.tile.append(
|
| 169 |
+
ImageFile._Tile(
|
| 170 |
+
"raw",
|
| 171 |
+
(x, y, x1, y1),
|
| 172 |
+
i32(s, i) + 28,
|
| 173 |
+
self.rawmode,
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
elif compression == 1:
|
| 178 |
+
# FIXME: the fill decoder is not implemented
|
| 179 |
+
self.tile.append(
|
| 180 |
+
ImageFile._Tile(
|
| 181 |
+
"fill",
|
| 182 |
+
(x, y, x1, y1),
|
| 183 |
+
i32(s, i) + 28,
|
| 184 |
+
(self.rawmode, s[12:16]),
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
elif compression == 2:
|
| 189 |
+
internal_color_conversion = s[14]
|
| 190 |
+
jpeg_tables = s[15]
|
| 191 |
+
rawmode = self.rawmode
|
| 192 |
+
|
| 193 |
+
if internal_color_conversion:
|
| 194 |
+
# The image is stored as usual (usually YCbCr).
|
| 195 |
+
if rawmode == "RGBA":
|
| 196 |
+
# For "RGBA", data is stored as YCbCrA based on
|
| 197 |
+
# negative RGB. The following trick works around
|
| 198 |
+
# this problem :
|
| 199 |
+
jpegmode, rawmode = "YCbCrK", "CMYK"
|
| 200 |
+
else:
|
| 201 |
+
jpegmode = None # let the decoder decide
|
| 202 |
+
|
| 203 |
+
else:
|
| 204 |
+
# The image is stored as defined by rawmode
|
| 205 |
+
jpegmode = rawmode
|
| 206 |
+
|
| 207 |
+
self.tile.append(
|
| 208 |
+
ImageFile._Tile(
|
| 209 |
+
"jpeg",
|
| 210 |
+
(x, y, x1, y1),
|
| 211 |
+
i32(s, i) + 28,
|
| 212 |
+
(rawmode, jpegmode),
|
| 213 |
+
)
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# FIXME: jpeg tables are tile dependent; the prefix
|
| 217 |
+
# data must be placed in the tile descriptor itself!
|
| 218 |
+
|
| 219 |
+
if jpeg_tables:
|
| 220 |
+
self.tile_prefix = self.jpeg[jpeg_tables]
|
| 221 |
+
|
| 222 |
+
else:
|
| 223 |
+
msg = "unknown/invalid compression"
|
| 224 |
+
raise OSError(msg)
|
| 225 |
+
|
| 226 |
+
x = x + xtile
|
| 227 |
+
if x >= xsize:
|
| 228 |
+
x, y = 0, y + ytile
|
| 229 |
+
if y >= ysize:
|
| 230 |
+
break # isn't really required
|
| 231 |
+
|
| 232 |
+
self.stream = stream
|
| 233 |
+
self._fp = self.fp
|
| 234 |
+
self.fp = None
|
| 235 |
+
|
| 236 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 237 |
+
if not self.fp:
|
| 238 |
+
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
|
| 239 |
+
|
| 240 |
+
return ImageFile.ImageFile.load(self)
|
| 241 |
+
|
| 242 |
+
def close(self) -> None:
|
| 243 |
+
self.ole.close()
|
| 244 |
+
super().close()
|
| 245 |
+
|
| 246 |
+
def __exit__(self, *args: object) -> None:
|
| 247 |
+
self.ole.close()
|
| 248 |
+
super().__exit__()
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
#
|
| 252 |
+
# --------------------------------------------------------------------
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
|
| 256 |
+
|
| 257 |
+
Image.register_extension(FpxImageFile.format, ".fpx")
|
.venv/lib/python3.12/site-packages/PIL/GbrImagePlugin.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
self.info["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 |
+
# Image might not be small
|
| 84 |
+
Image._decompression_bomb_check(self.size)
|
| 85 |
+
|
| 86 |
+
# Data is an uncompressed block of w * h * bytes/pixel
|
| 87 |
+
self._data_size = width * height * color_depth
|
| 88 |
+
|
| 89 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 90 |
+
if self._im is None:
|
| 91 |
+
self.im = Image.core.new(self.mode, self.size)
|
| 92 |
+
self.frombytes(self.fp.read(self._data_size))
|
| 93 |
+
return Image.Image.load(self)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
#
|
| 97 |
+
# registry
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
|
| 101 |
+
Image.register_extension(GbrImageFile.format, ".gbr")
|
.venv/lib/python3.12/site-packages/PIL/GifImagePlugin.py
ADDED
|
@@ -0,0 +1,1215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
from enum import IntEnum
|
| 33 |
+
from functools import cached_property
|
| 34 |
+
from typing import Any, NamedTuple, cast
|
| 35 |
+
|
| 36 |
+
from . import (
|
| 37 |
+
Image,
|
| 38 |
+
ImageChops,
|
| 39 |
+
ImageFile,
|
| 40 |
+
ImageMath,
|
| 41 |
+
ImageOps,
|
| 42 |
+
ImagePalette,
|
| 43 |
+
ImageSequence,
|
| 44 |
+
)
|
| 45 |
+
from ._binary import i16le as i16
|
| 46 |
+
from ._binary import o8
|
| 47 |
+
from ._binary import o16le as o16
|
| 48 |
+
from ._util import DeferredError
|
| 49 |
+
|
| 50 |
+
TYPE_CHECKING = False
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
from typing import IO, Literal
|
| 53 |
+
|
| 54 |
+
from . import _imaging
|
| 55 |
+
from ._typing import Buffer
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class LoadingStrategy(IntEnum):
|
| 59 |
+
""".. versionadded:: 9.1.0"""
|
| 60 |
+
|
| 61 |
+
RGB_AFTER_FIRST = 0
|
| 62 |
+
RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
|
| 63 |
+
RGB_ALWAYS = 2
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
#: .. versionadded:: 9.1.0
|
| 67 |
+
LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
|
| 68 |
+
|
| 69 |
+
# --------------------------------------------------------------------
|
| 70 |
+
# Identify/read GIF files
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _accept(prefix: bytes) -> bool:
|
| 74 |
+
return prefix.startswith((b"GIF87a", b"GIF89a"))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
##
|
| 78 |
+
# Image plugin for GIF images. This plugin supports both GIF87 and
|
| 79 |
+
# GIF89 images.
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class GifImageFile(ImageFile.ImageFile):
|
| 83 |
+
format = "GIF"
|
| 84 |
+
format_description = "Compuserve GIF"
|
| 85 |
+
_close_exclusive_fp_after_loading = False
|
| 86 |
+
|
| 87 |
+
global_palette = None
|
| 88 |
+
|
| 89 |
+
def data(self) -> bytes | None:
|
| 90 |
+
s = self.fp.read(1)
|
| 91 |
+
if s and s[0]:
|
| 92 |
+
return self.fp.read(s[0])
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
def _is_palette_needed(self, p: bytes) -> bool:
|
| 96 |
+
for i in range(0, len(p), 3):
|
| 97 |
+
if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
|
| 98 |
+
return True
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
def _open(self) -> None:
|
| 102 |
+
# Screen
|
| 103 |
+
s = self.fp.read(13)
|
| 104 |
+
if not _accept(s):
|
| 105 |
+
msg = "not a GIF file"
|
| 106 |
+
raise SyntaxError(msg)
|
| 107 |
+
|
| 108 |
+
self.info["version"] = s[:6]
|
| 109 |
+
self._size = i16(s, 6), i16(s, 8)
|
| 110 |
+
flags = s[10]
|
| 111 |
+
bits = (flags & 7) + 1
|
| 112 |
+
|
| 113 |
+
if flags & 128:
|
| 114 |
+
# get global palette
|
| 115 |
+
self.info["background"] = s[11]
|
| 116 |
+
# check if palette contains colour indices
|
| 117 |
+
p = self.fp.read(3 << bits)
|
| 118 |
+
if self._is_palette_needed(p):
|
| 119 |
+
p = ImagePalette.raw("RGB", p)
|
| 120 |
+
self.global_palette = self.palette = p
|
| 121 |
+
|
| 122 |
+
self._fp = self.fp # FIXME: hack
|
| 123 |
+
self.__rewind = self.fp.tell()
|
| 124 |
+
self._n_frames: int | None = None
|
| 125 |
+
self._seek(0) # get ready to read first frame
|
| 126 |
+
|
| 127 |
+
@property
|
| 128 |
+
def n_frames(self) -> int:
|
| 129 |
+
if self._n_frames is None:
|
| 130 |
+
current = self.tell()
|
| 131 |
+
try:
|
| 132 |
+
while True:
|
| 133 |
+
self._seek(self.tell() + 1, False)
|
| 134 |
+
except EOFError:
|
| 135 |
+
self._n_frames = self.tell() + 1
|
| 136 |
+
self.seek(current)
|
| 137 |
+
return self._n_frames
|
| 138 |
+
|
| 139 |
+
@cached_property
|
| 140 |
+
def is_animated(self) -> bool:
|
| 141 |
+
if self._n_frames is not None:
|
| 142 |
+
return self._n_frames != 1
|
| 143 |
+
|
| 144 |
+
current = self.tell()
|
| 145 |
+
if current:
|
| 146 |
+
return True
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
self._seek(1, False)
|
| 150 |
+
is_animated = True
|
| 151 |
+
except EOFError:
|
| 152 |
+
is_animated = False
|
| 153 |
+
|
| 154 |
+
self.seek(current)
|
| 155 |
+
return is_animated
|
| 156 |
+
|
| 157 |
+
def seek(self, frame: int) -> None:
|
| 158 |
+
if not self._seek_check(frame):
|
| 159 |
+
return
|
| 160 |
+
if frame < self.__frame:
|
| 161 |
+
self._im = None
|
| 162 |
+
self._seek(0)
|
| 163 |
+
|
| 164 |
+
last_frame = self.__frame
|
| 165 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 166 |
+
try:
|
| 167 |
+
self._seek(f)
|
| 168 |
+
except EOFError as e:
|
| 169 |
+
self.seek(last_frame)
|
| 170 |
+
msg = "no more images in GIF file"
|
| 171 |
+
raise EOFError(msg) from e
|
| 172 |
+
|
| 173 |
+
def _seek(self, frame: int, update_image: bool = True) -> None:
|
| 174 |
+
if isinstance(self._fp, DeferredError):
|
| 175 |
+
raise self._fp.ex
|
| 176 |
+
if frame == 0:
|
| 177 |
+
# rewind
|
| 178 |
+
self.__offset = 0
|
| 179 |
+
self.dispose: _imaging.ImagingCore | None = None
|
| 180 |
+
self.__frame = -1
|
| 181 |
+
self._fp.seek(self.__rewind)
|
| 182 |
+
self.disposal_method = 0
|
| 183 |
+
if "comment" in self.info:
|
| 184 |
+
del self.info["comment"]
|
| 185 |
+
else:
|
| 186 |
+
# ensure that the previous frame was loaded
|
| 187 |
+
if self.tile and update_image:
|
| 188 |
+
self.load()
|
| 189 |
+
|
| 190 |
+
if frame != self.__frame + 1:
|
| 191 |
+
msg = f"cannot seek to frame {frame}"
|
| 192 |
+
raise ValueError(msg)
|
| 193 |
+
|
| 194 |
+
self.fp = self._fp
|
| 195 |
+
if self.__offset:
|
| 196 |
+
# backup to last frame
|
| 197 |
+
self.fp.seek(self.__offset)
|
| 198 |
+
while self.data():
|
| 199 |
+
pass
|
| 200 |
+
self.__offset = 0
|
| 201 |
+
|
| 202 |
+
s = self.fp.read(1)
|
| 203 |
+
if not s or s == b";":
|
| 204 |
+
msg = "no more images in GIF file"
|
| 205 |
+
raise EOFError(msg)
|
| 206 |
+
|
| 207 |
+
palette: ImagePalette.ImagePalette | Literal[False] | None = None
|
| 208 |
+
|
| 209 |
+
info: dict[str, Any] = {}
|
| 210 |
+
frame_transparency = None
|
| 211 |
+
interlace = None
|
| 212 |
+
frame_dispose_extent = None
|
| 213 |
+
while True:
|
| 214 |
+
if not s:
|
| 215 |
+
s = self.fp.read(1)
|
| 216 |
+
if not s or s == b";":
|
| 217 |
+
break
|
| 218 |
+
|
| 219 |
+
elif s == b"!":
|
| 220 |
+
#
|
| 221 |
+
# extensions
|
| 222 |
+
#
|
| 223 |
+
s = self.fp.read(1)
|
| 224 |
+
block = self.data()
|
| 225 |
+
if s[0] == 249 and block is not None:
|
| 226 |
+
#
|
| 227 |
+
# graphic control extension
|
| 228 |
+
#
|
| 229 |
+
flags = block[0]
|
| 230 |
+
if flags & 1:
|
| 231 |
+
frame_transparency = block[3]
|
| 232 |
+
info["duration"] = i16(block, 1) * 10
|
| 233 |
+
|
| 234 |
+
# disposal method - find the value of bits 4 - 6
|
| 235 |
+
dispose_bits = 0b00011100 & flags
|
| 236 |
+
dispose_bits = dispose_bits >> 2
|
| 237 |
+
if dispose_bits:
|
| 238 |
+
# only set the dispose if it is not
|
| 239 |
+
# unspecified. I'm not sure if this is
|
| 240 |
+
# correct, but it seems to prevent the last
|
| 241 |
+
# frame from looking odd for some animations
|
| 242 |
+
self.disposal_method = dispose_bits
|
| 243 |
+
elif s[0] == 254:
|
| 244 |
+
#
|
| 245 |
+
# comment extension
|
| 246 |
+
#
|
| 247 |
+
comment = b""
|
| 248 |
+
|
| 249 |
+
# Read this comment block
|
| 250 |
+
while block:
|
| 251 |
+
comment += block
|
| 252 |
+
block = self.data()
|
| 253 |
+
|
| 254 |
+
if "comment" in info:
|
| 255 |
+
# If multiple comment blocks in frame, separate with \n
|
| 256 |
+
info["comment"] += b"\n" + comment
|
| 257 |
+
else:
|
| 258 |
+
info["comment"] = comment
|
| 259 |
+
s = None
|
| 260 |
+
continue
|
| 261 |
+
elif s[0] == 255 and frame == 0 and block is not None:
|
| 262 |
+
#
|
| 263 |
+
# application extension
|
| 264 |
+
#
|
| 265 |
+
info["extension"] = block, self.fp.tell()
|
| 266 |
+
if block.startswith(b"NETSCAPE2.0"):
|
| 267 |
+
block = self.data()
|
| 268 |
+
if block and len(block) >= 3 and block[0] == 1:
|
| 269 |
+
self.info["loop"] = i16(block, 1)
|
| 270 |
+
while self.data():
|
| 271 |
+
pass
|
| 272 |
+
|
| 273 |
+
elif s == b",":
|
| 274 |
+
#
|
| 275 |
+
# local image
|
| 276 |
+
#
|
| 277 |
+
s = self.fp.read(9)
|
| 278 |
+
|
| 279 |
+
# extent
|
| 280 |
+
x0, y0 = i16(s, 0), i16(s, 2)
|
| 281 |
+
x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
|
| 282 |
+
if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
|
| 283 |
+
self._size = max(x1, self.size[0]), max(y1, self.size[1])
|
| 284 |
+
Image._decompression_bomb_check(self._size)
|
| 285 |
+
frame_dispose_extent = x0, y0, x1, y1
|
| 286 |
+
flags = s[8]
|
| 287 |
+
|
| 288 |
+
interlace = (flags & 64) != 0
|
| 289 |
+
|
| 290 |
+
if flags & 128:
|
| 291 |
+
bits = (flags & 7) + 1
|
| 292 |
+
p = self.fp.read(3 << bits)
|
| 293 |
+
if self._is_palette_needed(p):
|
| 294 |
+
palette = ImagePalette.raw("RGB", p)
|
| 295 |
+
else:
|
| 296 |
+
palette = False
|
| 297 |
+
|
| 298 |
+
# image data
|
| 299 |
+
bits = self.fp.read(1)[0]
|
| 300 |
+
self.__offset = self.fp.tell()
|
| 301 |
+
break
|
| 302 |
+
s = None
|
| 303 |
+
|
| 304 |
+
if interlace is None:
|
| 305 |
+
msg = "image not found in GIF frame"
|
| 306 |
+
raise EOFError(msg)
|
| 307 |
+
|
| 308 |
+
self.__frame = frame
|
| 309 |
+
if not update_image:
|
| 310 |
+
return
|
| 311 |
+
|
| 312 |
+
self.tile = []
|
| 313 |
+
|
| 314 |
+
if self.dispose:
|
| 315 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
| 316 |
+
|
| 317 |
+
self._frame_palette = palette if palette is not None else self.global_palette
|
| 318 |
+
self._frame_transparency = frame_transparency
|
| 319 |
+
if frame == 0:
|
| 320 |
+
if self._frame_palette:
|
| 321 |
+
if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
| 322 |
+
self._mode = "RGBA" if frame_transparency is not None else "RGB"
|
| 323 |
+
else:
|
| 324 |
+
self._mode = "P"
|
| 325 |
+
else:
|
| 326 |
+
self._mode = "L"
|
| 327 |
+
|
| 328 |
+
if palette:
|
| 329 |
+
self.palette = palette
|
| 330 |
+
elif self.global_palette:
|
| 331 |
+
from copy import copy
|
| 332 |
+
|
| 333 |
+
self.palette = copy(self.global_palette)
|
| 334 |
+
else:
|
| 335 |
+
self.palette = None
|
| 336 |
+
else:
|
| 337 |
+
if self.mode == "P":
|
| 338 |
+
if (
|
| 339 |
+
LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
|
| 340 |
+
or palette
|
| 341 |
+
):
|
| 342 |
+
if "transparency" in self.info:
|
| 343 |
+
self.im.putpalettealpha(self.info["transparency"], 0)
|
| 344 |
+
self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
|
| 345 |
+
self._mode = "RGBA"
|
| 346 |
+
del self.info["transparency"]
|
| 347 |
+
else:
|
| 348 |
+
self._mode = "RGB"
|
| 349 |
+
self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
|
| 350 |
+
|
| 351 |
+
def _rgb(color: int) -> tuple[int, int, int]:
|
| 352 |
+
if self._frame_palette:
|
| 353 |
+
if color * 3 + 3 > len(self._frame_palette.palette):
|
| 354 |
+
color = 0
|
| 355 |
+
return cast(
|
| 356 |
+
tuple[int, int, int],
|
| 357 |
+
tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]),
|
| 358 |
+
)
|
| 359 |
+
else:
|
| 360 |
+
return (color, color, color)
|
| 361 |
+
|
| 362 |
+
self.dispose = None
|
| 363 |
+
self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent
|
| 364 |
+
if self.dispose_extent and self.disposal_method >= 2:
|
| 365 |
+
try:
|
| 366 |
+
if self.disposal_method == 2:
|
| 367 |
+
# replace with background colour
|
| 368 |
+
|
| 369 |
+
# only dispose the extent in this frame
|
| 370 |
+
x0, y0, x1, y1 = self.dispose_extent
|
| 371 |
+
dispose_size = (x1 - x0, y1 - y0)
|
| 372 |
+
|
| 373 |
+
Image._decompression_bomb_check(dispose_size)
|
| 374 |
+
|
| 375 |
+
# by convention, attempt to use transparency first
|
| 376 |
+
dispose_mode = "P"
|
| 377 |
+
color = self.info.get("transparency", frame_transparency)
|
| 378 |
+
if color is not None:
|
| 379 |
+
if self.mode in ("RGB", "RGBA"):
|
| 380 |
+
dispose_mode = "RGBA"
|
| 381 |
+
color = _rgb(color) + (0,)
|
| 382 |
+
else:
|
| 383 |
+
color = self.info.get("background", 0)
|
| 384 |
+
if self.mode in ("RGB", "RGBA"):
|
| 385 |
+
dispose_mode = "RGB"
|
| 386 |
+
color = _rgb(color)
|
| 387 |
+
self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
|
| 388 |
+
else:
|
| 389 |
+
# replace with previous contents
|
| 390 |
+
if self._im is not None:
|
| 391 |
+
# only dispose the extent in this frame
|
| 392 |
+
self.dispose = self._crop(self.im, self.dispose_extent)
|
| 393 |
+
elif frame_transparency is not None:
|
| 394 |
+
x0, y0, x1, y1 = self.dispose_extent
|
| 395 |
+
dispose_size = (x1 - x0, y1 - y0)
|
| 396 |
+
|
| 397 |
+
Image._decompression_bomb_check(dispose_size)
|
| 398 |
+
dispose_mode = "P"
|
| 399 |
+
color = frame_transparency
|
| 400 |
+
if self.mode in ("RGB", "RGBA"):
|
| 401 |
+
dispose_mode = "RGBA"
|
| 402 |
+
color = _rgb(frame_transparency) + (0,)
|
| 403 |
+
self.dispose = Image.core.fill(
|
| 404 |
+
dispose_mode, dispose_size, color
|
| 405 |
+
)
|
| 406 |
+
except AttributeError:
|
| 407 |
+
pass
|
| 408 |
+
|
| 409 |
+
if interlace is not None:
|
| 410 |
+
transparency = -1
|
| 411 |
+
if frame_transparency is not None:
|
| 412 |
+
if frame == 0:
|
| 413 |
+
if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
|
| 414 |
+
self.info["transparency"] = frame_transparency
|
| 415 |
+
elif self.mode not in ("RGB", "RGBA"):
|
| 416 |
+
transparency = frame_transparency
|
| 417 |
+
self.tile = [
|
| 418 |
+
ImageFile._Tile(
|
| 419 |
+
"gif",
|
| 420 |
+
(x0, y0, x1, y1),
|
| 421 |
+
self.__offset,
|
| 422 |
+
(bits, interlace, transparency),
|
| 423 |
+
)
|
| 424 |
+
]
|
| 425 |
+
|
| 426 |
+
if info.get("comment"):
|
| 427 |
+
self.info["comment"] = info["comment"]
|
| 428 |
+
for k in ["duration", "extension"]:
|
| 429 |
+
if k in info:
|
| 430 |
+
self.info[k] = info[k]
|
| 431 |
+
elif k in self.info:
|
| 432 |
+
del self.info[k]
|
| 433 |
+
|
| 434 |
+
def load_prepare(self) -> None:
|
| 435 |
+
temp_mode = "P" if self._frame_palette else "L"
|
| 436 |
+
self._prev_im = None
|
| 437 |
+
if self.__frame == 0:
|
| 438 |
+
if self._frame_transparency is not None:
|
| 439 |
+
self.im = Image.core.fill(
|
| 440 |
+
temp_mode, self.size, self._frame_transparency
|
| 441 |
+
)
|
| 442 |
+
elif self.mode in ("RGB", "RGBA"):
|
| 443 |
+
self._prev_im = self.im
|
| 444 |
+
if self._frame_palette:
|
| 445 |
+
self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
|
| 446 |
+
self.im.putpalette("RGB", *self._frame_palette.getdata())
|
| 447 |
+
else:
|
| 448 |
+
self._im = None
|
| 449 |
+
if not self._prev_im and self._im is not None and self.size != self.im.size:
|
| 450 |
+
expanded_im = Image.core.fill(self.im.mode, self.size)
|
| 451 |
+
if self._frame_palette:
|
| 452 |
+
expanded_im.putpalette("RGB", *self._frame_palette.getdata())
|
| 453 |
+
expanded_im.paste(self.im, (0, 0) + self.im.size)
|
| 454 |
+
|
| 455 |
+
self.im = expanded_im
|
| 456 |
+
self._mode = temp_mode
|
| 457 |
+
self._frame_palette = None
|
| 458 |
+
|
| 459 |
+
super().load_prepare()
|
| 460 |
+
|
| 461 |
+
def load_end(self) -> None:
|
| 462 |
+
if self.__frame == 0:
|
| 463 |
+
if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
| 464 |
+
if self._frame_transparency is not None:
|
| 465 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
| 466 |
+
self._mode = "RGBA"
|
| 467 |
+
else:
|
| 468 |
+
self._mode = "RGB"
|
| 469 |
+
self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
|
| 470 |
+
return
|
| 471 |
+
if not self._prev_im:
|
| 472 |
+
return
|
| 473 |
+
if self.size != self._prev_im.size:
|
| 474 |
+
if self._frame_transparency is not None:
|
| 475 |
+
expanded_im = Image.core.fill("RGBA", self.size)
|
| 476 |
+
else:
|
| 477 |
+
expanded_im = Image.core.fill("P", self.size)
|
| 478 |
+
expanded_im.putpalette("RGB", "RGB", self.im.getpalette())
|
| 479 |
+
expanded_im = expanded_im.convert("RGB")
|
| 480 |
+
expanded_im.paste(self._prev_im, (0, 0) + self._prev_im.size)
|
| 481 |
+
|
| 482 |
+
self._prev_im = expanded_im
|
| 483 |
+
assert self._prev_im is not None
|
| 484 |
+
if self._frame_transparency is not None:
|
| 485 |
+
if self.mode == "L":
|
| 486 |
+
frame_im = self.im.convert_transparent("LA", self._frame_transparency)
|
| 487 |
+
else:
|
| 488 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
| 489 |
+
frame_im = self.im.convert("RGBA")
|
| 490 |
+
else:
|
| 491 |
+
frame_im = self.im.convert("RGB")
|
| 492 |
+
|
| 493 |
+
assert self.dispose_extent is not None
|
| 494 |
+
frame_im = self._crop(frame_im, self.dispose_extent)
|
| 495 |
+
|
| 496 |
+
self.im = self._prev_im
|
| 497 |
+
self._mode = self.im.mode
|
| 498 |
+
if frame_im.mode in ("LA", "RGBA"):
|
| 499 |
+
self.im.paste(frame_im, self.dispose_extent, frame_im)
|
| 500 |
+
else:
|
| 501 |
+
self.im.paste(frame_im, self.dispose_extent)
|
| 502 |
+
|
| 503 |
+
def tell(self) -> int:
|
| 504 |
+
return self.__frame
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
# --------------------------------------------------------------------
|
| 508 |
+
# Write GIF files
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
RAWMODE = {"1": "L", "L": "L", "P": "P"}
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _normalize_mode(im: Image.Image) -> Image.Image:
|
| 515 |
+
"""
|
| 516 |
+
Takes an image (or frame), returns an image in a mode that is appropriate
|
| 517 |
+
for saving in a Gif.
|
| 518 |
+
|
| 519 |
+
It may return the original image, or it may return an image converted to
|
| 520 |
+
palette or 'L' mode.
|
| 521 |
+
|
| 522 |
+
:param im: Image object
|
| 523 |
+
:returns: Image object
|
| 524 |
+
"""
|
| 525 |
+
if im.mode in RAWMODE:
|
| 526 |
+
im.load()
|
| 527 |
+
return im
|
| 528 |
+
if Image.getmodebase(im.mode) == "RGB":
|
| 529 |
+
im = im.convert("P", palette=Image.Palette.ADAPTIVE)
|
| 530 |
+
assert im.palette is not None
|
| 531 |
+
if im.palette.mode == "RGBA":
|
| 532 |
+
for rgba in im.palette.colors:
|
| 533 |
+
if rgba[3] == 0:
|
| 534 |
+
im.info["transparency"] = im.palette.colors[rgba]
|
| 535 |
+
break
|
| 536 |
+
return im
|
| 537 |
+
return im.convert("L")
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
_Palette = bytes | bytearray | list[int] | ImagePalette.ImagePalette
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def _normalize_palette(
|
| 544 |
+
im: Image.Image, palette: _Palette | None, info: dict[str, Any]
|
| 545 |
+
) -> Image.Image:
|
| 546 |
+
"""
|
| 547 |
+
Normalizes the palette for image.
|
| 548 |
+
- Sets the palette to the incoming palette, if provided.
|
| 549 |
+
- Ensures that there's a palette for L mode images
|
| 550 |
+
- Optimizes the palette if necessary/desired.
|
| 551 |
+
|
| 552 |
+
:param im: Image object
|
| 553 |
+
:param palette: bytes object containing the source palette, or ....
|
| 554 |
+
:param info: encoderinfo
|
| 555 |
+
:returns: Image object
|
| 556 |
+
"""
|
| 557 |
+
source_palette = None
|
| 558 |
+
if palette:
|
| 559 |
+
# a bytes palette
|
| 560 |
+
if isinstance(palette, (bytes, bytearray, list)):
|
| 561 |
+
source_palette = bytearray(palette[:768])
|
| 562 |
+
if isinstance(palette, ImagePalette.ImagePalette):
|
| 563 |
+
source_palette = bytearray(palette.palette)
|
| 564 |
+
|
| 565 |
+
if im.mode == "P":
|
| 566 |
+
if not source_palette:
|
| 567 |
+
im_palette = im.getpalette(None)
|
| 568 |
+
assert im_palette is not None
|
| 569 |
+
source_palette = bytearray(im_palette)
|
| 570 |
+
else: # L-mode
|
| 571 |
+
if not source_palette:
|
| 572 |
+
source_palette = bytearray(i // 3 for i in range(768))
|
| 573 |
+
im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
|
| 574 |
+
assert source_palette is not None
|
| 575 |
+
|
| 576 |
+
if palette:
|
| 577 |
+
used_palette_colors: list[int | None] = []
|
| 578 |
+
assert im.palette is not None
|
| 579 |
+
for i in range(0, len(source_palette), 3):
|
| 580 |
+
source_color = tuple(source_palette[i : i + 3])
|
| 581 |
+
index = im.palette.colors.get(source_color)
|
| 582 |
+
if index in used_palette_colors:
|
| 583 |
+
index = None
|
| 584 |
+
used_palette_colors.append(index)
|
| 585 |
+
for i, index in enumerate(used_palette_colors):
|
| 586 |
+
if index is None:
|
| 587 |
+
for j in range(len(used_palette_colors)):
|
| 588 |
+
if j not in used_palette_colors:
|
| 589 |
+
used_palette_colors[i] = j
|
| 590 |
+
break
|
| 591 |
+
dest_map: list[int] = []
|
| 592 |
+
for index in used_palette_colors:
|
| 593 |
+
assert index is not None
|
| 594 |
+
dest_map.append(index)
|
| 595 |
+
im = im.remap_palette(dest_map)
|
| 596 |
+
else:
|
| 597 |
+
optimized_palette_colors = _get_optimize(im, info)
|
| 598 |
+
if optimized_palette_colors is not None:
|
| 599 |
+
im = im.remap_palette(optimized_palette_colors, source_palette)
|
| 600 |
+
if "transparency" in info:
|
| 601 |
+
try:
|
| 602 |
+
info["transparency"] = optimized_palette_colors.index(
|
| 603 |
+
info["transparency"]
|
| 604 |
+
)
|
| 605 |
+
except ValueError:
|
| 606 |
+
del info["transparency"]
|
| 607 |
+
return im
|
| 608 |
+
|
| 609 |
+
assert im.palette is not None
|
| 610 |
+
im.palette.palette = source_palette
|
| 611 |
+
return im
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def _write_single_frame(
|
| 615 |
+
im: Image.Image,
|
| 616 |
+
fp: IO[bytes],
|
| 617 |
+
palette: _Palette | None,
|
| 618 |
+
) -> None:
|
| 619 |
+
im_out = _normalize_mode(im)
|
| 620 |
+
for k, v in im_out.info.items():
|
| 621 |
+
if isinstance(k, str):
|
| 622 |
+
im.encoderinfo.setdefault(k, v)
|
| 623 |
+
im_out = _normalize_palette(im_out, palette, im.encoderinfo)
|
| 624 |
+
|
| 625 |
+
for s in _get_global_header(im_out, im.encoderinfo):
|
| 626 |
+
fp.write(s)
|
| 627 |
+
|
| 628 |
+
# local image header
|
| 629 |
+
flags = 0
|
| 630 |
+
if get_interlace(im):
|
| 631 |
+
flags = flags | 64
|
| 632 |
+
_write_local_header(fp, im, (0, 0), flags)
|
| 633 |
+
|
| 634 |
+
im_out.encoderconfig = (8, get_interlace(im))
|
| 635 |
+
ImageFile._save(
|
| 636 |
+
im_out, fp, [ImageFile._Tile("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])]
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
fp.write(b"\0") # end of image data
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def _getbbox(
|
| 643 |
+
base_im: Image.Image, im_frame: Image.Image
|
| 644 |
+
) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
|
| 645 |
+
palette_bytes = [
|
| 646 |
+
bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame)
|
| 647 |
+
]
|
| 648 |
+
if palette_bytes[0] != palette_bytes[1]:
|
| 649 |
+
im_frame = im_frame.convert("RGBA")
|
| 650 |
+
base_im = base_im.convert("RGBA")
|
| 651 |
+
delta = ImageChops.subtract_modulo(im_frame, base_im)
|
| 652 |
+
return delta, delta.getbbox(alpha_only=False)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class _Frame(NamedTuple):
|
| 656 |
+
im: Image.Image
|
| 657 |
+
bbox: tuple[int, int, int, int] | None
|
| 658 |
+
encoderinfo: dict[str, Any]
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _write_multiple_frames(
|
| 662 |
+
im: Image.Image, fp: IO[bytes], palette: _Palette | None
|
| 663 |
+
) -> bool:
|
| 664 |
+
duration = im.encoderinfo.get("duration")
|
| 665 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
|
| 666 |
+
|
| 667 |
+
im_frames: list[_Frame] = []
|
| 668 |
+
previous_im: Image.Image | None = None
|
| 669 |
+
frame_count = 0
|
| 670 |
+
background_im = None
|
| 671 |
+
for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
|
| 672 |
+
for im_frame in ImageSequence.Iterator(imSequence):
|
| 673 |
+
# a copy is required here since seek can still mutate the image
|
| 674 |
+
im_frame = _normalize_mode(im_frame.copy())
|
| 675 |
+
if frame_count == 0:
|
| 676 |
+
for k, v in im_frame.info.items():
|
| 677 |
+
if k == "transparency":
|
| 678 |
+
continue
|
| 679 |
+
if isinstance(k, str):
|
| 680 |
+
im.encoderinfo.setdefault(k, v)
|
| 681 |
+
|
| 682 |
+
encoderinfo = im.encoderinfo.copy()
|
| 683 |
+
if "transparency" in im_frame.info:
|
| 684 |
+
encoderinfo.setdefault("transparency", im_frame.info["transparency"])
|
| 685 |
+
im_frame = _normalize_palette(im_frame, palette, encoderinfo)
|
| 686 |
+
if isinstance(duration, (list, tuple)):
|
| 687 |
+
encoderinfo["duration"] = duration[frame_count]
|
| 688 |
+
elif duration is None and "duration" in im_frame.info:
|
| 689 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
| 690 |
+
if isinstance(disposal, (list, tuple)):
|
| 691 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
| 692 |
+
frame_count += 1
|
| 693 |
+
|
| 694 |
+
diff_frame = None
|
| 695 |
+
if im_frames and previous_im:
|
| 696 |
+
# delta frame
|
| 697 |
+
delta, bbox = _getbbox(previous_im, im_frame)
|
| 698 |
+
if not bbox:
|
| 699 |
+
# This frame is identical to the previous frame
|
| 700 |
+
if encoderinfo.get("duration"):
|
| 701 |
+
im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"]
|
| 702 |
+
continue
|
| 703 |
+
if im_frames[-1].encoderinfo.get("disposal") == 2:
|
| 704 |
+
# To appear correctly in viewers using a convention,
|
| 705 |
+
# only consider transparency, and not background color
|
| 706 |
+
color = im.encoderinfo.get(
|
| 707 |
+
"transparency", im.info.get("transparency")
|
| 708 |
+
)
|
| 709 |
+
if color is not None:
|
| 710 |
+
if background_im is None:
|
| 711 |
+
background = _get_background(im_frame, color)
|
| 712 |
+
background_im = Image.new("P", im_frame.size, background)
|
| 713 |
+
first_palette = im_frames[0].im.palette
|
| 714 |
+
assert first_palette is not None
|
| 715 |
+
background_im.putpalette(first_palette, first_palette.mode)
|
| 716 |
+
bbox = _getbbox(background_im, im_frame)[1]
|
| 717 |
+
else:
|
| 718 |
+
bbox = (0, 0) + im_frame.size
|
| 719 |
+
elif encoderinfo.get("optimize") and im_frame.mode != "1":
|
| 720 |
+
if "transparency" not in encoderinfo:
|
| 721 |
+
assert im_frame.palette is not None
|
| 722 |
+
try:
|
| 723 |
+
encoderinfo["transparency"] = (
|
| 724 |
+
im_frame.palette._new_color_index(im_frame)
|
| 725 |
+
)
|
| 726 |
+
except ValueError:
|
| 727 |
+
pass
|
| 728 |
+
if "transparency" in encoderinfo:
|
| 729 |
+
# When the delta is zero, fill the image with transparency
|
| 730 |
+
diff_frame = im_frame.copy()
|
| 731 |
+
fill = Image.new("P", delta.size, encoderinfo["transparency"])
|
| 732 |
+
if delta.mode == "RGBA":
|
| 733 |
+
r, g, b, a = delta.split()
|
| 734 |
+
mask = ImageMath.lambda_eval(
|
| 735 |
+
lambda args: args["convert"](
|
| 736 |
+
args["max"](
|
| 737 |
+
args["max"](
|
| 738 |
+
args["max"](args["r"], args["g"]), args["b"]
|
| 739 |
+
),
|
| 740 |
+
args["a"],
|
| 741 |
+
)
|
| 742 |
+
* 255,
|
| 743 |
+
"1",
|
| 744 |
+
),
|
| 745 |
+
r=r,
|
| 746 |
+
g=g,
|
| 747 |
+
b=b,
|
| 748 |
+
a=a,
|
| 749 |
+
)
|
| 750 |
+
else:
|
| 751 |
+
if delta.mode == "P":
|
| 752 |
+
# Convert to L without considering palette
|
| 753 |
+
delta_l = Image.new("L", delta.size)
|
| 754 |
+
delta_l.putdata(delta.getdata())
|
| 755 |
+
delta = delta_l
|
| 756 |
+
mask = ImageMath.lambda_eval(
|
| 757 |
+
lambda args: args["convert"](args["im"] * 255, "1"),
|
| 758 |
+
im=delta,
|
| 759 |
+
)
|
| 760 |
+
diff_frame.paste(fill, mask=ImageOps.invert(mask))
|
| 761 |
+
else:
|
| 762 |
+
bbox = None
|
| 763 |
+
previous_im = im_frame
|
| 764 |
+
im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
|
| 765 |
+
|
| 766 |
+
if len(im_frames) == 1:
|
| 767 |
+
if "duration" in im.encoderinfo:
|
| 768 |
+
# Since multiple frames will not be written, use the combined duration
|
| 769 |
+
im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
|
| 770 |
+
return False
|
| 771 |
+
|
| 772 |
+
for frame_data in im_frames:
|
| 773 |
+
im_frame = frame_data.im
|
| 774 |
+
if not frame_data.bbox:
|
| 775 |
+
# global header
|
| 776 |
+
for s in _get_global_header(im_frame, frame_data.encoderinfo):
|
| 777 |
+
fp.write(s)
|
| 778 |
+
offset = (0, 0)
|
| 779 |
+
else:
|
| 780 |
+
# compress difference
|
| 781 |
+
if not palette:
|
| 782 |
+
frame_data.encoderinfo["include_color_table"] = True
|
| 783 |
+
|
| 784 |
+
if frame_data.bbox != (0, 0) + im_frame.size:
|
| 785 |
+
im_frame = im_frame.crop(frame_data.bbox)
|
| 786 |
+
offset = frame_data.bbox[:2]
|
| 787 |
+
_write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
|
| 788 |
+
return True
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 792 |
+
_save(im, fp, filename, save_all=True)
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def _save(
|
| 796 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
|
| 797 |
+
) -> None:
|
| 798 |
+
# header
|
| 799 |
+
if "palette" in im.encoderinfo or "palette" in im.info:
|
| 800 |
+
palette = im.encoderinfo.get("palette", im.info.get("palette"))
|
| 801 |
+
else:
|
| 802 |
+
palette = None
|
| 803 |
+
im.encoderinfo.setdefault("optimize", True)
|
| 804 |
+
|
| 805 |
+
if not save_all or not _write_multiple_frames(im, fp, palette):
|
| 806 |
+
_write_single_frame(im, fp, palette)
|
| 807 |
+
|
| 808 |
+
fp.write(b";") # end of file
|
| 809 |
+
|
| 810 |
+
if hasattr(fp, "flush"):
|
| 811 |
+
fp.flush()
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def get_interlace(im: Image.Image) -> int:
|
| 815 |
+
interlace = im.encoderinfo.get("interlace", 1)
|
| 816 |
+
|
| 817 |
+
# workaround for @PIL153
|
| 818 |
+
if min(im.size) < 16:
|
| 819 |
+
interlace = 0
|
| 820 |
+
|
| 821 |
+
return interlace
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def _write_local_header(
|
| 825 |
+
fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
|
| 826 |
+
) -> None:
|
| 827 |
+
try:
|
| 828 |
+
transparency = im.encoderinfo["transparency"]
|
| 829 |
+
except KeyError:
|
| 830 |
+
transparency = None
|
| 831 |
+
|
| 832 |
+
if "duration" in im.encoderinfo:
|
| 833 |
+
duration = int(im.encoderinfo["duration"] / 10)
|
| 834 |
+
else:
|
| 835 |
+
duration = 0
|
| 836 |
+
|
| 837 |
+
disposal = int(im.encoderinfo.get("disposal", 0))
|
| 838 |
+
|
| 839 |
+
if transparency is not None or duration != 0 or disposal:
|
| 840 |
+
packed_flag = 1 if transparency is not None else 0
|
| 841 |
+
packed_flag |= disposal << 2
|
| 842 |
+
|
| 843 |
+
fp.write(
|
| 844 |
+
b"!"
|
| 845 |
+
+ o8(249) # extension intro
|
| 846 |
+
+ o8(4) # length
|
| 847 |
+
+ o8(packed_flag) # packed fields
|
| 848 |
+
+ o16(duration) # duration
|
| 849 |
+
+ o8(transparency or 0) # transparency index
|
| 850 |
+
+ o8(0)
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
include_color_table = im.encoderinfo.get("include_color_table")
|
| 854 |
+
if include_color_table:
|
| 855 |
+
palette_bytes = _get_palette_bytes(im)
|
| 856 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 857 |
+
if color_table_size:
|
| 858 |
+
flags = flags | 128 # local color table flag
|
| 859 |
+
flags = flags | color_table_size
|
| 860 |
+
|
| 861 |
+
fp.write(
|
| 862 |
+
b","
|
| 863 |
+
+ o16(offset[0]) # offset
|
| 864 |
+
+ o16(offset[1])
|
| 865 |
+
+ o16(im.size[0]) # size
|
| 866 |
+
+ o16(im.size[1])
|
| 867 |
+
+ o8(flags) # flags
|
| 868 |
+
)
|
| 869 |
+
if include_color_table and color_table_size:
|
| 870 |
+
fp.write(_get_header_palette(palette_bytes))
|
| 871 |
+
fp.write(o8(8)) # bits
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 875 |
+
# Unused by default.
|
| 876 |
+
# To use, uncomment the register_save call at the end of the file.
|
| 877 |
+
#
|
| 878 |
+
# If you need real GIF compression and/or RGB quantization, you
|
| 879 |
+
# can use the external NETPBM/PBMPLUS utilities. See comments
|
| 880 |
+
# below for information on how to enable this.
|
| 881 |
+
tempfile = im._dump()
|
| 882 |
+
|
| 883 |
+
try:
|
| 884 |
+
with open(filename, "wb") as f:
|
| 885 |
+
if im.mode != "RGB":
|
| 886 |
+
subprocess.check_call(
|
| 887 |
+
["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
|
| 888 |
+
)
|
| 889 |
+
else:
|
| 890 |
+
# Pipe ppmquant output into ppmtogif
|
| 891 |
+
# "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
|
| 892 |
+
quant_cmd = ["ppmquant", "256", tempfile]
|
| 893 |
+
togif_cmd = ["ppmtogif"]
|
| 894 |
+
quant_proc = subprocess.Popen(
|
| 895 |
+
quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
| 896 |
+
)
|
| 897 |
+
togif_proc = subprocess.Popen(
|
| 898 |
+
togif_cmd,
|
| 899 |
+
stdin=quant_proc.stdout,
|
| 900 |
+
stdout=f,
|
| 901 |
+
stderr=subprocess.DEVNULL,
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
# Allow ppmquant to receive SIGPIPE if ppmtogif exits
|
| 905 |
+
assert quant_proc.stdout is not None
|
| 906 |
+
quant_proc.stdout.close()
|
| 907 |
+
|
| 908 |
+
retcode = quant_proc.wait()
|
| 909 |
+
if retcode:
|
| 910 |
+
raise subprocess.CalledProcessError(retcode, quant_cmd)
|
| 911 |
+
|
| 912 |
+
retcode = togif_proc.wait()
|
| 913 |
+
if retcode:
|
| 914 |
+
raise subprocess.CalledProcessError(retcode, togif_cmd)
|
| 915 |
+
finally:
|
| 916 |
+
try:
|
| 917 |
+
os.unlink(tempfile)
|
| 918 |
+
except OSError:
|
| 919 |
+
pass
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
# Force optimization so that we can test performance against
|
| 923 |
+
# cases where it took lots of memory and time previously.
|
| 924 |
+
_FORCE_OPTIMIZE = False
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
|
| 928 |
+
"""
|
| 929 |
+
Palette optimization is a potentially expensive operation.
|
| 930 |
+
|
| 931 |
+
This function determines if the palette should be optimized using
|
| 932 |
+
some heuristics, then returns the list of palette entries in use.
|
| 933 |
+
|
| 934 |
+
:param im: Image object
|
| 935 |
+
:param info: encoderinfo
|
| 936 |
+
:returns: list of indexes of palette entries in use, or None
|
| 937 |
+
"""
|
| 938 |
+
if im.mode in ("P", "L") and info and info.get("optimize"):
|
| 939 |
+
# Potentially expensive operation.
|
| 940 |
+
|
| 941 |
+
# The palette saves 3 bytes per color not used, but palette
|
| 942 |
+
# lengths are restricted to 3*(2**N) bytes. Max saving would
|
| 943 |
+
# be 768 -> 6 bytes if we went all the way down to 2 colors.
|
| 944 |
+
# * If we're over 128 colors, we can't save any space.
|
| 945 |
+
# * If there aren't any holes, it's not worth collapsing.
|
| 946 |
+
# * If we have a 'large' image, the palette is in the noise.
|
| 947 |
+
|
| 948 |
+
# create the new palette if not every color is used
|
| 949 |
+
optimise = _FORCE_OPTIMIZE or im.mode == "L"
|
| 950 |
+
if optimise or im.width * im.height < 512 * 512:
|
| 951 |
+
# check which colors are used
|
| 952 |
+
used_palette_colors = []
|
| 953 |
+
for i, count in enumerate(im.histogram()):
|
| 954 |
+
if count:
|
| 955 |
+
used_palette_colors.append(i)
|
| 956 |
+
|
| 957 |
+
if optimise or max(used_palette_colors) >= len(used_palette_colors):
|
| 958 |
+
return used_palette_colors
|
| 959 |
+
|
| 960 |
+
assert im.palette is not None
|
| 961 |
+
num_palette_colors = len(im.palette.palette) // Image.getmodebands(
|
| 962 |
+
im.palette.mode
|
| 963 |
+
)
|
| 964 |
+
current_palette_size = 1 << (num_palette_colors - 1).bit_length()
|
| 965 |
+
if (
|
| 966 |
+
# check that the palette would become smaller when saved
|
| 967 |
+
len(used_palette_colors) <= current_palette_size // 2
|
| 968 |
+
# check that the palette is not already the smallest possible size
|
| 969 |
+
and current_palette_size > 2
|
| 970 |
+
):
|
| 971 |
+
return used_palette_colors
|
| 972 |
+
return None
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def _get_color_table_size(palette_bytes: bytes) -> int:
|
| 976 |
+
# calculate the palette size for the header
|
| 977 |
+
if not palette_bytes:
|
| 978 |
+
return 0
|
| 979 |
+
elif len(palette_bytes) < 9:
|
| 980 |
+
return 1
|
| 981 |
+
else:
|
| 982 |
+
return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def _get_header_palette(palette_bytes: bytes) -> bytes:
|
| 986 |
+
"""
|
| 987 |
+
Returns the palette, null padded to the next power of 2 (*3) bytes
|
| 988 |
+
suitable for direct inclusion in the GIF header
|
| 989 |
+
|
| 990 |
+
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
|
| 991 |
+
:returns: Null padded palette
|
| 992 |
+
"""
|
| 993 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 994 |
+
|
| 995 |
+
# add the missing amount of bytes
|
| 996 |
+
# the palette has to be 2<<n in size
|
| 997 |
+
actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
|
| 998 |
+
if actual_target_size_diff > 0:
|
| 999 |
+
palette_bytes += o8(0) * 3 * actual_target_size_diff
|
| 1000 |
+
return palette_bytes
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def _get_palette_bytes(im: Image.Image) -> bytes:
|
| 1004 |
+
"""
|
| 1005 |
+
Gets the palette for inclusion in the gif header
|
| 1006 |
+
|
| 1007 |
+
:param im: Image object
|
| 1008 |
+
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
| 1009 |
+
"""
|
| 1010 |
+
if not im.palette:
|
| 1011 |
+
return b""
|
| 1012 |
+
|
| 1013 |
+
palette = bytes(im.palette.palette)
|
| 1014 |
+
if im.palette.mode == "RGBA":
|
| 1015 |
+
palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3))
|
| 1016 |
+
return palette
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def _get_background(
|
| 1020 |
+
im: Image.Image,
|
| 1021 |
+
info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
|
| 1022 |
+
) -> int:
|
| 1023 |
+
background = 0
|
| 1024 |
+
if info_background:
|
| 1025 |
+
if isinstance(info_background, tuple):
|
| 1026 |
+
# WebPImagePlugin stores an RGBA value in info["background"]
|
| 1027 |
+
# So it must be converted to the same format as GifImagePlugin's
|
| 1028 |
+
# info["background"] - a global color table index
|
| 1029 |
+
assert im.palette is not None
|
| 1030 |
+
try:
|
| 1031 |
+
background = im.palette.getcolor(info_background, im)
|
| 1032 |
+
except ValueError as e:
|
| 1033 |
+
if str(e) not in (
|
| 1034 |
+
# If all 256 colors are in use,
|
| 1035 |
+
# then there is no need for the background color
|
| 1036 |
+
"cannot allocate more than 256 colors",
|
| 1037 |
+
# Ignore non-opaque WebP background
|
| 1038 |
+
"cannot add non-opaque RGBA color to RGB palette",
|
| 1039 |
+
):
|
| 1040 |
+
raise
|
| 1041 |
+
else:
|
| 1042 |
+
background = info_background
|
| 1043 |
+
return background
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
|
| 1047 |
+
"""Return a list of strings representing a GIF header"""
|
| 1048 |
+
|
| 1049 |
+
# Header Block
|
| 1050 |
+
# https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
|
| 1051 |
+
|
| 1052 |
+
version = b"87a"
|
| 1053 |
+
if im.info.get("version") == b"89a" or (
|
| 1054 |
+
info
|
| 1055 |
+
and (
|
| 1056 |
+
"transparency" in info
|
| 1057 |
+
or info.get("loop") is not None
|
| 1058 |
+
or info.get("duration")
|
| 1059 |
+
or info.get("comment")
|
| 1060 |
+
)
|
| 1061 |
+
):
|
| 1062 |
+
version = b"89a"
|
| 1063 |
+
|
| 1064 |
+
background = _get_background(im, info.get("background"))
|
| 1065 |
+
|
| 1066 |
+
palette_bytes = _get_palette_bytes(im)
|
| 1067 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 1068 |
+
|
| 1069 |
+
header = [
|
| 1070 |
+
b"GIF" # signature
|
| 1071 |
+
+ version # version
|
| 1072 |
+
+ o16(im.size[0]) # canvas width
|
| 1073 |
+
+ o16(im.size[1]), # canvas height
|
| 1074 |
+
# Logical Screen Descriptor
|
| 1075 |
+
# size of global color table + global color table flag
|
| 1076 |
+
o8(color_table_size + 128), # packed fields
|
| 1077 |
+
# background + reserved/aspect
|
| 1078 |
+
o8(background) + o8(0),
|
| 1079 |
+
# Global Color Table
|
| 1080 |
+
_get_header_palette(palette_bytes),
|
| 1081 |
+
]
|
| 1082 |
+
if info.get("loop") is not None:
|
| 1083 |
+
header.append(
|
| 1084 |
+
b"!"
|
| 1085 |
+
+ o8(255) # extension intro
|
| 1086 |
+
+ o8(11)
|
| 1087 |
+
+ b"NETSCAPE2.0"
|
| 1088 |
+
+ o8(3)
|
| 1089 |
+
+ o8(1)
|
| 1090 |
+
+ o16(info["loop"]) # number of loops
|
| 1091 |
+
+ o8(0)
|
| 1092 |
+
)
|
| 1093 |
+
if info.get("comment"):
|
| 1094 |
+
comment_block = b"!" + o8(254) # extension intro
|
| 1095 |
+
|
| 1096 |
+
comment = info["comment"]
|
| 1097 |
+
if isinstance(comment, str):
|
| 1098 |
+
comment = comment.encode()
|
| 1099 |
+
for i in range(0, len(comment), 255):
|
| 1100 |
+
subblock = comment[i : i + 255]
|
| 1101 |
+
comment_block += o8(len(subblock)) + subblock
|
| 1102 |
+
|
| 1103 |
+
comment_block += o8(0)
|
| 1104 |
+
header.append(comment_block)
|
| 1105 |
+
return header
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
def _write_frame_data(
|
| 1109 |
+
fp: IO[bytes],
|
| 1110 |
+
im_frame: Image.Image,
|
| 1111 |
+
offset: tuple[int, int],
|
| 1112 |
+
params: dict[str, Any],
|
| 1113 |
+
) -> None:
|
| 1114 |
+
try:
|
| 1115 |
+
im_frame.encoderinfo = params
|
| 1116 |
+
|
| 1117 |
+
# local image header
|
| 1118 |
+
_write_local_header(fp, im_frame, offset, 0)
|
| 1119 |
+
|
| 1120 |
+
ImageFile._save(
|
| 1121 |
+
im_frame,
|
| 1122 |
+
fp,
|
| 1123 |
+
[ImageFile._Tile("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])],
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
+
fp.write(b"\0") # end of image data
|
| 1127 |
+
finally:
|
| 1128 |
+
del im_frame.encoderinfo
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
# --------------------------------------------------------------------
|
| 1132 |
+
# Legacy GIF utilities
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
def getheader(
|
| 1136 |
+
im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
|
| 1137 |
+
) -> tuple[list[bytes], list[int] | None]:
|
| 1138 |
+
"""
|
| 1139 |
+
Legacy Method to get Gif data from image.
|
| 1140 |
+
|
| 1141 |
+
Warning:: May modify image data.
|
| 1142 |
+
|
| 1143 |
+
:param im: Image object
|
| 1144 |
+
:param palette: bytes object containing the source palette, or ....
|
| 1145 |
+
:param info: encoderinfo
|
| 1146 |
+
:returns: tuple of(list of header items, optimized palette)
|
| 1147 |
+
|
| 1148 |
+
"""
|
| 1149 |
+
if info is None:
|
| 1150 |
+
info = {}
|
| 1151 |
+
|
| 1152 |
+
used_palette_colors = _get_optimize(im, info)
|
| 1153 |
+
|
| 1154 |
+
if "background" not in info and "background" in im.info:
|
| 1155 |
+
info["background"] = im.info["background"]
|
| 1156 |
+
|
| 1157 |
+
im_mod = _normalize_palette(im, palette, info)
|
| 1158 |
+
im.palette = im_mod.palette
|
| 1159 |
+
im.im = im_mod.im
|
| 1160 |
+
header = _get_global_header(im, info)
|
| 1161 |
+
|
| 1162 |
+
return header, used_palette_colors
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def getdata(
|
| 1166 |
+
im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
|
| 1167 |
+
) -> list[bytes]:
|
| 1168 |
+
"""
|
| 1169 |
+
Legacy Method
|
| 1170 |
+
|
| 1171 |
+
Return a list of strings representing this image.
|
| 1172 |
+
The first string is a local image header, the rest contains
|
| 1173 |
+
encoded image data.
|
| 1174 |
+
|
| 1175 |
+
To specify duration, add the time in milliseconds,
|
| 1176 |
+
e.g. ``getdata(im_frame, duration=1000)``
|
| 1177 |
+
|
| 1178 |
+
:param im: Image object
|
| 1179 |
+
:param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
|
| 1180 |
+
:param \\**params: e.g. duration or other encoder info parameters
|
| 1181 |
+
:returns: List of bytes containing GIF encoded frame data
|
| 1182 |
+
|
| 1183 |
+
"""
|
| 1184 |
+
from io import BytesIO
|
| 1185 |
+
|
| 1186 |
+
class Collector(BytesIO):
|
| 1187 |
+
data = []
|
| 1188 |
+
|
| 1189 |
+
def write(self, data: Buffer) -> int:
|
| 1190 |
+
self.data.append(data)
|
| 1191 |
+
return len(data)
|
| 1192 |
+
|
| 1193 |
+
im.load() # make sure raster data is available
|
| 1194 |
+
|
| 1195 |
+
fp = Collector()
|
| 1196 |
+
|
| 1197 |
+
_write_frame_data(fp, im, offset, params)
|
| 1198 |
+
|
| 1199 |
+
return fp.data
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
# --------------------------------------------------------------------
|
| 1203 |
+
# Registry
|
| 1204 |
+
|
| 1205 |
+
Image.register_open(GifImageFile.format, GifImageFile, _accept)
|
| 1206 |
+
Image.register_save(GifImageFile.format, _save)
|
| 1207 |
+
Image.register_save_all(GifImageFile.format, _save_all)
|
| 1208 |
+
Image.register_extension(GifImageFile.format, ".gif")
|
| 1209 |
+
Image.register_mime(GifImageFile.format, "image/gif")
|
| 1210 |
+
|
| 1211 |
+
#
|
| 1212 |
+
# Uncomment the following line if you wish to use NETPBM/PBMPLUS
|
| 1213 |
+
# instead of the built-in "uncompressed" GIF encoder
|
| 1214 |
+
|
| 1215 |
+
# Image.register_save(GifImageFile.format, _save_netpbm)
|
.venv/lib/python3.12/site-packages/PIL/GimpPaletteFile.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 io import BytesIO
|
| 20 |
+
|
| 21 |
+
TYPE_CHECKING = False
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from typing import IO
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class GimpPaletteFile:
|
| 27 |
+
"""File handler for GIMP's palette format."""
|
| 28 |
+
|
| 29 |
+
rawmode = "RGB"
|
| 30 |
+
|
| 31 |
+
def _read(self, fp: IO[bytes], limit: bool = True) -> None:
|
| 32 |
+
if not fp.readline().startswith(b"GIMP Palette"):
|
| 33 |
+
msg = "not a GIMP palette file"
|
| 34 |
+
raise SyntaxError(msg)
|
| 35 |
+
|
| 36 |
+
palette: list[int] = []
|
| 37 |
+
i = 0
|
| 38 |
+
while True:
|
| 39 |
+
if limit and i == 256 + 3:
|
| 40 |
+
break
|
| 41 |
+
|
| 42 |
+
i += 1
|
| 43 |
+
s = fp.readline()
|
| 44 |
+
if not s:
|
| 45 |
+
break
|
| 46 |
+
|
| 47 |
+
# skip fields and comment lines
|
| 48 |
+
if re.match(rb"\w+:|#", s):
|
| 49 |
+
continue
|
| 50 |
+
if limit and len(s) > 100:
|
| 51 |
+
msg = "bad palette file"
|
| 52 |
+
raise SyntaxError(msg)
|
| 53 |
+
|
| 54 |
+
v = s.split(maxsplit=3)
|
| 55 |
+
if len(v) < 3:
|
| 56 |
+
msg = "bad palette entry"
|
| 57 |
+
raise ValueError(msg)
|
| 58 |
+
|
| 59 |
+
palette += (int(v[i]) for i in range(3))
|
| 60 |
+
if limit and len(palette) == 768:
|
| 61 |
+
break
|
| 62 |
+
|
| 63 |
+
self.palette = bytes(palette)
|
| 64 |
+
|
| 65 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 66 |
+
self._read(fp)
|
| 67 |
+
|
| 68 |
+
@classmethod
|
| 69 |
+
def frombytes(cls, data: bytes) -> GimpPaletteFile:
|
| 70 |
+
self = cls.__new__(cls)
|
| 71 |
+
self._read(BytesIO(data), False)
|
| 72 |
+
return self
|
| 73 |
+
|
| 74 |
+
def getpalette(self) -> tuple[bytes, str]:
|
| 75 |
+
return self.palette, self.rawmode
|
.venv/lib/python3.12/site-packages/PIL/GribStubImagePlugin.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 14 |
+
from typing import IO
|
| 15 |
+
|
| 16 |
+
from . import Image, ImageFile
|
| 17 |
+
|
| 18 |
+
_handler = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 22 |
+
"""
|
| 23 |
+
Install application-specific GRIB image handler.
|
| 24 |
+
|
| 25 |
+
:param handler: Handler object.
|
| 26 |
+
"""
|
| 27 |
+
global _handler
|
| 28 |
+
_handler = handler
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# --------------------------------------------------------------------
|
| 32 |
+
# Image adapter
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _accept(prefix: bytes) -> bool:
|
| 36 |
+
return len(prefix) >= 8 and prefix.startswith(b"GRIB") and prefix[7] == 1
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class GribStubImageFile(ImageFile.StubImageFile):
|
| 40 |
+
format = "GRIB"
|
| 41 |
+
format_description = "GRIB"
|
| 42 |
+
|
| 43 |
+
def _open(self) -> None:
|
| 44 |
+
if not _accept(self.fp.read(8)):
|
| 45 |
+
msg = "Not a GRIB file"
|
| 46 |
+
raise SyntaxError(msg)
|
| 47 |
+
|
| 48 |
+
self.fp.seek(-8, os.SEEK_CUR)
|
| 49 |
+
|
| 50 |
+
# make something up
|
| 51 |
+
self._mode = "F"
|
| 52 |
+
self._size = 1, 1
|
| 53 |
+
|
| 54 |
+
loader = self._load()
|
| 55 |
+
if loader:
|
| 56 |
+
loader.open(self)
|
| 57 |
+
|
| 58 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 59 |
+
return _handler
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 63 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 64 |
+
msg = "GRIB save handler not installed"
|
| 65 |
+
raise OSError(msg)
|
| 66 |
+
_handler.save(im, fp, filename)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# --------------------------------------------------------------------
|
| 70 |
+
# Registry
|
| 71 |
+
|
| 72 |
+
Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
|
| 73 |
+
Image.register_save(GribStubImageFile.format, _save)
|
| 74 |
+
|
| 75 |
+
Image.register_extension(GribStubImageFile.format, ".grib")
|
.venv/lib/python3.12/site-packages/PIL/IcnsImagePlugin.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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: IO[bytes]) -> tuple[bytes, int]:
|
| 38 |
+
return struct.unpack(">4sI", fobj.read(HEADERSIZE))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def read_32t(
|
| 42 |
+
fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
|
| 43 |
+
) -> dict[str, Image.Image]:
|
| 44 |
+
# The 128x128 icon seems to have an extra header for some reason.
|
| 45 |
+
(start, length) = start_length
|
| 46 |
+
fobj.seek(start)
|
| 47 |
+
sig = fobj.read(4)
|
| 48 |
+
if sig != b"\x00\x00\x00\x00":
|
| 49 |
+
msg = "Unknown signature, expecting 0x00000000"
|
| 50 |
+
raise SyntaxError(msg)
|
| 51 |
+
return read_32(fobj, (start + 4, length - 4), size)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def read_32(
|
| 55 |
+
fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
|
| 56 |
+
) -> dict[str, Image.Image]:
|
| 57 |
+
"""
|
| 58 |
+
Read a 32bit RGB icon resource. Seems to be either uncompressed or
|
| 59 |
+
an RLE packbits-like scheme.
|
| 60 |
+
"""
|
| 61 |
+
(start, length) = start_length
|
| 62 |
+
fobj.seek(start)
|
| 63 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 64 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 65 |
+
if length == sizesq * 3:
|
| 66 |
+
# uncompressed ("RGBRGBGB")
|
| 67 |
+
indata = fobj.read(length)
|
| 68 |
+
im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
|
| 69 |
+
else:
|
| 70 |
+
# decode image
|
| 71 |
+
im = Image.new("RGB", pixel_size, None)
|
| 72 |
+
for band_ix in range(3):
|
| 73 |
+
data = []
|
| 74 |
+
bytesleft = sizesq
|
| 75 |
+
while bytesleft > 0:
|
| 76 |
+
byte = fobj.read(1)
|
| 77 |
+
if not byte:
|
| 78 |
+
break
|
| 79 |
+
byte_int = byte[0]
|
| 80 |
+
if byte_int & 0x80:
|
| 81 |
+
blocksize = byte_int - 125
|
| 82 |
+
byte = fobj.read(1)
|
| 83 |
+
for i in range(blocksize):
|
| 84 |
+
data.append(byte)
|
| 85 |
+
else:
|
| 86 |
+
blocksize = byte_int + 1
|
| 87 |
+
data.append(fobj.read(blocksize))
|
| 88 |
+
bytesleft -= blocksize
|
| 89 |
+
if bytesleft <= 0:
|
| 90 |
+
break
|
| 91 |
+
if bytesleft != 0:
|
| 92 |
+
msg = f"Error reading channel [{repr(bytesleft)} left]"
|
| 93 |
+
raise SyntaxError(msg)
|
| 94 |
+
band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
|
| 95 |
+
im.im.putband(band.im, band_ix)
|
| 96 |
+
return {"RGB": im}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def read_mk(
|
| 100 |
+
fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
|
| 101 |
+
) -> dict[str, Image.Image]:
|
| 102 |
+
# Alpha masks seem to be uncompressed
|
| 103 |
+
start = start_length[0]
|
| 104 |
+
fobj.seek(start)
|
| 105 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 106 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 107 |
+
band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
|
| 108 |
+
return {"A": band}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def read_png_or_jpeg2000(
|
| 112 |
+
fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
|
| 113 |
+
) -> dict[str, Image.Image]:
|
| 114 |
+
(start, length) = start_length
|
| 115 |
+
fobj.seek(start)
|
| 116 |
+
sig = fobj.read(12)
|
| 117 |
+
|
| 118 |
+
im: Image.Image
|
| 119 |
+
if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"):
|
| 120 |
+
fobj.seek(start)
|
| 121 |
+
im = PngImagePlugin.PngImageFile(fobj)
|
| 122 |
+
Image._decompression_bomb_check(im.size)
|
| 123 |
+
return {"RGBA": im}
|
| 124 |
+
elif (
|
| 125 |
+
sig.startswith((b"\xff\x4f\xff\x51", b"\x0d\x0a\x87\x0a"))
|
| 126 |
+
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
| 127 |
+
):
|
| 128 |
+
if not enable_jpeg2k:
|
| 129 |
+
msg = (
|
| 130 |
+
"Unsupported icon subimage format (rebuild PIL "
|
| 131 |
+
"with JPEG 2000 support to fix this)"
|
| 132 |
+
)
|
| 133 |
+
raise ValueError(msg)
|
| 134 |
+
# j2k, jpc or j2c
|
| 135 |
+
fobj.seek(start)
|
| 136 |
+
jp2kstream = fobj.read(length)
|
| 137 |
+
f = io.BytesIO(jp2kstream)
|
| 138 |
+
im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
|
| 139 |
+
Image._decompression_bomb_check(im.size)
|
| 140 |
+
if im.mode != "RGBA":
|
| 141 |
+
im = im.convert("RGBA")
|
| 142 |
+
return {"RGBA": im}
|
| 143 |
+
else:
|
| 144 |
+
msg = "Unsupported icon subimage format"
|
| 145 |
+
raise ValueError(msg)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class IcnsFile:
|
| 149 |
+
SIZES = {
|
| 150 |
+
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
|
| 151 |
+
(512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
|
| 152 |
+
(256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
|
| 153 |
+
(256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
|
| 154 |
+
(128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
|
| 155 |
+
(128, 128, 1): [
|
| 156 |
+
(b"ic07", read_png_or_jpeg2000),
|
| 157 |
+
(b"it32", read_32t),
|
| 158 |
+
(b"t8mk", read_mk),
|
| 159 |
+
],
|
| 160 |
+
(64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
|
| 161 |
+
(32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
|
| 162 |
+
(48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
|
| 163 |
+
(32, 32, 1): [
|
| 164 |
+
(b"icp5", read_png_or_jpeg2000),
|
| 165 |
+
(b"il32", read_32),
|
| 166 |
+
(b"l8mk", read_mk),
|
| 167 |
+
],
|
| 168 |
+
(16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
|
| 169 |
+
(16, 16, 1): [
|
| 170 |
+
(b"icp4", read_png_or_jpeg2000),
|
| 171 |
+
(b"is32", read_32),
|
| 172 |
+
(b"s8mk", read_mk),
|
| 173 |
+
],
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
def __init__(self, fobj: IO[bytes]) -> None:
|
| 177 |
+
"""
|
| 178 |
+
fobj is a file-like object as an icns resource
|
| 179 |
+
"""
|
| 180 |
+
# signature : (start, length)
|
| 181 |
+
self.dct = {}
|
| 182 |
+
self.fobj = fobj
|
| 183 |
+
sig, filesize = nextheader(fobj)
|
| 184 |
+
if not _accept(sig):
|
| 185 |
+
msg = "not an icns file"
|
| 186 |
+
raise SyntaxError(msg)
|
| 187 |
+
i = HEADERSIZE
|
| 188 |
+
while i < filesize:
|
| 189 |
+
sig, blocksize = nextheader(fobj)
|
| 190 |
+
if blocksize <= 0:
|
| 191 |
+
msg = "invalid block header"
|
| 192 |
+
raise SyntaxError(msg)
|
| 193 |
+
i += HEADERSIZE
|
| 194 |
+
blocksize -= HEADERSIZE
|
| 195 |
+
self.dct[sig] = (i, blocksize)
|
| 196 |
+
fobj.seek(blocksize, io.SEEK_CUR)
|
| 197 |
+
i += blocksize
|
| 198 |
+
|
| 199 |
+
def itersizes(self) -> list[tuple[int, int, int]]:
|
| 200 |
+
sizes = []
|
| 201 |
+
for size, fmts in self.SIZES.items():
|
| 202 |
+
for fmt, reader in fmts:
|
| 203 |
+
if fmt in self.dct:
|
| 204 |
+
sizes.append(size)
|
| 205 |
+
break
|
| 206 |
+
return sizes
|
| 207 |
+
|
| 208 |
+
def bestsize(self) -> tuple[int, int, int]:
|
| 209 |
+
sizes = self.itersizes()
|
| 210 |
+
if not sizes:
|
| 211 |
+
msg = "No 32bit icon resources found"
|
| 212 |
+
raise SyntaxError(msg)
|
| 213 |
+
return max(sizes)
|
| 214 |
+
|
| 215 |
+
def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:
|
| 216 |
+
"""
|
| 217 |
+
Get an icon resource as {channel: array}. Note that
|
| 218 |
+
the arrays are bottom-up like windows bitmaps and will likely
|
| 219 |
+
need to be flipped or transposed in some way.
|
| 220 |
+
"""
|
| 221 |
+
dct = {}
|
| 222 |
+
for code, reader in self.SIZES[size]:
|
| 223 |
+
desc = self.dct.get(code)
|
| 224 |
+
if desc is not None:
|
| 225 |
+
dct.update(reader(self.fobj, desc, size))
|
| 226 |
+
return dct
|
| 227 |
+
|
| 228 |
+
def getimage(
|
| 229 |
+
self, size: tuple[int, int] | tuple[int, int, int] | None = None
|
| 230 |
+
) -> Image.Image:
|
| 231 |
+
if size is None:
|
| 232 |
+
size = self.bestsize()
|
| 233 |
+
elif len(size) == 2:
|
| 234 |
+
size = (size[0], size[1], 1)
|
| 235 |
+
channels = self.dataforsize(size)
|
| 236 |
+
|
| 237 |
+
im = channels.get("RGBA")
|
| 238 |
+
if im:
|
| 239 |
+
return im
|
| 240 |
+
|
| 241 |
+
im = channels["RGB"].copy()
|
| 242 |
+
try:
|
| 243 |
+
im.putalpha(channels["A"])
|
| 244 |
+
except KeyError:
|
| 245 |
+
pass
|
| 246 |
+
return im
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
##
|
| 250 |
+
# Image plugin for Mac OS icons.
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class IcnsImageFile(ImageFile.ImageFile):
|
| 254 |
+
"""
|
| 255 |
+
PIL image support for Mac OS .icns files.
|
| 256 |
+
Chooses the best resolution, but will possibly load
|
| 257 |
+
a different size image if you mutate the size attribute
|
| 258 |
+
before calling 'load'.
|
| 259 |
+
|
| 260 |
+
The info dictionary has a key 'sizes' that is a list
|
| 261 |
+
of sizes that the icns file has.
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
format = "ICNS"
|
| 265 |
+
format_description = "Mac OS icns resource"
|
| 266 |
+
|
| 267 |
+
def _open(self) -> None:
|
| 268 |
+
self.icns = IcnsFile(self.fp)
|
| 269 |
+
self._mode = "RGBA"
|
| 270 |
+
self.info["sizes"] = self.icns.itersizes()
|
| 271 |
+
self.best_size = self.icns.bestsize()
|
| 272 |
+
self.size = (
|
| 273 |
+
self.best_size[0] * self.best_size[2],
|
| 274 |
+
self.best_size[1] * self.best_size[2],
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def size(self) -> tuple[int, int]:
|
| 279 |
+
return self._size
|
| 280 |
+
|
| 281 |
+
@size.setter
|
| 282 |
+
def size(self, value: tuple[int, int]) -> None:
|
| 283 |
+
# Check that a matching size exists,
|
| 284 |
+
# or that there is a scale that would create a size that matches
|
| 285 |
+
for size in self.info["sizes"]:
|
| 286 |
+
simple_size = size[0] * size[2], size[1] * size[2]
|
| 287 |
+
scale = simple_size[0] // value[0]
|
| 288 |
+
if simple_size[1] / value[1] == scale:
|
| 289 |
+
self._size = value
|
| 290 |
+
return
|
| 291 |
+
msg = "This is not one of the allowed sizes of this image"
|
| 292 |
+
raise ValueError(msg)
|
| 293 |
+
|
| 294 |
+
def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:
|
| 295 |
+
if scale is not None:
|
| 296 |
+
width, height = self.size[:2]
|
| 297 |
+
self.size = width * scale, height * scale
|
| 298 |
+
self.best_size = width, height, scale
|
| 299 |
+
|
| 300 |
+
px = Image.Image.load(self)
|
| 301 |
+
if self._im is not None and self.im.size == self.size:
|
| 302 |
+
# Already loaded
|
| 303 |
+
return px
|
| 304 |
+
self.load_prepare()
|
| 305 |
+
# This is likely NOT the best way to do it, but whatever.
|
| 306 |
+
im = self.icns.getimage(self.best_size)
|
| 307 |
+
|
| 308 |
+
# If this is a PNG or JPEG 2000, it won't be loaded yet
|
| 309 |
+
px = im.load()
|
| 310 |
+
|
| 311 |
+
self.im = im.im
|
| 312 |
+
self._mode = im.mode
|
| 313 |
+
self.size = im.size
|
| 314 |
+
|
| 315 |
+
return px
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 319 |
+
"""
|
| 320 |
+
Saves the image as a series of PNG files,
|
| 321 |
+
that are then combined into a .icns file.
|
| 322 |
+
"""
|
| 323 |
+
if hasattr(fp, "flush"):
|
| 324 |
+
fp.flush()
|
| 325 |
+
|
| 326 |
+
sizes = {
|
| 327 |
+
b"ic07": 128,
|
| 328 |
+
b"ic08": 256,
|
| 329 |
+
b"ic09": 512,
|
| 330 |
+
b"ic10": 1024,
|
| 331 |
+
b"ic11": 32,
|
| 332 |
+
b"ic12": 64,
|
| 333 |
+
b"ic13": 256,
|
| 334 |
+
b"ic14": 512,
|
| 335 |
+
}
|
| 336 |
+
provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
|
| 337 |
+
size_streams = {}
|
| 338 |
+
for size in set(sizes.values()):
|
| 339 |
+
image = (
|
| 340 |
+
provided_images[size]
|
| 341 |
+
if size in provided_images
|
| 342 |
+
else im.resize((size, size))
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
temp = io.BytesIO()
|
| 346 |
+
image.save(temp, "png")
|
| 347 |
+
size_streams[size] = temp.getvalue()
|
| 348 |
+
|
| 349 |
+
entries = []
|
| 350 |
+
for type, size in sizes.items():
|
| 351 |
+
stream = size_streams[size]
|
| 352 |
+
entries.append((type, HEADERSIZE + len(stream), stream))
|
| 353 |
+
|
| 354 |
+
# Header
|
| 355 |
+
fp.write(MAGIC)
|
| 356 |
+
file_length = HEADERSIZE # Header
|
| 357 |
+
file_length += HEADERSIZE + 8 * len(entries) # TOC
|
| 358 |
+
file_length += sum(entry[1] for entry in entries)
|
| 359 |
+
fp.write(struct.pack(">i", file_length))
|
| 360 |
+
|
| 361 |
+
# TOC
|
| 362 |
+
fp.write(b"TOC ")
|
| 363 |
+
fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
|
| 364 |
+
for entry in entries:
|
| 365 |
+
fp.write(entry[0])
|
| 366 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 367 |
+
|
| 368 |
+
# Data
|
| 369 |
+
for entry in entries:
|
| 370 |
+
fp.write(entry[0])
|
| 371 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 372 |
+
fp.write(entry[2])
|
| 373 |
+
|
| 374 |
+
if hasattr(fp, "flush"):
|
| 375 |
+
fp.flush()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _accept(prefix: bytes) -> bool:
|
| 379 |
+
return prefix.startswith(MAGIC)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
|
| 383 |
+
Image.register_extension(IcnsImageFile.format, ".icns")
|
| 384 |
+
|
| 385 |
+
Image.register_save(IcnsImageFile.format, _save)
|
| 386 |
+
Image.register_mime(IcnsImageFile.format, "image/icns")
|
| 387 |
+
|
| 388 |
+
if __name__ == "__main__":
|
| 389 |
+
if len(sys.argv) < 2:
|
| 390 |
+
print("Syntax: python3 IcnsImagePlugin.py [file]")
|
| 391 |
+
sys.exit()
|
| 392 |
+
|
| 393 |
+
with open(sys.argv[1], "rb") as fp:
|
| 394 |
+
imf = IcnsImageFile(fp)
|
| 395 |
+
for size in imf.info["sizes"]:
|
| 396 |
+
width, height, scale = imf.size = size
|
| 397 |
+
imf.save(f"out-{width}-{height}-{scale}.png")
|
| 398 |
+
with Image.open(sys.argv[1]) as im:
|
| 399 |
+
im.save("out.png")
|
| 400 |
+
if sys.platform == "windows":
|
| 401 |
+
os.startfile("out.png")
|
.venv/lib/python3.12/site-packages/PIL/ImImagePlugin.py
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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 |
+
from ._util import DeferredError
|
| 35 |
+
|
| 36 |
+
# --------------------------------------------------------------------
|
| 37 |
+
# Standard tags
|
| 38 |
+
|
| 39 |
+
COMMENT = "Comment"
|
| 40 |
+
DATE = "Date"
|
| 41 |
+
EQUIPMENT = "Digitalization equipment"
|
| 42 |
+
FRAMES = "File size (no of images)"
|
| 43 |
+
LUT = "Lut"
|
| 44 |
+
NAME = "Name"
|
| 45 |
+
SCALE = "Scale (x,y)"
|
| 46 |
+
SIZE = "Image size (x*y)"
|
| 47 |
+
MODE = "Image type"
|
| 48 |
+
|
| 49 |
+
TAGS = {
|
| 50 |
+
COMMENT: 0,
|
| 51 |
+
DATE: 0,
|
| 52 |
+
EQUIPMENT: 0,
|
| 53 |
+
FRAMES: 0,
|
| 54 |
+
LUT: 0,
|
| 55 |
+
NAME: 0,
|
| 56 |
+
SCALE: 0,
|
| 57 |
+
SIZE: 0,
|
| 58 |
+
MODE: 0,
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
OPEN = {
|
| 62 |
+
# ifunc93/p3cfunc formats
|
| 63 |
+
"0 1 image": ("1", "1"),
|
| 64 |
+
"L 1 image": ("1", "1"),
|
| 65 |
+
"Greyscale image": ("L", "L"),
|
| 66 |
+
"Grayscale image": ("L", "L"),
|
| 67 |
+
"RGB image": ("RGB", "RGB;L"),
|
| 68 |
+
"RLB image": ("RGB", "RLB"),
|
| 69 |
+
"RYB image": ("RGB", "RLB"),
|
| 70 |
+
"B1 image": ("1", "1"),
|
| 71 |
+
"B2 image": ("P", "P;2"),
|
| 72 |
+
"B4 image": ("P", "P;4"),
|
| 73 |
+
"X 24 image": ("RGB", "RGB"),
|
| 74 |
+
"L 32 S image": ("I", "I;32"),
|
| 75 |
+
"L 32 F image": ("F", "F;32"),
|
| 76 |
+
# old p3cfunc formats
|
| 77 |
+
"RGB3 image": ("RGB", "RGB;T"),
|
| 78 |
+
"RYB3 image": ("RGB", "RYB;T"),
|
| 79 |
+
# extensions
|
| 80 |
+
"LA image": ("LA", "LA;L"),
|
| 81 |
+
"PA image": ("LA", "PA;L"),
|
| 82 |
+
"RGBA image": ("RGBA", "RGBA;L"),
|
| 83 |
+
"RGBX image": ("RGB", "RGBX;L"),
|
| 84 |
+
"CMYK image": ("CMYK", "CMYK;L"),
|
| 85 |
+
"YCC image": ("YCbCr", "YCbCr;L"),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# ifunc95 extensions
|
| 89 |
+
for i in ["8", "8S", "16", "16S", "32", "32F"]:
|
| 90 |
+
OPEN[f"L {i} image"] = ("F", f"F;{i}")
|
| 91 |
+
OPEN[f"L*{i} image"] = ("F", f"F;{i}")
|
| 92 |
+
for i in ["16", "16L", "16B"]:
|
| 93 |
+
OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
|
| 94 |
+
OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
|
| 95 |
+
for i in ["32S"]:
|
| 96 |
+
OPEN[f"L {i} image"] = ("I", f"I;{i}")
|
| 97 |
+
OPEN[f"L*{i} image"] = ("I", f"I;{i}")
|
| 98 |
+
for j in range(2, 33):
|
| 99 |
+
OPEN[f"L*{j} image"] = ("F", f"F;{j}")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# --------------------------------------------------------------------
|
| 103 |
+
# Read IM directory
|
| 104 |
+
|
| 105 |
+
split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def number(s: Any) -> float:
|
| 109 |
+
try:
|
| 110 |
+
return int(s)
|
| 111 |
+
except ValueError:
|
| 112 |
+
return float(s)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
##
|
| 116 |
+
# Image plugin for the IFUNC IM file format.
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class ImImageFile(ImageFile.ImageFile):
|
| 120 |
+
format = "IM"
|
| 121 |
+
format_description = "IFUNC Image Memory"
|
| 122 |
+
_close_exclusive_fp_after_loading = False
|
| 123 |
+
|
| 124 |
+
def _open(self) -> None:
|
| 125 |
+
# Quick rejection: if there's not an LF among the first
|
| 126 |
+
# 100 bytes, this is (probably) not a text header.
|
| 127 |
+
|
| 128 |
+
if b"\n" not in self.fp.read(100):
|
| 129 |
+
msg = "not an IM file"
|
| 130 |
+
raise SyntaxError(msg)
|
| 131 |
+
self.fp.seek(0)
|
| 132 |
+
|
| 133 |
+
n = 0
|
| 134 |
+
|
| 135 |
+
# Default values
|
| 136 |
+
self.info[MODE] = "L"
|
| 137 |
+
self.info[SIZE] = (512, 512)
|
| 138 |
+
self.info[FRAMES] = 1
|
| 139 |
+
|
| 140 |
+
self.rawmode = "L"
|
| 141 |
+
|
| 142 |
+
while True:
|
| 143 |
+
s = self.fp.read(1)
|
| 144 |
+
|
| 145 |
+
# Some versions of IFUNC uses \n\r instead of \r\n...
|
| 146 |
+
if s == b"\r":
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
if not s or s == b"\0" or s == b"\x1a":
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
# FIXME: this may read whole file if not a text file
|
| 153 |
+
s = s + self.fp.readline()
|
| 154 |
+
|
| 155 |
+
if len(s) > 100:
|
| 156 |
+
msg = "not an IM file"
|
| 157 |
+
raise SyntaxError(msg)
|
| 158 |
+
|
| 159 |
+
if s.endswith(b"\r\n"):
|
| 160 |
+
s = s[:-2]
|
| 161 |
+
elif s.endswith(b"\n"):
|
| 162 |
+
s = s[:-1]
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
m = split.match(s)
|
| 166 |
+
except re.error as e:
|
| 167 |
+
msg = "not an IM file"
|
| 168 |
+
raise SyntaxError(msg) from e
|
| 169 |
+
|
| 170 |
+
if m:
|
| 171 |
+
k, v = m.group(1, 2)
|
| 172 |
+
|
| 173 |
+
# Don't know if this is the correct encoding,
|
| 174 |
+
# but a decent guess (I guess)
|
| 175 |
+
k = k.decode("latin-1", "replace")
|
| 176 |
+
v = v.decode("latin-1", "replace")
|
| 177 |
+
|
| 178 |
+
# Convert value as appropriate
|
| 179 |
+
if k in [FRAMES, SCALE, SIZE]:
|
| 180 |
+
v = v.replace("*", ",")
|
| 181 |
+
v = tuple(map(number, v.split(",")))
|
| 182 |
+
if len(v) == 1:
|
| 183 |
+
v = v[0]
|
| 184 |
+
elif k == MODE and v in OPEN:
|
| 185 |
+
v, self.rawmode = OPEN[v]
|
| 186 |
+
|
| 187 |
+
# Add to dictionary. Note that COMMENT tags are
|
| 188 |
+
# combined into a list of strings.
|
| 189 |
+
if k == COMMENT:
|
| 190 |
+
if k in self.info:
|
| 191 |
+
self.info[k].append(v)
|
| 192 |
+
else:
|
| 193 |
+
self.info[k] = [v]
|
| 194 |
+
else:
|
| 195 |
+
self.info[k] = v
|
| 196 |
+
|
| 197 |
+
if k in TAGS:
|
| 198 |
+
n += 1
|
| 199 |
+
|
| 200 |
+
else:
|
| 201 |
+
msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
|
| 202 |
+
raise SyntaxError(msg)
|
| 203 |
+
|
| 204 |
+
if not n:
|
| 205 |
+
msg = "Not an IM file"
|
| 206 |
+
raise SyntaxError(msg)
|
| 207 |
+
|
| 208 |
+
# Basic attributes
|
| 209 |
+
self._size = self.info[SIZE]
|
| 210 |
+
self._mode = self.info[MODE]
|
| 211 |
+
|
| 212 |
+
# Skip forward to start of image data
|
| 213 |
+
while s and not s.startswith(b"\x1a"):
|
| 214 |
+
s = self.fp.read(1)
|
| 215 |
+
if not s:
|
| 216 |
+
msg = "File truncated"
|
| 217 |
+
raise SyntaxError(msg)
|
| 218 |
+
|
| 219 |
+
if LUT in self.info:
|
| 220 |
+
# convert lookup table to palette or lut attribute
|
| 221 |
+
palette = self.fp.read(768)
|
| 222 |
+
greyscale = 1 # greyscale palette
|
| 223 |
+
linear = 1 # linear greyscale palette
|
| 224 |
+
for i in range(256):
|
| 225 |
+
if palette[i] == palette[i + 256] == palette[i + 512]:
|
| 226 |
+
if palette[i] != i:
|
| 227 |
+
linear = 0
|
| 228 |
+
else:
|
| 229 |
+
greyscale = 0
|
| 230 |
+
if self.mode in ["L", "LA", "P", "PA"]:
|
| 231 |
+
if greyscale:
|
| 232 |
+
if not linear:
|
| 233 |
+
self.lut = list(palette[:256])
|
| 234 |
+
else:
|
| 235 |
+
if self.mode in ["L", "P"]:
|
| 236 |
+
self._mode = self.rawmode = "P"
|
| 237 |
+
elif self.mode in ["LA", "PA"]:
|
| 238 |
+
self._mode = "PA"
|
| 239 |
+
self.rawmode = "PA;L"
|
| 240 |
+
self.palette = ImagePalette.raw("RGB;L", palette)
|
| 241 |
+
elif self.mode == "RGB":
|
| 242 |
+
if not greyscale or not linear:
|
| 243 |
+
self.lut = list(palette)
|
| 244 |
+
|
| 245 |
+
self.frame = 0
|
| 246 |
+
|
| 247 |
+
self.__offset = offs = self.fp.tell()
|
| 248 |
+
|
| 249 |
+
self._fp = self.fp # FIXME: hack
|
| 250 |
+
|
| 251 |
+
if self.rawmode.startswith("F;"):
|
| 252 |
+
# ifunc95 formats
|
| 253 |
+
try:
|
| 254 |
+
# use bit decoder (if necessary)
|
| 255 |
+
bits = int(self.rawmode[2:])
|
| 256 |
+
if bits not in [8, 16, 32]:
|
| 257 |
+
self.tile = [
|
| 258 |
+
ImageFile._Tile(
|
| 259 |
+
"bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
|
| 260 |
+
)
|
| 261 |
+
]
|
| 262 |
+
return
|
| 263 |
+
except ValueError:
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
if self.rawmode in ["RGB;T", "RYB;T"]:
|
| 267 |
+
# Old LabEye/3PC files. Would be very surprised if anyone
|
| 268 |
+
# ever stumbled upon such a file ;-)
|
| 269 |
+
size = self.size[0] * self.size[1]
|
| 270 |
+
self.tile = [
|
| 271 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
|
| 272 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
|
| 273 |
+
ImageFile._Tile(
|
| 274 |
+
"raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
|
| 275 |
+
),
|
| 276 |
+
]
|
| 277 |
+
else:
|
| 278 |
+
# LabEye/IFUNC files
|
| 279 |
+
self.tile = [
|
| 280 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def n_frames(self) -> int:
|
| 285 |
+
return self.info[FRAMES]
|
| 286 |
+
|
| 287 |
+
@property
|
| 288 |
+
def is_animated(self) -> bool:
|
| 289 |
+
return self.info[FRAMES] > 1
|
| 290 |
+
|
| 291 |
+
def seek(self, frame: int) -> None:
|
| 292 |
+
if not self._seek_check(frame):
|
| 293 |
+
return
|
| 294 |
+
if isinstance(self._fp, DeferredError):
|
| 295 |
+
raise self._fp.ex
|
| 296 |
+
|
| 297 |
+
self.frame = frame
|
| 298 |
+
|
| 299 |
+
if self.mode == "1":
|
| 300 |
+
bits = 1
|
| 301 |
+
else:
|
| 302 |
+
bits = 8 * len(self.mode)
|
| 303 |
+
|
| 304 |
+
size = ((self.size[0] * bits + 7) // 8) * self.size[1]
|
| 305 |
+
offs = self.__offset + frame * size
|
| 306 |
+
|
| 307 |
+
self.fp = self._fp
|
| 308 |
+
|
| 309 |
+
self.tile = [
|
| 310 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
|
| 311 |
+
]
|
| 312 |
+
|
| 313 |
+
def tell(self) -> int:
|
| 314 |
+
return self.frame
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
#
|
| 318 |
+
# --------------------------------------------------------------------
|
| 319 |
+
# Save IM files
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
SAVE = {
|
| 323 |
+
# mode: (im type, raw mode)
|
| 324 |
+
"1": ("0 1", "1"),
|
| 325 |
+
"L": ("Greyscale", "L"),
|
| 326 |
+
"LA": ("LA", "LA;L"),
|
| 327 |
+
"P": ("Greyscale", "P"),
|
| 328 |
+
"PA": ("LA", "PA;L"),
|
| 329 |
+
"I": ("L 32S", "I;32S"),
|
| 330 |
+
"I;16": ("L 16", "I;16"),
|
| 331 |
+
"I;16L": ("L 16L", "I;16L"),
|
| 332 |
+
"I;16B": ("L 16B", "I;16B"),
|
| 333 |
+
"F": ("L 32F", "F;32F"),
|
| 334 |
+
"RGB": ("RGB", "RGB;L"),
|
| 335 |
+
"RGBA": ("RGBA", "RGBA;L"),
|
| 336 |
+
"RGBX": ("RGBX", "RGBX;L"),
|
| 337 |
+
"CMYK": ("CMYK", "CMYK;L"),
|
| 338 |
+
"YCbCr": ("YCC", "YCbCr;L"),
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 343 |
+
try:
|
| 344 |
+
image_type, rawmode = SAVE[im.mode]
|
| 345 |
+
except KeyError as e:
|
| 346 |
+
msg = f"Cannot save {im.mode} images as IM"
|
| 347 |
+
raise ValueError(msg) from e
|
| 348 |
+
|
| 349 |
+
frames = im.encoderinfo.get("frames", 1)
|
| 350 |
+
|
| 351 |
+
fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
|
| 352 |
+
if filename:
|
| 353 |
+
# Each line must be 100 characters or less,
|
| 354 |
+
# or: SyntaxError("not an IM file")
|
| 355 |
+
# 8 characters are used for "Name: " and "\r\n"
|
| 356 |
+
# Keep just the filename, ditch the potentially overlong path
|
| 357 |
+
if isinstance(filename, bytes):
|
| 358 |
+
filename = filename.decode("ascii")
|
| 359 |
+
name, ext = os.path.splitext(os.path.basename(filename))
|
| 360 |
+
name = "".join([name[: 92 - len(ext)], ext])
|
| 361 |
+
|
| 362 |
+
fp.write(f"Name: {name}\r\n".encode("ascii"))
|
| 363 |
+
fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))
|
| 364 |
+
fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
|
| 365 |
+
if im.mode in ["P", "PA"]:
|
| 366 |
+
fp.write(b"Lut: 1\r\n")
|
| 367 |
+
fp.write(b"\000" * (511 - fp.tell()) + b"\032")
|
| 368 |
+
if im.mode in ["P", "PA"]:
|
| 369 |
+
im_palette = im.im.getpalette("RGB", "RGB;L")
|
| 370 |
+
colors = len(im_palette) // 3
|
| 371 |
+
palette = b""
|
| 372 |
+
for i in range(3):
|
| 373 |
+
palette += im_palette[colors * i : colors * (i + 1)]
|
| 374 |
+
palette += b"\x00" * (256 - colors)
|
| 375 |
+
fp.write(palette) # 768 bytes
|
| 376 |
+
ImageFile._save(
|
| 377 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
#
|
| 382 |
+
# --------------------------------------------------------------------
|
| 383 |
+
# Registry
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
Image.register_open(ImImageFile.format, ImImageFile)
|
| 387 |
+
Image.register_save(ImImageFile.format, _save)
|
| 388 |
+
|
| 389 |
+
Image.register_extension(ImImageFile.format, ".im")
|
.venv/lib/python3.12/site-packages/PIL/Image.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.12/site-packages/PIL/ImageCms.py
ADDED
|
@@ -0,0 +1,1076 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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
|
| 29 |
+
from ._deprecate import deprecate
|
| 30 |
+
from ._typing import SupportsRead
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
from . import _imagingcms as core
|
| 34 |
+
|
| 35 |
+
_CmsProfileCompatible = Union[
|
| 36 |
+
str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile"
|
| 37 |
+
]
|
| 38 |
+
except ImportError as ex:
|
| 39 |
+
# Allow error import for doc purposes, but error out when accessing
|
| 40 |
+
# anything in core.
|
| 41 |
+
from ._util import DeferredError
|
| 42 |
+
|
| 43 |
+
core = DeferredError.new(ex)
|
| 44 |
+
|
| 45 |
+
_DESCRIPTION = """
|
| 46 |
+
pyCMS
|
| 47 |
+
|
| 48 |
+
a Python / PIL interface to the littleCMS ICC Color Management System
|
| 49 |
+
Copyright (C) 2002-2003 Kevin Cazabon
|
| 50 |
+
kevin@cazabon.com
|
| 51 |
+
https://www.cazabon.com
|
| 52 |
+
|
| 53 |
+
pyCMS home page: https://www.cazabon.com/pyCMS
|
| 54 |
+
littleCMS home page: https://www.littlecms.com
|
| 55 |
+
(littleCMS is Copyright (C) 1998-2001 Marti Maria)
|
| 56 |
+
|
| 57 |
+
Originally released under LGPL. Graciously donated to PIL in
|
| 58 |
+
March 2009, for distribution under the standard PIL license
|
| 59 |
+
|
| 60 |
+
The pyCMS.py module provides a "clean" interface between Python/PIL and
|
| 61 |
+
pyCMSdll, taking care of some of the more complex handling of the direct
|
| 62 |
+
pyCMSdll functions, as well as error-checking and making sure that all
|
| 63 |
+
relevant data is kept together.
|
| 64 |
+
|
| 65 |
+
While it is possible to call pyCMSdll functions directly, it's not highly
|
| 66 |
+
recommended.
|
| 67 |
+
|
| 68 |
+
Version History:
|
| 69 |
+
|
| 70 |
+
1.0.0 pil Oct 2013 Port to LCMS 2.
|
| 71 |
+
|
| 72 |
+
0.1.0 pil mod March 10, 2009
|
| 73 |
+
|
| 74 |
+
Renamed display profile to proof profile. The proof
|
| 75 |
+
profile is the profile of the device that is being
|
| 76 |
+
simulated, not the profile of the device which is
|
| 77 |
+
actually used to display/print the final simulation
|
| 78 |
+
(that'd be the output profile) - also see LCMSAPI.txt
|
| 79 |
+
input colorspace -> using 'renderingIntent' -> proof
|
| 80 |
+
colorspace -> using 'proofRenderingIntent' -> output
|
| 81 |
+
colorspace
|
| 82 |
+
|
| 83 |
+
Added LCMS FLAGS support.
|
| 84 |
+
Added FLAGS["SOFTPROOFING"] as default flag for
|
| 85 |
+
buildProofTransform (otherwise the proof profile/intent
|
| 86 |
+
would be ignored).
|
| 87 |
+
|
| 88 |
+
0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
|
| 89 |
+
|
| 90 |
+
0.0.2 alpha Jan 6, 2002
|
| 91 |
+
|
| 92 |
+
Added try/except statements around type() checks of
|
| 93 |
+
potential CObjects... Python won't let you use type()
|
| 94 |
+
on them, and raises a TypeError (stupid, if you ask
|
| 95 |
+
me!)
|
| 96 |
+
|
| 97 |
+
Added buildProofTransformFromOpenProfiles() function.
|
| 98 |
+
Additional fixes in DLL, see DLL code for details.
|
| 99 |
+
|
| 100 |
+
0.0.1 alpha first public release, Dec. 26, 2002
|
| 101 |
+
|
| 102 |
+
Known to-do list with current version (of Python interface, not pyCMSdll):
|
| 103 |
+
|
| 104 |
+
none
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
_VERSION = "1.0.0 pil"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# --------------------------------------------------------------------.
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
#
|
| 115 |
+
# intent/direction values
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Intent(IntEnum):
|
| 119 |
+
PERCEPTUAL = 0
|
| 120 |
+
RELATIVE_COLORIMETRIC = 1
|
| 121 |
+
SATURATION = 2
|
| 122 |
+
ABSOLUTE_COLORIMETRIC = 3
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Direction(IntEnum):
|
| 126 |
+
INPUT = 0
|
| 127 |
+
OUTPUT = 1
|
| 128 |
+
PROOF = 2
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
#
|
| 132 |
+
# flags
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class Flags(IntFlag):
|
| 136 |
+
"""Flags and documentation are taken from ``lcms2.h``."""
|
| 137 |
+
|
| 138 |
+
NONE = 0
|
| 139 |
+
NOCACHE = 0x0040
|
| 140 |
+
"""Inhibit 1-pixel cache"""
|
| 141 |
+
NOOPTIMIZE = 0x0100
|
| 142 |
+
"""Inhibit optimizations"""
|
| 143 |
+
NULLTRANSFORM = 0x0200
|
| 144 |
+
"""Don't transform anyway"""
|
| 145 |
+
GAMUTCHECK = 0x1000
|
| 146 |
+
"""Out of Gamut alarm"""
|
| 147 |
+
SOFTPROOFING = 0x4000
|
| 148 |
+
"""Do softproofing"""
|
| 149 |
+
BLACKPOINTCOMPENSATION = 0x2000
|
| 150 |
+
NOWHITEONWHITEFIXUP = 0x0004
|
| 151 |
+
"""Don't fix scum dot"""
|
| 152 |
+
HIGHRESPRECALC = 0x0400
|
| 153 |
+
"""Use more memory to give better accuracy"""
|
| 154 |
+
LOWRESPRECALC = 0x0800
|
| 155 |
+
"""Use less memory to minimize resources"""
|
| 156 |
+
# this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
|
| 157 |
+
USE_8BITS_DEVICELINK = 0x0008
|
| 158 |
+
"""Create 8 bits devicelinks"""
|
| 159 |
+
GUESSDEVICECLASS = 0x0020
|
| 160 |
+
"""Guess device class (for ``transform2devicelink``)"""
|
| 161 |
+
KEEP_SEQUENCE = 0x0080
|
| 162 |
+
"""Keep profile sequence for devicelink creation"""
|
| 163 |
+
FORCE_CLUT = 0x0002
|
| 164 |
+
"""Force CLUT optimization"""
|
| 165 |
+
CLUT_POST_LINEARIZATION = 0x0001
|
| 166 |
+
"""create postlinearization tables if possible"""
|
| 167 |
+
CLUT_PRE_LINEARIZATION = 0x0010
|
| 168 |
+
"""create prelinearization tables if possible"""
|
| 169 |
+
NONEGATIVES = 0x8000
|
| 170 |
+
"""Prevent negative numbers in floating point transforms"""
|
| 171 |
+
COPY_ALPHA = 0x04000000
|
| 172 |
+
"""Alpha channels are copied on ``cmsDoTransform()``"""
|
| 173 |
+
NODEFAULTRESOURCEDEF = 0x01000000
|
| 174 |
+
|
| 175 |
+
_GRIDPOINTS_1 = 1 << 16
|
| 176 |
+
_GRIDPOINTS_2 = 2 << 16
|
| 177 |
+
_GRIDPOINTS_4 = 4 << 16
|
| 178 |
+
_GRIDPOINTS_8 = 8 << 16
|
| 179 |
+
_GRIDPOINTS_16 = 16 << 16
|
| 180 |
+
_GRIDPOINTS_32 = 32 << 16
|
| 181 |
+
_GRIDPOINTS_64 = 64 << 16
|
| 182 |
+
_GRIDPOINTS_128 = 128 << 16
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def GRIDPOINTS(n: int) -> Flags:
|
| 186 |
+
"""
|
| 187 |
+
Fine-tune control over number of gridpoints
|
| 188 |
+
|
| 189 |
+
:param n: :py:class:`int` in range ``0 <= n <= 255``
|
| 190 |
+
"""
|
| 191 |
+
return Flags.NONE | ((n & 0xFF) << 16)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
_MAX_FLAG = reduce(operator.or_, Flags)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
_FLAGS = {
|
| 198 |
+
"MATRIXINPUT": 1,
|
| 199 |
+
"MATRIXOUTPUT": 2,
|
| 200 |
+
"MATRIXONLY": (1 | 2),
|
| 201 |
+
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
|
| 202 |
+
# Don't create prelinearization tables on precalculated transforms
|
| 203 |
+
# (internal use):
|
| 204 |
+
"NOPRELINEARIZATION": 16,
|
| 205 |
+
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
|
| 206 |
+
"NOTCACHE": 64, # Inhibit 1-pixel cache
|
| 207 |
+
"NOTPRECALC": 256,
|
| 208 |
+
"NULLTRANSFORM": 512, # Don't transform anyway
|
| 209 |
+
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
|
| 210 |
+
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
|
| 211 |
+
"WHITEBLACKCOMPENSATION": 8192,
|
| 212 |
+
"BLACKPOINTCOMPENSATION": 8192,
|
| 213 |
+
"GAMUTCHECK": 4096, # Out of Gamut alarm
|
| 214 |
+
"SOFTPROOFING": 16384, # Do softproofing
|
| 215 |
+
"PRESERVEBLACK": 32768, # Black preservation
|
| 216 |
+
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
|
| 217 |
+
"GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# --------------------------------------------------------------------.
|
| 222 |
+
# Experimental PIL-level API
|
| 223 |
+
# --------------------------------------------------------------------.
|
| 224 |
+
|
| 225 |
+
##
|
| 226 |
+
# Profile.
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class ImageCmsProfile:
|
| 230 |
+
def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
|
| 231 |
+
"""
|
| 232 |
+
:param profile: Either a string representing a filename,
|
| 233 |
+
a file like object containing a profile or a
|
| 234 |
+
low-level profile object
|
| 235 |
+
|
| 236 |
+
"""
|
| 237 |
+
self.filename: str | None = None
|
| 238 |
+
|
| 239 |
+
if isinstance(profile, str):
|
| 240 |
+
if sys.platform == "win32":
|
| 241 |
+
profile_bytes_path = profile.encode()
|
| 242 |
+
try:
|
| 243 |
+
profile_bytes_path.decode("ascii")
|
| 244 |
+
except UnicodeDecodeError:
|
| 245 |
+
with open(profile, "rb") as f:
|
| 246 |
+
self.profile = core.profile_frombytes(f.read())
|
| 247 |
+
return
|
| 248 |
+
self.filename = profile
|
| 249 |
+
self.profile = core.profile_open(profile)
|
| 250 |
+
elif hasattr(profile, "read"):
|
| 251 |
+
self.profile = core.profile_frombytes(profile.read())
|
| 252 |
+
elif isinstance(profile, core.CmsProfile):
|
| 253 |
+
self.profile = profile
|
| 254 |
+
else:
|
| 255 |
+
msg = "Invalid type for Profile" # type: ignore[unreachable]
|
| 256 |
+
raise TypeError(msg)
|
| 257 |
+
|
| 258 |
+
def __getattr__(self, name: str) -> Any:
|
| 259 |
+
if name in ("product_name", "product_info"):
|
| 260 |
+
deprecate(f"ImageCms.ImageCmsProfile.{name}", 13)
|
| 261 |
+
return None
|
| 262 |
+
msg = f"'{self.__class__.__name__}' object has no attribute '{name}'"
|
| 263 |
+
raise AttributeError(msg)
|
| 264 |
+
|
| 265 |
+
def tobytes(self) -> bytes:
|
| 266 |
+
"""
|
| 267 |
+
Returns the profile in a format suitable for embedding in
|
| 268 |
+
saved images.
|
| 269 |
+
|
| 270 |
+
:returns: a bytes object containing the ICC profile.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
return core.profile_tobytes(self.profile)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class ImageCmsTransform(Image.ImagePointHandler):
|
| 277 |
+
"""
|
| 278 |
+
Transform. This can be used with the procedural API, or with the standard
|
| 279 |
+
:py:func:`~PIL.Image.Image.point` method.
|
| 280 |
+
|
| 281 |
+
Will return the output profile in the ``output.info['icc_profile']``.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
def __init__(
|
| 285 |
+
self,
|
| 286 |
+
input: ImageCmsProfile,
|
| 287 |
+
output: ImageCmsProfile,
|
| 288 |
+
input_mode: str,
|
| 289 |
+
output_mode: str,
|
| 290 |
+
intent: Intent = Intent.PERCEPTUAL,
|
| 291 |
+
proof: ImageCmsProfile | None = None,
|
| 292 |
+
proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 293 |
+
flags: Flags = Flags.NONE,
|
| 294 |
+
):
|
| 295 |
+
if proof is None:
|
| 296 |
+
self.transform = core.buildTransform(
|
| 297 |
+
input.profile, output.profile, input_mode, output_mode, intent, flags
|
| 298 |
+
)
|
| 299 |
+
else:
|
| 300 |
+
self.transform = core.buildProofTransform(
|
| 301 |
+
input.profile,
|
| 302 |
+
output.profile,
|
| 303 |
+
proof.profile,
|
| 304 |
+
input_mode,
|
| 305 |
+
output_mode,
|
| 306 |
+
intent,
|
| 307 |
+
proof_intent,
|
| 308 |
+
flags,
|
| 309 |
+
)
|
| 310 |
+
# Note: inputMode and outputMode are for pyCMS compatibility only
|
| 311 |
+
self.input_mode = self.inputMode = input_mode
|
| 312 |
+
self.output_mode = self.outputMode = output_mode
|
| 313 |
+
|
| 314 |
+
self.output_profile = output
|
| 315 |
+
|
| 316 |
+
def point(self, im: Image.Image) -> Image.Image:
|
| 317 |
+
return self.apply(im)
|
| 318 |
+
|
| 319 |
+
def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
|
| 320 |
+
if imOut is None:
|
| 321 |
+
imOut = Image.new(self.output_mode, im.size, None)
|
| 322 |
+
self.transform.apply(im.getim(), imOut.getim())
|
| 323 |
+
imOut.info["icc_profile"] = self.output_profile.tobytes()
|
| 324 |
+
return imOut
|
| 325 |
+
|
| 326 |
+
def apply_in_place(self, im: Image.Image) -> Image.Image:
|
| 327 |
+
if im.mode != self.output_mode:
|
| 328 |
+
msg = "mode mismatch"
|
| 329 |
+
raise ValueError(msg) # wrong output mode
|
| 330 |
+
self.transform.apply(im.getim(), im.getim())
|
| 331 |
+
im.info["icc_profile"] = self.output_profile.tobytes()
|
| 332 |
+
return im
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
|
| 336 |
+
"""
|
| 337 |
+
(experimental) Fetches the profile for the current display device.
|
| 338 |
+
|
| 339 |
+
:returns: ``None`` if the profile is not known.
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
if sys.platform != "win32":
|
| 343 |
+
return None
|
| 344 |
+
|
| 345 |
+
from . import ImageWin # type: ignore[unused-ignore, unreachable]
|
| 346 |
+
|
| 347 |
+
if isinstance(handle, ImageWin.HDC):
|
| 348 |
+
profile = core.get_display_profile_win32(int(handle), 1)
|
| 349 |
+
else:
|
| 350 |
+
profile = core.get_display_profile_win32(int(handle or 0))
|
| 351 |
+
if profile is None:
|
| 352 |
+
return None
|
| 353 |
+
return ImageCmsProfile(profile)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# --------------------------------------------------------------------.
|
| 357 |
+
# pyCMS compatible layer
|
| 358 |
+
# --------------------------------------------------------------------.
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class PyCMSError(Exception):
|
| 362 |
+
"""(pyCMS) Exception class.
|
| 363 |
+
This is used for all errors in the pyCMS API."""
|
| 364 |
+
|
| 365 |
+
pass
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def profileToProfile(
|
| 369 |
+
im: Image.Image,
|
| 370 |
+
inputProfile: _CmsProfileCompatible,
|
| 371 |
+
outputProfile: _CmsProfileCompatible,
|
| 372 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 373 |
+
outputMode: str | None = None,
|
| 374 |
+
inPlace: bool = False,
|
| 375 |
+
flags: Flags = Flags.NONE,
|
| 376 |
+
) -> Image.Image | None:
|
| 377 |
+
"""
|
| 378 |
+
(pyCMS) Applies an ICC transformation to a given image, mapping from
|
| 379 |
+
``inputProfile`` to ``outputProfile``.
|
| 380 |
+
|
| 381 |
+
If the input or output profiles specified are not valid filenames, a
|
| 382 |
+
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
|
| 383 |
+
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
|
| 384 |
+
If an error occurs during application of the profiles,
|
| 385 |
+
a :exc:`PyCMSError` will be raised.
|
| 386 |
+
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
|
| 387 |
+
a :exc:`PyCMSError` will be raised.
|
| 388 |
+
|
| 389 |
+
This function applies an ICC transformation to im from ``inputProfile``'s
|
| 390 |
+
color space to ``outputProfile``'s color space using the specified rendering
|
| 391 |
+
intent to decide how to handle out-of-gamut colors.
|
| 392 |
+
|
| 393 |
+
``outputMode`` can be used to specify that a color mode conversion is to
|
| 394 |
+
be done using these profiles, but the specified profiles must be able
|
| 395 |
+
to handle that mode. I.e., if converting im from RGB to CMYK using
|
| 396 |
+
profiles, the input profile must handle RGB data, and the output
|
| 397 |
+
profile must handle CMYK data.
|
| 398 |
+
|
| 399 |
+
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
|
| 400 |
+
or Image.open(...), etc.)
|
| 401 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 402 |
+
profile you wish to use for this image, or a profile object
|
| 403 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 404 |
+
profile you wish to use for this image, or a profile object
|
| 405 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 406 |
+
wish to use for the transform
|
| 407 |
+
|
| 408 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 409 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 410 |
+
ImageCms.Intent.SATURATION = 2
|
| 411 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 412 |
+
|
| 413 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 414 |
+
they do.
|
| 415 |
+
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
|
| 416 |
+
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
|
| 417 |
+
MUST be the same mode as the input, or omitted completely. If
|
| 418 |
+
omitted, the outputMode will be the same as the mode of the input
|
| 419 |
+
image (im.mode)
|
| 420 |
+
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
|
| 421 |
+
and ``None`` is returned. If ``False`` (default), a new
|
| 422 |
+
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
|
| 423 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 424 |
+
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
|
| 425 |
+
the value of ``inPlace``
|
| 426 |
+
:exception PyCMSError:
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
if outputMode is None:
|
| 430 |
+
outputMode = im.mode
|
| 431 |
+
|
| 432 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 433 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 434 |
+
raise PyCMSError(msg)
|
| 435 |
+
|
| 436 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 437 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 438 |
+
raise PyCMSError(msg)
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 442 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 443 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 444 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 445 |
+
transform = ImageCmsTransform(
|
| 446 |
+
inputProfile,
|
| 447 |
+
outputProfile,
|
| 448 |
+
im.mode,
|
| 449 |
+
outputMode,
|
| 450 |
+
renderingIntent,
|
| 451 |
+
flags=flags,
|
| 452 |
+
)
|
| 453 |
+
if inPlace:
|
| 454 |
+
transform.apply_in_place(im)
|
| 455 |
+
imOut = None
|
| 456 |
+
else:
|
| 457 |
+
imOut = transform.apply(im)
|
| 458 |
+
except (OSError, TypeError, ValueError) as v:
|
| 459 |
+
raise PyCMSError(v) from v
|
| 460 |
+
|
| 461 |
+
return imOut
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def getOpenProfile(
|
| 465 |
+
profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
|
| 466 |
+
) -> ImageCmsProfile:
|
| 467 |
+
"""
|
| 468 |
+
(pyCMS) Opens an ICC profile file.
|
| 469 |
+
|
| 470 |
+
The PyCMSProfile object can be passed back into pyCMS for use in creating
|
| 471 |
+
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
|
| 472 |
+
|
| 473 |
+
If ``profileFilename`` is not a valid filename for an ICC profile,
|
| 474 |
+
a :exc:`PyCMSError` will be raised.
|
| 475 |
+
|
| 476 |
+
:param profileFilename: String, as a valid filename path to the ICC profile
|
| 477 |
+
you wish to open, or a file-like object.
|
| 478 |
+
:returns: A CmsProfile class object.
|
| 479 |
+
:exception PyCMSError:
|
| 480 |
+
"""
|
| 481 |
+
|
| 482 |
+
try:
|
| 483 |
+
return ImageCmsProfile(profileFilename)
|
| 484 |
+
except (OSError, TypeError, ValueError) as v:
|
| 485 |
+
raise PyCMSError(v) from v
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def buildTransform(
|
| 489 |
+
inputProfile: _CmsProfileCompatible,
|
| 490 |
+
outputProfile: _CmsProfileCompatible,
|
| 491 |
+
inMode: str,
|
| 492 |
+
outMode: str,
|
| 493 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 494 |
+
flags: Flags = Flags.NONE,
|
| 495 |
+
) -> ImageCmsTransform:
|
| 496 |
+
"""
|
| 497 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 498 |
+
``outputProfile``. Use applyTransform to apply the transform to a given
|
| 499 |
+
image.
|
| 500 |
+
|
| 501 |
+
If the input or output profiles specified are not valid filenames, a
|
| 502 |
+
:exc:`PyCMSError` will be raised. If an error occurs during creation
|
| 503 |
+
of the transform, a :exc:`PyCMSError` will be raised.
|
| 504 |
+
|
| 505 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 506 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 507 |
+
|
| 508 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 509 |
+
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
|
| 510 |
+
with out-of-gamut colors. It will ONLY work for converting images that
|
| 511 |
+
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
|
| 512 |
+
i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 513 |
+
|
| 514 |
+
Building the transform is a fair part of the overhead in
|
| 515 |
+
ImageCms.profileToProfile(), so if you're planning on converting multiple
|
| 516 |
+
images using the same input/output settings, this can save you time.
|
| 517 |
+
Once you have a transform object, it can be used with
|
| 518 |
+
ImageCms.applyProfile() to convert images without the need to re-compute
|
| 519 |
+
the lookup table for the transform.
|
| 520 |
+
|
| 521 |
+
The reason pyCMS returns a class object rather than a handle directly
|
| 522 |
+
to the transform is that it needs to keep track of the PIL input/output
|
| 523 |
+
modes that the transform is meant for. These attributes are stored in
|
| 524 |
+
the ``inMode`` and ``outMode`` attributes of the object (which can be
|
| 525 |
+
manually overridden if you really want to, but I don't know of any
|
| 526 |
+
time that would be of use, or would even work).
|
| 527 |
+
|
| 528 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 529 |
+
profile you wish to use for this transform, or a profile object
|
| 530 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 531 |
+
profile you wish to use for this transform, or a profile object
|
| 532 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 533 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 534 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 535 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 536 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 537 |
+
wish to use for the transform
|
| 538 |
+
|
| 539 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 540 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 541 |
+
ImageCms.Intent.SATURATION = 2
|
| 542 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 543 |
+
|
| 544 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 545 |
+
they do.
|
| 546 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 547 |
+
:returns: A CmsTransform class object.
|
| 548 |
+
:exception PyCMSError:
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 552 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 553 |
+
raise PyCMSError(msg)
|
| 554 |
+
|
| 555 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 556 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 557 |
+
raise PyCMSError(msg)
|
| 558 |
+
|
| 559 |
+
try:
|
| 560 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 561 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 562 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 563 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 564 |
+
return ImageCmsTransform(
|
| 565 |
+
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
|
| 566 |
+
)
|
| 567 |
+
except (OSError, TypeError, ValueError) as v:
|
| 568 |
+
raise PyCMSError(v) from v
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def buildProofTransform(
|
| 572 |
+
inputProfile: _CmsProfileCompatible,
|
| 573 |
+
outputProfile: _CmsProfileCompatible,
|
| 574 |
+
proofProfile: _CmsProfileCompatible,
|
| 575 |
+
inMode: str,
|
| 576 |
+
outMode: str,
|
| 577 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 578 |
+
proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 579 |
+
flags: Flags = Flags.SOFTPROOFING,
|
| 580 |
+
) -> ImageCmsTransform:
|
| 581 |
+
"""
|
| 582 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 583 |
+
``outputProfile``, but tries to simulate the result that would be
|
| 584 |
+
obtained on the ``proofProfile`` device.
|
| 585 |
+
|
| 586 |
+
If the input, output, or proof profiles specified are not valid
|
| 587 |
+
filenames, a :exc:`PyCMSError` will be raised.
|
| 588 |
+
|
| 589 |
+
If an error occurs during creation of the transform,
|
| 590 |
+
a :exc:`PyCMSError` will be raised.
|
| 591 |
+
|
| 592 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 593 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 594 |
+
|
| 595 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 596 |
+
to the ``outputProfile``, but tries to simulate the result that would be
|
| 597 |
+
obtained on the ``proofProfile`` device using ``renderingIntent`` and
|
| 598 |
+
``proofRenderingIntent`` to determine what to do with out-of-gamut
|
| 599 |
+
colors. This is known as "soft-proofing". It will ONLY work for
|
| 600 |
+
converting images that are in ``inMode`` to images that are in outMode
|
| 601 |
+
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 602 |
+
|
| 603 |
+
Usage of the resulting transform object is exactly the same as with
|
| 604 |
+
ImageCms.buildTransform().
|
| 605 |
+
|
| 606 |
+
Proof profiling is generally used when using an output device to get a
|
| 607 |
+
good idea of what the final printed/displayed image would look like on
|
| 608 |
+
the ``proofProfile`` device when it's quicker and easier to use the
|
| 609 |
+
output device for judging color. Generally, this means that the
|
| 610 |
+
output device is a monitor, or a dye-sub printer (etc.), and the simulated
|
| 611 |
+
device is something more expensive, complicated, or time consuming
|
| 612 |
+
(making it difficult to make a real print for color judgement purposes).
|
| 613 |
+
|
| 614 |
+
Soft-proofing basically functions by adjusting the colors on the
|
| 615 |
+
output device to match the colors of the device being simulated. However,
|
| 616 |
+
when the simulated device has a much wider gamut than the output
|
| 617 |
+
device, you may obtain marginal results.
|
| 618 |
+
|
| 619 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 620 |
+
profile you wish to use for this transform, or a profile object
|
| 621 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 622 |
+
(monitor, usually) profile you wish to use for this transform, or a
|
| 623 |
+
profile object
|
| 624 |
+
:param proofProfile: String, as a valid filename path to the ICC proof
|
| 625 |
+
profile you wish to use for this transform, or a profile object
|
| 626 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 627 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 628 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 629 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 630 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 631 |
+
wish to use for the input->proof (simulated) transform
|
| 632 |
+
|
| 633 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 634 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 635 |
+
ImageCms.Intent.SATURATION = 2
|
| 636 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 637 |
+
|
| 638 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 639 |
+
they do.
|
| 640 |
+
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
|
| 641 |
+
you wish to use for proof->output transform
|
| 642 |
+
|
| 643 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 644 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 645 |
+
ImageCms.Intent.SATURATION = 2
|
| 646 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 647 |
+
|
| 648 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 649 |
+
they do.
|
| 650 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 651 |
+
:returns: A CmsTransform class object.
|
| 652 |
+
:exception PyCMSError:
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 656 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 657 |
+
raise PyCMSError(msg)
|
| 658 |
+
|
| 659 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 660 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 661 |
+
raise PyCMSError(msg)
|
| 662 |
+
|
| 663 |
+
try:
|
| 664 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 665 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 666 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 667 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 668 |
+
if not isinstance(proofProfile, ImageCmsProfile):
|
| 669 |
+
proofProfile = ImageCmsProfile(proofProfile)
|
| 670 |
+
return ImageCmsTransform(
|
| 671 |
+
inputProfile,
|
| 672 |
+
outputProfile,
|
| 673 |
+
inMode,
|
| 674 |
+
outMode,
|
| 675 |
+
renderingIntent,
|
| 676 |
+
proofProfile,
|
| 677 |
+
proofRenderingIntent,
|
| 678 |
+
flags,
|
| 679 |
+
)
|
| 680 |
+
except (OSError, TypeError, ValueError) as v:
|
| 681 |
+
raise PyCMSError(v) from v
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
buildTransformFromOpenProfiles = buildTransform
|
| 685 |
+
buildProofTransformFromOpenProfiles = buildProofTransform
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def applyTransform(
|
| 689 |
+
im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
|
| 690 |
+
) -> Image.Image | None:
|
| 691 |
+
"""
|
| 692 |
+
(pyCMS) Applies a transform to a given image.
|
| 693 |
+
|
| 694 |
+
If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
|
| 695 |
+
|
| 696 |
+
If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
|
| 697 |
+
:exc:`PyCMSError` is raised.
|
| 698 |
+
|
| 699 |
+
If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
|
| 700 |
+
supported by pyCMSdll or the profiles you used for the transform, a
|
| 701 |
+
:exc:`PyCMSError` is raised.
|
| 702 |
+
|
| 703 |
+
If an error occurs while the transform is being applied,
|
| 704 |
+
a :exc:`PyCMSError` is raised.
|
| 705 |
+
|
| 706 |
+
This function applies a pre-calculated transform (from
|
| 707 |
+
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
|
| 708 |
+
to an image. The transform can be used for multiple images, saving
|
| 709 |
+
considerable calculation time if doing the same conversion multiple times.
|
| 710 |
+
|
| 711 |
+
If you want to modify im in-place instead of receiving a new image as
|
| 712 |
+
the return value, set ``inPlace`` to ``True``. This can only be done if
|
| 713 |
+
``transform.input_mode`` and ``transform.output_mode`` are the same, because we
|
| 714 |
+
can't change the mode in-place (the buffer sizes for some modes are
|
| 715 |
+
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
|
| 716 |
+
object of the same dimensions in mode ``transform.output_mode``.
|
| 717 |
+
|
| 718 |
+
:param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
|
| 719 |
+
as the ``input_mode`` supported by the transform.
|
| 720 |
+
:param transform: A valid CmsTransform class object
|
| 721 |
+
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
|
| 722 |
+
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
|
| 723 |
+
transform applied is returned (and ``im`` is not changed). The default is
|
| 724 |
+
``False``.
|
| 725 |
+
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
|
| 726 |
+
depending on the value of ``inPlace``. The profile will be returned in
|
| 727 |
+
the image's ``info['icc_profile']``.
|
| 728 |
+
:exception PyCMSError:
|
| 729 |
+
"""
|
| 730 |
+
|
| 731 |
+
try:
|
| 732 |
+
if inPlace:
|
| 733 |
+
transform.apply_in_place(im)
|
| 734 |
+
imOut = None
|
| 735 |
+
else:
|
| 736 |
+
imOut = transform.apply(im)
|
| 737 |
+
except (TypeError, ValueError) as v:
|
| 738 |
+
raise PyCMSError(v) from v
|
| 739 |
+
|
| 740 |
+
return imOut
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def createProfile(
|
| 744 |
+
colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
|
| 745 |
+
) -> core.CmsProfile:
|
| 746 |
+
"""
|
| 747 |
+
(pyCMS) Creates a profile.
|
| 748 |
+
|
| 749 |
+
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
|
| 750 |
+
a :exc:`PyCMSError` is raised.
|
| 751 |
+
|
| 752 |
+
If using LAB and ``colorTemp`` is not a positive integer,
|
| 753 |
+
a :exc:`PyCMSError` is raised.
|
| 754 |
+
|
| 755 |
+
If an error occurs while creating the profile,
|
| 756 |
+
a :exc:`PyCMSError` is raised.
|
| 757 |
+
|
| 758 |
+
Use this function to create common profiles on-the-fly instead of
|
| 759 |
+
having to supply a profile on disk and knowing the path to it. It
|
| 760 |
+
returns a normal CmsProfile object that can be passed to
|
| 761 |
+
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
|
| 762 |
+
to images.
|
| 763 |
+
|
| 764 |
+
:param colorSpace: String, the color space of the profile you wish to
|
| 765 |
+
create.
|
| 766 |
+
Currently only "LAB", "XYZ", and "sRGB" are supported.
|
| 767 |
+
:param colorTemp: Positive number for the white point for the profile, in
|
| 768 |
+
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
|
| 769 |
+
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
|
| 770 |
+
profiles, and is ignored for XYZ and sRGB.
|
| 771 |
+
:returns: A CmsProfile class object
|
| 772 |
+
:exception PyCMSError:
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
|
| 776 |
+
msg = (
|
| 777 |
+
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
|
| 778 |
+
)
|
| 779 |
+
raise PyCMSError(msg)
|
| 780 |
+
|
| 781 |
+
if colorSpace == "LAB":
|
| 782 |
+
try:
|
| 783 |
+
colorTemp = float(colorTemp)
|
| 784 |
+
except (TypeError, ValueError) as e:
|
| 785 |
+
msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
|
| 786 |
+
raise PyCMSError(msg) from e
|
| 787 |
+
|
| 788 |
+
try:
|
| 789 |
+
return core.createProfile(colorSpace, colorTemp)
|
| 790 |
+
except (TypeError, ValueError) as v:
|
| 791 |
+
raise PyCMSError(v) from v
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def getProfileName(profile: _CmsProfileCompatible) -> str:
|
| 795 |
+
"""
|
| 796 |
+
|
| 797 |
+
(pyCMS) Gets the internal product name for the given profile.
|
| 798 |
+
|
| 799 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 800 |
+
a :exc:`PyCMSError` is raised If an error occurs while trying
|
| 801 |
+
to obtain the name tag, a :exc:`PyCMSError` is raised.
|
| 802 |
+
|
| 803 |
+
Use this function to obtain the INTERNAL name of the profile (stored
|
| 804 |
+
in an ICC tag in the profile itself), usually the one used when the
|
| 805 |
+
profile was originally created. Sometimes this tag also contains
|
| 806 |
+
additional information supplied by the creator.
|
| 807 |
+
|
| 808 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 809 |
+
filename of an ICC profile.
|
| 810 |
+
:returns: A string containing the internal name of the profile as stored
|
| 811 |
+
in an ICC tag.
|
| 812 |
+
:exception PyCMSError:
|
| 813 |
+
"""
|
| 814 |
+
|
| 815 |
+
try:
|
| 816 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 817 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 818 |
+
profile = ImageCmsProfile(profile)
|
| 819 |
+
# do it in python, not c.
|
| 820 |
+
# // name was "%s - %s" (model, manufacturer) || Description ,
|
| 821 |
+
# // but if the Model and Manufacturer were the same or the model
|
| 822 |
+
# // was long, Just the model, in 1.x
|
| 823 |
+
model = profile.profile.model
|
| 824 |
+
manufacturer = profile.profile.manufacturer
|
| 825 |
+
|
| 826 |
+
if not (model or manufacturer):
|
| 827 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 828 |
+
if not manufacturer or (model and len(model) > 30):
|
| 829 |
+
return f"{model}\n"
|
| 830 |
+
return f"{model} - {manufacturer}\n"
|
| 831 |
+
|
| 832 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 833 |
+
raise PyCMSError(v) from v
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def getProfileInfo(profile: _CmsProfileCompatible) -> str:
|
| 837 |
+
"""
|
| 838 |
+
(pyCMS) Gets the internal product information for the given profile.
|
| 839 |
+
|
| 840 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 841 |
+
a :exc:`PyCMSError` is raised.
|
| 842 |
+
|
| 843 |
+
If an error occurs while trying to obtain the info tag,
|
| 844 |
+
a :exc:`PyCMSError` is raised.
|
| 845 |
+
|
| 846 |
+
Use this function to obtain the information stored in the profile's
|
| 847 |
+
info tag. This often contains details about the profile, and how it
|
| 848 |
+
was created, as supplied by the creator.
|
| 849 |
+
|
| 850 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 851 |
+
filename of an ICC profile.
|
| 852 |
+
:returns: A string containing the internal profile information stored in
|
| 853 |
+
an ICC tag.
|
| 854 |
+
:exception PyCMSError:
|
| 855 |
+
"""
|
| 856 |
+
|
| 857 |
+
try:
|
| 858 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 859 |
+
profile = ImageCmsProfile(profile)
|
| 860 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 861 |
+
# Python, not C. the white point bits weren't working well,
|
| 862 |
+
# so skipping.
|
| 863 |
+
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
|
| 864 |
+
description = profile.profile.profile_description
|
| 865 |
+
cpright = profile.profile.copyright
|
| 866 |
+
elements = [element for element in (description, cpright) if element]
|
| 867 |
+
return "\r\n\r\n".join(elements) + "\r\n\r\n"
|
| 868 |
+
|
| 869 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 870 |
+
raise PyCMSError(v) from v
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
|
| 874 |
+
"""
|
| 875 |
+
(pyCMS) Gets the copyright for the given profile.
|
| 876 |
+
|
| 877 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 878 |
+
:exc:`PyCMSError` is raised.
|
| 879 |
+
|
| 880 |
+
If an error occurs while trying to obtain the copyright tag,
|
| 881 |
+
a :exc:`PyCMSError` is raised.
|
| 882 |
+
|
| 883 |
+
Use this function to obtain the information stored in the profile's
|
| 884 |
+
copyright tag.
|
| 885 |
+
|
| 886 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 887 |
+
filename of an ICC profile.
|
| 888 |
+
:returns: A string containing the internal profile information stored in
|
| 889 |
+
an ICC tag.
|
| 890 |
+
:exception PyCMSError:
|
| 891 |
+
"""
|
| 892 |
+
try:
|
| 893 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 894 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 895 |
+
profile = ImageCmsProfile(profile)
|
| 896 |
+
return (profile.profile.copyright or "") + "\n"
|
| 897 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 898 |
+
raise PyCMSError(v) from v
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
|
| 902 |
+
"""
|
| 903 |
+
(pyCMS) Gets the manufacturer for the given profile.
|
| 904 |
+
|
| 905 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 906 |
+
:exc:`PyCMSError` is raised.
|
| 907 |
+
|
| 908 |
+
If an error occurs while trying to obtain the manufacturer tag, a
|
| 909 |
+
:exc:`PyCMSError` is raised.
|
| 910 |
+
|
| 911 |
+
Use this function to obtain the information stored in the profile's
|
| 912 |
+
manufacturer tag.
|
| 913 |
+
|
| 914 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 915 |
+
filename of an ICC profile.
|
| 916 |
+
:returns: A string containing the internal profile information stored in
|
| 917 |
+
an ICC tag.
|
| 918 |
+
:exception PyCMSError:
|
| 919 |
+
"""
|
| 920 |
+
try:
|
| 921 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 922 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 923 |
+
profile = ImageCmsProfile(profile)
|
| 924 |
+
return (profile.profile.manufacturer or "") + "\n"
|
| 925 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 926 |
+
raise PyCMSError(v) from v
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def getProfileModel(profile: _CmsProfileCompatible) -> str:
|
| 930 |
+
"""
|
| 931 |
+
(pyCMS) Gets the model for the given profile.
|
| 932 |
+
|
| 933 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 934 |
+
:exc:`PyCMSError` is raised.
|
| 935 |
+
|
| 936 |
+
If an error occurs while trying to obtain the model tag,
|
| 937 |
+
a :exc:`PyCMSError` is raised.
|
| 938 |
+
|
| 939 |
+
Use this function to obtain the information stored in the profile's
|
| 940 |
+
model tag.
|
| 941 |
+
|
| 942 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 943 |
+
filename of an ICC profile.
|
| 944 |
+
:returns: A string containing the internal profile information stored in
|
| 945 |
+
an ICC tag.
|
| 946 |
+
:exception PyCMSError:
|
| 947 |
+
"""
|
| 948 |
+
|
| 949 |
+
try:
|
| 950 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 951 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 952 |
+
profile = ImageCmsProfile(profile)
|
| 953 |
+
return (profile.profile.model or "") + "\n"
|
| 954 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 955 |
+
raise PyCMSError(v) from v
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
def getProfileDescription(profile: _CmsProfileCompatible) -> str:
|
| 959 |
+
"""
|
| 960 |
+
(pyCMS) Gets the description for the given profile.
|
| 961 |
+
|
| 962 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 963 |
+
:exc:`PyCMSError` is raised.
|
| 964 |
+
|
| 965 |
+
If an error occurs while trying to obtain the description tag,
|
| 966 |
+
a :exc:`PyCMSError` is raised.
|
| 967 |
+
|
| 968 |
+
Use this function to obtain the information stored in the profile's
|
| 969 |
+
description tag.
|
| 970 |
+
|
| 971 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 972 |
+
filename of an ICC profile.
|
| 973 |
+
:returns: A string containing the internal profile information stored in an
|
| 974 |
+
ICC tag.
|
| 975 |
+
:exception PyCMSError:
|
| 976 |
+
"""
|
| 977 |
+
|
| 978 |
+
try:
|
| 979 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 980 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 981 |
+
profile = ImageCmsProfile(profile)
|
| 982 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 983 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 984 |
+
raise PyCMSError(v) from v
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
|
| 988 |
+
"""
|
| 989 |
+
(pyCMS) Gets the default intent name for the given profile.
|
| 990 |
+
|
| 991 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 992 |
+
:exc:`PyCMSError` is raised.
|
| 993 |
+
|
| 994 |
+
If an error occurs while trying to obtain the default intent, a
|
| 995 |
+
:exc:`PyCMSError` is raised.
|
| 996 |
+
|
| 997 |
+
Use this function to determine the default (and usually best optimized)
|
| 998 |
+
rendering intent for this profile. Most profiles support multiple
|
| 999 |
+
rendering intents, but are intended mostly for one type of conversion.
|
| 1000 |
+
If you wish to use a different intent than returned, use
|
| 1001 |
+
ImageCms.isIntentSupported() to verify it will work first.
|
| 1002 |
+
|
| 1003 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1004 |
+
filename of an ICC profile.
|
| 1005 |
+
:returns: Integer 0-3 specifying the default rendering intent for this
|
| 1006 |
+
profile.
|
| 1007 |
+
|
| 1008 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1009 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1010 |
+
ImageCms.Intent.SATURATION = 2
|
| 1011 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1012 |
+
|
| 1013 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1014 |
+
they do.
|
| 1015 |
+
:exception PyCMSError:
|
| 1016 |
+
"""
|
| 1017 |
+
|
| 1018 |
+
try:
|
| 1019 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1020 |
+
profile = ImageCmsProfile(profile)
|
| 1021 |
+
return profile.profile.rendering_intent
|
| 1022 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1023 |
+
raise PyCMSError(v) from v
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def isIntentSupported(
|
| 1027 |
+
profile: _CmsProfileCompatible, intent: Intent, direction: Direction
|
| 1028 |
+
) -> Literal[-1, 1]:
|
| 1029 |
+
"""
|
| 1030 |
+
(pyCMS) Checks if a given intent is supported.
|
| 1031 |
+
|
| 1032 |
+
Use this function to verify that you can use your desired
|
| 1033 |
+
``intent`` with ``profile``, and that ``profile`` can be used for the
|
| 1034 |
+
input/output/proof profile as you desire.
|
| 1035 |
+
|
| 1036 |
+
Some profiles are created specifically for one "direction", can cannot
|
| 1037 |
+
be used for others. Some profiles can only be used for certain
|
| 1038 |
+
rendering intents, so it's best to either verify this before trying
|
| 1039 |
+
to create a transform with them (using this function), or catch the
|
| 1040 |
+
potential :exc:`PyCMSError` that will occur if they don't
|
| 1041 |
+
support the modes you select.
|
| 1042 |
+
|
| 1043 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1044 |
+
filename of an ICC profile.
|
| 1045 |
+
:param intent: Integer (0-3) specifying the rendering intent you wish to
|
| 1046 |
+
use with this profile
|
| 1047 |
+
|
| 1048 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1049 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1050 |
+
ImageCms.Intent.SATURATION = 2
|
| 1051 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1052 |
+
|
| 1053 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1054 |
+
they do.
|
| 1055 |
+
:param direction: Integer specifying if the profile is to be used for
|
| 1056 |
+
input, output, or proof
|
| 1057 |
+
|
| 1058 |
+
INPUT = 0 (or use ImageCms.Direction.INPUT)
|
| 1059 |
+
OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
|
| 1060 |
+
PROOF = 2 (or use ImageCms.Direction.PROOF)
|
| 1061 |
+
|
| 1062 |
+
:returns: 1 if the intent/direction are supported, -1 if they are not.
|
| 1063 |
+
:exception PyCMSError:
|
| 1064 |
+
"""
|
| 1065 |
+
|
| 1066 |
+
try:
|
| 1067 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1068 |
+
profile = ImageCmsProfile(profile)
|
| 1069 |
+
# FIXME: I get different results for the same data w. different
|
| 1070 |
+
# compilers. Bug in LittleCMS or in the binding?
|
| 1071 |
+
if profile.profile.is_intent_supported(intent, direction):
|
| 1072 |
+
return 1
|
| 1073 |
+
else:
|
| 1074 |
+
return -1
|
| 1075 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1076 |
+
raise PyCMSError(v) from v
|
.venv/lib/python3.12/site-packages/PIL/ImageDraw.py
ADDED
|
@@ -0,0 +1,1036 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# drawing interface operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-13 fl Created (experimental)
|
| 9 |
+
# 1996-08-07 fl 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 struct
|
| 36 |
+
from collections.abc import Sequence
|
| 37 |
+
from typing import cast
|
| 38 |
+
|
| 39 |
+
from . import Image, ImageColor, ImageText
|
| 40 |
+
|
| 41 |
+
TYPE_CHECKING = False
|
| 42 |
+
if TYPE_CHECKING:
|
| 43 |
+
from collections.abc import Callable
|
| 44 |
+
from types import ModuleType
|
| 45 |
+
from typing import Any, AnyStr
|
| 46 |
+
|
| 47 |
+
from . import ImageDraw2, ImageFont
|
| 48 |
+
from ._typing import Coords, _Ink
|
| 49 |
+
|
| 50 |
+
# experimental access to the outline API
|
| 51 |
+
Outline: Callable[[], Image.core._Outline] = Image.core.outline
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
A simple 2D drawing interface for PIL images.
|
| 55 |
+
<p>
|
| 56 |
+
Application code should use the <b>Draw</b> factory, instead of
|
| 57 |
+
directly.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class ImageDraw:
|
| 62 |
+
font: (
|
| 63 |
+
ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
|
| 64 |
+
) = None
|
| 65 |
+
|
| 66 |
+
def __init__(self, im: Image.Image, mode: str | None = None) -> None:
|
| 67 |
+
"""
|
| 68 |
+
Create a drawing instance.
|
| 69 |
+
|
| 70 |
+
:param im: The image to draw in.
|
| 71 |
+
:param mode: Optional mode to use for color values. For RGB
|
| 72 |
+
images, this argument can be RGB or RGBA (to blend the
|
| 73 |
+
drawing into the image). For all other modes, this argument
|
| 74 |
+
must be the same as the image mode. If omitted, the mode
|
| 75 |
+
defaults to the mode of the image.
|
| 76 |
+
"""
|
| 77 |
+
im._ensure_mutable()
|
| 78 |
+
blend = 0
|
| 79 |
+
if mode is None:
|
| 80 |
+
mode = im.mode
|
| 81 |
+
if mode != im.mode:
|
| 82 |
+
if mode == "RGBA" and im.mode == "RGB":
|
| 83 |
+
blend = 1
|
| 84 |
+
else:
|
| 85 |
+
msg = "mode mismatch"
|
| 86 |
+
raise ValueError(msg)
|
| 87 |
+
if mode == "P":
|
| 88 |
+
self.palette = im.palette
|
| 89 |
+
else:
|
| 90 |
+
self.palette = None
|
| 91 |
+
self._image = im
|
| 92 |
+
self.im = im.im
|
| 93 |
+
self.draw = Image.core.draw(self.im, blend)
|
| 94 |
+
self.mode = mode
|
| 95 |
+
if mode in ("I", "F"):
|
| 96 |
+
self.ink = self.draw.draw_ink(1)
|
| 97 |
+
else:
|
| 98 |
+
self.ink = self.draw.draw_ink(-1)
|
| 99 |
+
if mode in ("1", "P", "I", "F"):
|
| 100 |
+
# FIXME: fix Fill2 to properly support matte for I+F images
|
| 101 |
+
self.fontmode = "1"
|
| 102 |
+
else:
|
| 103 |
+
self.fontmode = "L" # aliasing is okay for other modes
|
| 104 |
+
self.fill = False
|
| 105 |
+
|
| 106 |
+
def getfont(
|
| 107 |
+
self,
|
| 108 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
| 109 |
+
"""
|
| 110 |
+
Get the current default font.
|
| 111 |
+
|
| 112 |
+
To set the default font for this ImageDraw instance::
|
| 113 |
+
|
| 114 |
+
from PIL import ImageDraw, ImageFont
|
| 115 |
+
draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
| 116 |
+
|
| 117 |
+
To set the default font for all future ImageDraw instances::
|
| 118 |
+
|
| 119 |
+
from PIL import ImageDraw, ImageFont
|
| 120 |
+
ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
| 121 |
+
|
| 122 |
+
If the current default font is ``None``,
|
| 123 |
+
it is initialized with ``ImageFont.load_default()``.
|
| 124 |
+
|
| 125 |
+
:returns: An image font."""
|
| 126 |
+
if not self.font:
|
| 127 |
+
# FIXME: should add a font repository
|
| 128 |
+
from . import ImageFont
|
| 129 |
+
|
| 130 |
+
self.font = ImageFont.load_default()
|
| 131 |
+
return self.font
|
| 132 |
+
|
| 133 |
+
def _getfont(
|
| 134 |
+
self, font_size: float | None
|
| 135 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
| 136 |
+
if font_size is not None:
|
| 137 |
+
from . import ImageFont
|
| 138 |
+
|
| 139 |
+
return ImageFont.load_default(font_size)
|
| 140 |
+
else:
|
| 141 |
+
return self.getfont()
|
| 142 |
+
|
| 143 |
+
def _getink(
|
| 144 |
+
self, ink: _Ink | None, fill: _Ink | None = None
|
| 145 |
+
) -> tuple[int | None, int | None]:
|
| 146 |
+
result_ink = None
|
| 147 |
+
result_fill = None
|
| 148 |
+
if ink is None and fill is None:
|
| 149 |
+
if self.fill:
|
| 150 |
+
result_fill = self.ink
|
| 151 |
+
else:
|
| 152 |
+
result_ink = self.ink
|
| 153 |
+
else:
|
| 154 |
+
if ink is not None:
|
| 155 |
+
if isinstance(ink, str):
|
| 156 |
+
ink = ImageColor.getcolor(ink, self.mode)
|
| 157 |
+
if self.palette and isinstance(ink, tuple):
|
| 158 |
+
ink = self.palette.getcolor(ink, self._image)
|
| 159 |
+
result_ink = self.draw.draw_ink(ink)
|
| 160 |
+
if fill is not None:
|
| 161 |
+
if isinstance(fill, str):
|
| 162 |
+
fill = ImageColor.getcolor(fill, self.mode)
|
| 163 |
+
if self.palette and isinstance(fill, tuple):
|
| 164 |
+
fill = self.palette.getcolor(fill, self._image)
|
| 165 |
+
result_fill = self.draw.draw_ink(fill)
|
| 166 |
+
return result_ink, result_fill
|
| 167 |
+
|
| 168 |
+
def arc(
|
| 169 |
+
self,
|
| 170 |
+
xy: Coords,
|
| 171 |
+
start: float,
|
| 172 |
+
end: float,
|
| 173 |
+
fill: _Ink | None = None,
|
| 174 |
+
width: int = 1,
|
| 175 |
+
) -> None:
|
| 176 |
+
"""Draw an arc."""
|
| 177 |
+
ink, fill = self._getink(fill)
|
| 178 |
+
if ink is not None:
|
| 179 |
+
self.draw.draw_arc(xy, start, end, ink, width)
|
| 180 |
+
|
| 181 |
+
def bitmap(
|
| 182 |
+
self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
|
| 183 |
+
) -> None:
|
| 184 |
+
"""Draw a bitmap."""
|
| 185 |
+
bitmap.load()
|
| 186 |
+
ink, fill = self._getink(fill)
|
| 187 |
+
if ink is None:
|
| 188 |
+
ink = fill
|
| 189 |
+
if ink is not None:
|
| 190 |
+
self.draw.draw_bitmap(xy, bitmap.im, ink)
|
| 191 |
+
|
| 192 |
+
def chord(
|
| 193 |
+
self,
|
| 194 |
+
xy: Coords,
|
| 195 |
+
start: float,
|
| 196 |
+
end: float,
|
| 197 |
+
fill: _Ink | None = None,
|
| 198 |
+
outline: _Ink | None = None,
|
| 199 |
+
width: int = 1,
|
| 200 |
+
) -> None:
|
| 201 |
+
"""Draw a chord."""
|
| 202 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 203 |
+
if fill_ink is not None:
|
| 204 |
+
self.draw.draw_chord(xy, start, end, fill_ink, 1)
|
| 205 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 206 |
+
self.draw.draw_chord(xy, start, end, ink, 0, width)
|
| 207 |
+
|
| 208 |
+
def ellipse(
|
| 209 |
+
self,
|
| 210 |
+
xy: Coords,
|
| 211 |
+
fill: _Ink | None = None,
|
| 212 |
+
outline: _Ink | None = None,
|
| 213 |
+
width: int = 1,
|
| 214 |
+
) -> None:
|
| 215 |
+
"""Draw an ellipse."""
|
| 216 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 217 |
+
if fill_ink is not None:
|
| 218 |
+
self.draw.draw_ellipse(xy, fill_ink, 1)
|
| 219 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 220 |
+
self.draw.draw_ellipse(xy, ink, 0, width)
|
| 221 |
+
|
| 222 |
+
def circle(
|
| 223 |
+
self,
|
| 224 |
+
xy: Sequence[float],
|
| 225 |
+
radius: float,
|
| 226 |
+
fill: _Ink | None = None,
|
| 227 |
+
outline: _Ink | None = None,
|
| 228 |
+
width: int = 1,
|
| 229 |
+
) -> None:
|
| 230 |
+
"""Draw a circle given center coordinates and a radius."""
|
| 231 |
+
ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
|
| 232 |
+
self.ellipse(ellipse_xy, fill, outline, width)
|
| 233 |
+
|
| 234 |
+
def line(
|
| 235 |
+
self,
|
| 236 |
+
xy: Coords,
|
| 237 |
+
fill: _Ink | None = None,
|
| 238 |
+
width: int = 0,
|
| 239 |
+
joint: str | None = None,
|
| 240 |
+
) -> None:
|
| 241 |
+
"""Draw a line, or a connected sequence of line segments."""
|
| 242 |
+
ink = self._getink(fill)[0]
|
| 243 |
+
if ink is not None:
|
| 244 |
+
self.draw.draw_lines(xy, ink, width)
|
| 245 |
+
if joint == "curve" and width > 4:
|
| 246 |
+
points: Sequence[Sequence[float]]
|
| 247 |
+
if isinstance(xy[0], (list, tuple)):
|
| 248 |
+
points = cast(Sequence[Sequence[float]], xy)
|
| 249 |
+
else:
|
| 250 |
+
points = [
|
| 251 |
+
cast(Sequence[float], tuple(xy[i : i + 2]))
|
| 252 |
+
for i in range(0, len(xy), 2)
|
| 253 |
+
]
|
| 254 |
+
for i in range(1, len(points) - 1):
|
| 255 |
+
point = points[i]
|
| 256 |
+
angles = [
|
| 257 |
+
math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
|
| 258 |
+
% 360
|
| 259 |
+
for start, end in (
|
| 260 |
+
(points[i - 1], point),
|
| 261 |
+
(point, points[i + 1]),
|
| 262 |
+
)
|
| 263 |
+
]
|
| 264 |
+
if angles[0] == angles[1]:
|
| 265 |
+
# This is a straight line, so no joint is required
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
def coord_at_angle(
|
| 269 |
+
coord: Sequence[float], angle: float
|
| 270 |
+
) -> tuple[float, ...]:
|
| 271 |
+
x, y = coord
|
| 272 |
+
angle -= 90
|
| 273 |
+
distance = width / 2 - 1
|
| 274 |
+
return tuple(
|
| 275 |
+
p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
|
| 276 |
+
for p, p_d in (
|
| 277 |
+
(x, distance * math.cos(math.radians(angle))),
|
| 278 |
+
(y, distance * math.sin(math.radians(angle))),
|
| 279 |
+
)
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
flipped = (
|
| 283 |
+
angles[1] > angles[0] and angles[1] - 180 > angles[0]
|
| 284 |
+
) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
|
| 285 |
+
coords = [
|
| 286 |
+
(point[0] - width / 2 + 1, point[1] - width / 2 + 1),
|
| 287 |
+
(point[0] + width / 2 - 1, point[1] + width / 2 - 1),
|
| 288 |
+
]
|
| 289 |
+
if flipped:
|
| 290 |
+
start, end = (angles[1] + 90, angles[0] + 90)
|
| 291 |
+
else:
|
| 292 |
+
start, end = (angles[0] - 90, angles[1] - 90)
|
| 293 |
+
self.pieslice(coords, start - 90, end - 90, fill)
|
| 294 |
+
|
| 295 |
+
if width > 8:
|
| 296 |
+
# Cover potential gaps between the line and the joint
|
| 297 |
+
if flipped:
|
| 298 |
+
gap_coords = [
|
| 299 |
+
coord_at_angle(point, angles[0] + 90),
|
| 300 |
+
point,
|
| 301 |
+
coord_at_angle(point, angles[1] + 90),
|
| 302 |
+
]
|
| 303 |
+
else:
|
| 304 |
+
gap_coords = [
|
| 305 |
+
coord_at_angle(point, angles[0] - 90),
|
| 306 |
+
point,
|
| 307 |
+
coord_at_angle(point, angles[1] - 90),
|
| 308 |
+
]
|
| 309 |
+
self.line(gap_coords, fill, width=3)
|
| 310 |
+
|
| 311 |
+
def shape(
|
| 312 |
+
self,
|
| 313 |
+
shape: Image.core._Outline,
|
| 314 |
+
fill: _Ink | None = None,
|
| 315 |
+
outline: _Ink | None = None,
|
| 316 |
+
) -> None:
|
| 317 |
+
"""(Experimental) Draw a shape."""
|
| 318 |
+
shape.close()
|
| 319 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 320 |
+
if fill_ink is not None:
|
| 321 |
+
self.draw.draw_outline(shape, fill_ink, 1)
|
| 322 |
+
if ink is not None and ink != fill_ink:
|
| 323 |
+
self.draw.draw_outline(shape, ink, 0)
|
| 324 |
+
|
| 325 |
+
def pieslice(
|
| 326 |
+
self,
|
| 327 |
+
xy: Coords,
|
| 328 |
+
start: float,
|
| 329 |
+
end: float,
|
| 330 |
+
fill: _Ink | None = None,
|
| 331 |
+
outline: _Ink | None = None,
|
| 332 |
+
width: int = 1,
|
| 333 |
+
) -> None:
|
| 334 |
+
"""Draw a pieslice."""
|
| 335 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 336 |
+
if fill_ink is not None:
|
| 337 |
+
self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
|
| 338 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 339 |
+
self.draw.draw_pieslice(xy, start, end, ink, 0, width)
|
| 340 |
+
|
| 341 |
+
def point(self, xy: Coords, fill: _Ink | None = None) -> None:
|
| 342 |
+
"""Draw one or more individual pixels."""
|
| 343 |
+
ink, fill = self._getink(fill)
|
| 344 |
+
if ink is not None:
|
| 345 |
+
self.draw.draw_points(xy, ink)
|
| 346 |
+
|
| 347 |
+
def polygon(
|
| 348 |
+
self,
|
| 349 |
+
xy: Coords,
|
| 350 |
+
fill: _Ink | None = None,
|
| 351 |
+
outline: _Ink | None = None,
|
| 352 |
+
width: int = 1,
|
| 353 |
+
) -> None:
|
| 354 |
+
"""Draw a polygon."""
|
| 355 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 356 |
+
if fill_ink is not None:
|
| 357 |
+
self.draw.draw_polygon(xy, fill_ink, 1)
|
| 358 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 359 |
+
if width == 1:
|
| 360 |
+
self.draw.draw_polygon(xy, ink, 0, width)
|
| 361 |
+
elif self.im is not None:
|
| 362 |
+
# To avoid expanding the polygon outwards,
|
| 363 |
+
# use the fill as a mask
|
| 364 |
+
mask = Image.new("1", self.im.size)
|
| 365 |
+
mask_ink = self._getink(1)[0]
|
| 366 |
+
draw = Draw(mask)
|
| 367 |
+
draw.draw.draw_polygon(xy, mask_ink, 1)
|
| 368 |
+
|
| 369 |
+
self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im)
|
| 370 |
+
|
| 371 |
+
def regular_polygon(
|
| 372 |
+
self,
|
| 373 |
+
bounding_circle: Sequence[Sequence[float] | float],
|
| 374 |
+
n_sides: int,
|
| 375 |
+
rotation: float = 0,
|
| 376 |
+
fill: _Ink | None = None,
|
| 377 |
+
outline: _Ink | None = None,
|
| 378 |
+
width: int = 1,
|
| 379 |
+
) -> None:
|
| 380 |
+
"""Draw a regular polygon."""
|
| 381 |
+
xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
|
| 382 |
+
self.polygon(xy, fill, outline, width)
|
| 383 |
+
|
| 384 |
+
def rectangle(
|
| 385 |
+
self,
|
| 386 |
+
xy: Coords,
|
| 387 |
+
fill: _Ink | None = None,
|
| 388 |
+
outline: _Ink | None = None,
|
| 389 |
+
width: int = 1,
|
| 390 |
+
) -> None:
|
| 391 |
+
"""Draw a rectangle."""
|
| 392 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 393 |
+
if fill_ink is not None:
|
| 394 |
+
self.draw.draw_rectangle(xy, fill_ink, 1)
|
| 395 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 396 |
+
self.draw.draw_rectangle(xy, ink, 0, width)
|
| 397 |
+
|
| 398 |
+
def rounded_rectangle(
|
| 399 |
+
self,
|
| 400 |
+
xy: Coords,
|
| 401 |
+
radius: float = 0,
|
| 402 |
+
fill: _Ink | None = None,
|
| 403 |
+
outline: _Ink | None = None,
|
| 404 |
+
width: int = 1,
|
| 405 |
+
*,
|
| 406 |
+
corners: tuple[bool, bool, bool, bool] | None = None,
|
| 407 |
+
) -> None:
|
| 408 |
+
"""Draw a rounded rectangle."""
|
| 409 |
+
if isinstance(xy[0], (list, tuple)):
|
| 410 |
+
(x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
|
| 411 |
+
else:
|
| 412 |
+
x0, y0, x1, y1 = cast(Sequence[float], xy)
|
| 413 |
+
if x1 < x0:
|
| 414 |
+
msg = "x1 must be greater than or equal to x0"
|
| 415 |
+
raise ValueError(msg)
|
| 416 |
+
if y1 < y0:
|
| 417 |
+
msg = "y1 must be greater than or equal to y0"
|
| 418 |
+
raise ValueError(msg)
|
| 419 |
+
if corners is None:
|
| 420 |
+
corners = (True, True, True, True)
|
| 421 |
+
|
| 422 |
+
d = radius * 2
|
| 423 |
+
|
| 424 |
+
x0 = round(x0)
|
| 425 |
+
y0 = round(y0)
|
| 426 |
+
x1 = round(x1)
|
| 427 |
+
y1 = round(y1)
|
| 428 |
+
full_x, full_y = False, False
|
| 429 |
+
if all(corners):
|
| 430 |
+
full_x = d >= x1 - x0 - 1
|
| 431 |
+
if full_x:
|
| 432 |
+
# The two left and two right corners are joined
|
| 433 |
+
d = x1 - x0
|
| 434 |
+
full_y = d >= y1 - y0 - 1
|
| 435 |
+
if full_y:
|
| 436 |
+
# The two top and two bottom corners are joined
|
| 437 |
+
d = y1 - y0
|
| 438 |
+
if full_x and full_y:
|
| 439 |
+
# If all corners are joined, that is a circle
|
| 440 |
+
return self.ellipse(xy, fill, outline, width)
|
| 441 |
+
|
| 442 |
+
if d == 0 or not any(corners):
|
| 443 |
+
# If the corners have no curve,
|
| 444 |
+
# or there are no corners,
|
| 445 |
+
# that is a rectangle
|
| 446 |
+
return self.rectangle(xy, fill, outline, width)
|
| 447 |
+
|
| 448 |
+
r = int(d // 2)
|
| 449 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 450 |
+
|
| 451 |
+
def draw_corners(pieslice: bool) -> None:
|
| 452 |
+
parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
|
| 453 |
+
if full_x:
|
| 454 |
+
# Draw top and bottom halves
|
| 455 |
+
parts = (
|
| 456 |
+
((x0, y0, x0 + d, y0 + d), 180, 360),
|
| 457 |
+
((x0, y1 - d, x0 + d, y1), 0, 180),
|
| 458 |
+
)
|
| 459 |
+
elif full_y:
|
| 460 |
+
# Draw left and right halves
|
| 461 |
+
parts = (
|
| 462 |
+
((x0, y0, x0 + d, y0 + d), 90, 270),
|
| 463 |
+
((x1 - d, y0, x1, y0 + d), 270, 90),
|
| 464 |
+
)
|
| 465 |
+
else:
|
| 466 |
+
# Draw four separate corners
|
| 467 |
+
parts = tuple(
|
| 468 |
+
part
|
| 469 |
+
for i, part in enumerate(
|
| 470 |
+
(
|
| 471 |
+
((x0, y0, x0 + d, y0 + d), 180, 270),
|
| 472 |
+
((x1 - d, y0, x1, y0 + d), 270, 360),
|
| 473 |
+
((x1 - d, y1 - d, x1, y1), 0, 90),
|
| 474 |
+
((x0, y1 - d, x0 + d, y1), 90, 180),
|
| 475 |
+
)
|
| 476 |
+
)
|
| 477 |
+
if corners[i]
|
| 478 |
+
)
|
| 479 |
+
for part in parts:
|
| 480 |
+
if pieslice:
|
| 481 |
+
self.draw.draw_pieslice(*(part + (fill_ink, 1)))
|
| 482 |
+
else:
|
| 483 |
+
self.draw.draw_arc(*(part + (ink, width)))
|
| 484 |
+
|
| 485 |
+
if fill_ink is not None:
|
| 486 |
+
draw_corners(True)
|
| 487 |
+
|
| 488 |
+
if full_x:
|
| 489 |
+
self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
|
| 490 |
+
elif x1 - r - 1 > x0 + r + 1:
|
| 491 |
+
self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
|
| 492 |
+
if not full_x and not full_y:
|
| 493 |
+
left = [x0, y0, x0 + r, y1]
|
| 494 |
+
if corners[0]:
|
| 495 |
+
left[1] += r + 1
|
| 496 |
+
if corners[3]:
|
| 497 |
+
left[3] -= r + 1
|
| 498 |
+
self.draw.draw_rectangle(left, fill_ink, 1)
|
| 499 |
+
|
| 500 |
+
right = [x1 - r, y0, x1, y1]
|
| 501 |
+
if corners[1]:
|
| 502 |
+
right[1] += r + 1
|
| 503 |
+
if corners[2]:
|
| 504 |
+
right[3] -= r + 1
|
| 505 |
+
self.draw.draw_rectangle(right, fill_ink, 1)
|
| 506 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 507 |
+
draw_corners(False)
|
| 508 |
+
|
| 509 |
+
if not full_x:
|
| 510 |
+
top = [x0, y0, x1, y0 + width - 1]
|
| 511 |
+
if corners[0]:
|
| 512 |
+
top[0] += r + 1
|
| 513 |
+
if corners[1]:
|
| 514 |
+
top[2] -= r + 1
|
| 515 |
+
self.draw.draw_rectangle(top, ink, 1)
|
| 516 |
+
|
| 517 |
+
bottom = [x0, y1 - width + 1, x1, y1]
|
| 518 |
+
if corners[3]:
|
| 519 |
+
bottom[0] += r + 1
|
| 520 |
+
if corners[2]:
|
| 521 |
+
bottom[2] -= r + 1
|
| 522 |
+
self.draw.draw_rectangle(bottom, ink, 1)
|
| 523 |
+
if not full_y:
|
| 524 |
+
left = [x0, y0, x0 + width - 1, y1]
|
| 525 |
+
if corners[0]:
|
| 526 |
+
left[1] += r + 1
|
| 527 |
+
if corners[3]:
|
| 528 |
+
left[3] -= r + 1
|
| 529 |
+
self.draw.draw_rectangle(left, ink, 1)
|
| 530 |
+
|
| 531 |
+
right = [x1 - width + 1, y0, x1, y1]
|
| 532 |
+
if corners[1]:
|
| 533 |
+
right[1] += r + 1
|
| 534 |
+
if corners[2]:
|
| 535 |
+
right[3] -= r + 1
|
| 536 |
+
self.draw.draw_rectangle(right, ink, 1)
|
| 537 |
+
|
| 538 |
+
def text(
|
| 539 |
+
self,
|
| 540 |
+
xy: tuple[float, float],
|
| 541 |
+
text: AnyStr | ImageText.Text,
|
| 542 |
+
fill: _Ink | None = None,
|
| 543 |
+
font: (
|
| 544 |
+
ImageFont.ImageFont
|
| 545 |
+
| ImageFont.FreeTypeFont
|
| 546 |
+
| ImageFont.TransposedFont
|
| 547 |
+
| None
|
| 548 |
+
) = None,
|
| 549 |
+
anchor: str | None = None,
|
| 550 |
+
spacing: float = 4,
|
| 551 |
+
align: str = "left",
|
| 552 |
+
direction: str | None = None,
|
| 553 |
+
features: list[str] | None = None,
|
| 554 |
+
language: str | None = None,
|
| 555 |
+
stroke_width: float = 0,
|
| 556 |
+
stroke_fill: _Ink | None = None,
|
| 557 |
+
embedded_color: bool = False,
|
| 558 |
+
*args: Any,
|
| 559 |
+
**kwargs: Any,
|
| 560 |
+
) -> None:
|
| 561 |
+
"""Draw text."""
|
| 562 |
+
if isinstance(text, ImageText.Text):
|
| 563 |
+
image_text = text
|
| 564 |
+
else:
|
| 565 |
+
if font is None:
|
| 566 |
+
font = self._getfont(kwargs.get("font_size"))
|
| 567 |
+
image_text = ImageText.Text(
|
| 568 |
+
text, font, self.mode, spacing, direction, features, language
|
| 569 |
+
)
|
| 570 |
+
if embedded_color:
|
| 571 |
+
image_text.embed_color()
|
| 572 |
+
if stroke_width:
|
| 573 |
+
image_text.stroke(stroke_width, stroke_fill)
|
| 574 |
+
|
| 575 |
+
def getink(fill: _Ink | None) -> int:
|
| 576 |
+
ink, fill_ink = self._getink(fill)
|
| 577 |
+
if ink is None:
|
| 578 |
+
assert fill_ink is not None
|
| 579 |
+
return fill_ink
|
| 580 |
+
return ink
|
| 581 |
+
|
| 582 |
+
ink = getink(fill)
|
| 583 |
+
if ink is None:
|
| 584 |
+
return
|
| 585 |
+
|
| 586 |
+
stroke_ink = None
|
| 587 |
+
if image_text.stroke_width:
|
| 588 |
+
stroke_ink = (
|
| 589 |
+
getink(image_text.stroke_fill)
|
| 590 |
+
if image_text.stroke_fill is not None
|
| 591 |
+
else ink
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
for xy, anchor, line in image_text._split(xy, anchor, align):
|
| 595 |
+
|
| 596 |
+
def draw_text(ink: int, stroke_width: float = 0) -> None:
|
| 597 |
+
mode = self.fontmode
|
| 598 |
+
if stroke_width == 0 and embedded_color:
|
| 599 |
+
mode = "RGBA"
|
| 600 |
+
coord = []
|
| 601 |
+
for i in range(2):
|
| 602 |
+
coord.append(int(xy[i]))
|
| 603 |
+
start = (math.modf(xy[0])[0], math.modf(xy[1])[0])
|
| 604 |
+
try:
|
| 605 |
+
mask, offset = image_text.font.getmask2( # type: ignore[union-attr,misc]
|
| 606 |
+
line,
|
| 607 |
+
mode,
|
| 608 |
+
direction=direction,
|
| 609 |
+
features=features,
|
| 610 |
+
language=language,
|
| 611 |
+
stroke_width=stroke_width,
|
| 612 |
+
stroke_filled=True,
|
| 613 |
+
anchor=anchor,
|
| 614 |
+
ink=ink,
|
| 615 |
+
start=start,
|
| 616 |
+
*args,
|
| 617 |
+
**kwargs,
|
| 618 |
+
)
|
| 619 |
+
coord = [coord[0] + offset[0], coord[1] + offset[1]]
|
| 620 |
+
except AttributeError:
|
| 621 |
+
try:
|
| 622 |
+
mask = image_text.font.getmask( # type: ignore[misc]
|
| 623 |
+
line,
|
| 624 |
+
mode,
|
| 625 |
+
direction,
|
| 626 |
+
features,
|
| 627 |
+
language,
|
| 628 |
+
stroke_width,
|
| 629 |
+
anchor,
|
| 630 |
+
ink,
|
| 631 |
+
start=start,
|
| 632 |
+
*args,
|
| 633 |
+
**kwargs,
|
| 634 |
+
)
|
| 635 |
+
except TypeError:
|
| 636 |
+
mask = image_text.font.getmask(line)
|
| 637 |
+
if mode == "RGBA":
|
| 638 |
+
# image_text.font.getmask2(mode="RGBA")
|
| 639 |
+
# returns color in RGB bands and mask in A
|
| 640 |
+
# extract mask and set text alpha
|
| 641 |
+
color, mask = mask, mask.getband(3)
|
| 642 |
+
ink_alpha = struct.pack("i", ink)[3]
|
| 643 |
+
color.fillband(3, ink_alpha)
|
| 644 |
+
x, y = coord
|
| 645 |
+
if self.im is not None:
|
| 646 |
+
self.im.paste(
|
| 647 |
+
color, (x, y, x + mask.size[0], y + mask.size[1]), mask
|
| 648 |
+
)
|
| 649 |
+
else:
|
| 650 |
+
self.draw.draw_bitmap(coord, mask, ink)
|
| 651 |
+
|
| 652 |
+
if stroke_ink is not None:
|
| 653 |
+
# Draw stroked text
|
| 654 |
+
draw_text(stroke_ink, image_text.stroke_width)
|
| 655 |
+
|
| 656 |
+
# Draw normal text
|
| 657 |
+
if ink != stroke_ink:
|
| 658 |
+
draw_text(ink)
|
| 659 |
+
else:
|
| 660 |
+
# Only draw normal text
|
| 661 |
+
draw_text(ink)
|
| 662 |
+
|
| 663 |
+
def multiline_text(
|
| 664 |
+
self,
|
| 665 |
+
xy: tuple[float, float],
|
| 666 |
+
text: AnyStr,
|
| 667 |
+
fill: _Ink | None = None,
|
| 668 |
+
font: (
|
| 669 |
+
ImageFont.ImageFont
|
| 670 |
+
| ImageFont.FreeTypeFont
|
| 671 |
+
| ImageFont.TransposedFont
|
| 672 |
+
| None
|
| 673 |
+
) = None,
|
| 674 |
+
anchor: str | None = None,
|
| 675 |
+
spacing: float = 4,
|
| 676 |
+
align: str = "left",
|
| 677 |
+
direction: str | None = None,
|
| 678 |
+
features: list[str] | None = None,
|
| 679 |
+
language: str | None = None,
|
| 680 |
+
stroke_width: float = 0,
|
| 681 |
+
stroke_fill: _Ink | None = None,
|
| 682 |
+
embedded_color: bool = False,
|
| 683 |
+
*,
|
| 684 |
+
font_size: float | None = None,
|
| 685 |
+
) -> None:
|
| 686 |
+
return self.text(
|
| 687 |
+
xy,
|
| 688 |
+
text,
|
| 689 |
+
fill,
|
| 690 |
+
font,
|
| 691 |
+
anchor,
|
| 692 |
+
spacing,
|
| 693 |
+
align,
|
| 694 |
+
direction,
|
| 695 |
+
features,
|
| 696 |
+
language,
|
| 697 |
+
stroke_width,
|
| 698 |
+
stroke_fill,
|
| 699 |
+
embedded_color,
|
| 700 |
+
font_size=font_size,
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
def textlength(
|
| 704 |
+
self,
|
| 705 |
+
text: AnyStr,
|
| 706 |
+
font: (
|
| 707 |
+
ImageFont.ImageFont
|
| 708 |
+
| ImageFont.FreeTypeFont
|
| 709 |
+
| ImageFont.TransposedFont
|
| 710 |
+
| None
|
| 711 |
+
) = None,
|
| 712 |
+
direction: str | None = None,
|
| 713 |
+
features: list[str] | None = None,
|
| 714 |
+
language: str | None = None,
|
| 715 |
+
embedded_color: bool = False,
|
| 716 |
+
*,
|
| 717 |
+
font_size: float | None = None,
|
| 718 |
+
) -> float:
|
| 719 |
+
"""Get the length of a given string, in pixels with 1/64 precision."""
|
| 720 |
+
if font is None:
|
| 721 |
+
font = self._getfont(font_size)
|
| 722 |
+
image_text = ImageText.Text(
|
| 723 |
+
text,
|
| 724 |
+
font,
|
| 725 |
+
self.mode,
|
| 726 |
+
direction=direction,
|
| 727 |
+
features=features,
|
| 728 |
+
language=language,
|
| 729 |
+
)
|
| 730 |
+
if embedded_color:
|
| 731 |
+
image_text.embed_color()
|
| 732 |
+
return image_text.get_length()
|
| 733 |
+
|
| 734 |
+
def textbbox(
|
| 735 |
+
self,
|
| 736 |
+
xy: tuple[float, float],
|
| 737 |
+
text: AnyStr,
|
| 738 |
+
font: (
|
| 739 |
+
ImageFont.ImageFont
|
| 740 |
+
| ImageFont.FreeTypeFont
|
| 741 |
+
| ImageFont.TransposedFont
|
| 742 |
+
| None
|
| 743 |
+
) = None,
|
| 744 |
+
anchor: str | None = None,
|
| 745 |
+
spacing: float = 4,
|
| 746 |
+
align: str = "left",
|
| 747 |
+
direction: str | None = None,
|
| 748 |
+
features: list[str] | None = None,
|
| 749 |
+
language: str | None = None,
|
| 750 |
+
stroke_width: float = 0,
|
| 751 |
+
embedded_color: bool = False,
|
| 752 |
+
*,
|
| 753 |
+
font_size: float | None = None,
|
| 754 |
+
) -> tuple[float, float, float, float]:
|
| 755 |
+
"""Get the bounding box of a given string, in pixels."""
|
| 756 |
+
if font is None:
|
| 757 |
+
font = self._getfont(font_size)
|
| 758 |
+
image_text = ImageText.Text(
|
| 759 |
+
text, font, self.mode, spacing, direction, features, language
|
| 760 |
+
)
|
| 761 |
+
if embedded_color:
|
| 762 |
+
image_text.embed_color()
|
| 763 |
+
if stroke_width:
|
| 764 |
+
image_text.stroke(stroke_width)
|
| 765 |
+
return image_text.get_bbox(xy, anchor, align)
|
| 766 |
+
|
| 767 |
+
def multiline_textbbox(
|
| 768 |
+
self,
|
| 769 |
+
xy: tuple[float, float],
|
| 770 |
+
text: AnyStr,
|
| 771 |
+
font: (
|
| 772 |
+
ImageFont.ImageFont
|
| 773 |
+
| ImageFont.FreeTypeFont
|
| 774 |
+
| ImageFont.TransposedFont
|
| 775 |
+
| None
|
| 776 |
+
) = None,
|
| 777 |
+
anchor: str | None = None,
|
| 778 |
+
spacing: float = 4,
|
| 779 |
+
align: str = "left",
|
| 780 |
+
direction: str | None = None,
|
| 781 |
+
features: list[str] | None = None,
|
| 782 |
+
language: str | None = None,
|
| 783 |
+
stroke_width: float = 0,
|
| 784 |
+
embedded_color: bool = False,
|
| 785 |
+
*,
|
| 786 |
+
font_size: float | None = None,
|
| 787 |
+
) -> tuple[float, float, float, float]:
|
| 788 |
+
return self.textbbox(
|
| 789 |
+
xy,
|
| 790 |
+
text,
|
| 791 |
+
font,
|
| 792 |
+
anchor,
|
| 793 |
+
spacing,
|
| 794 |
+
align,
|
| 795 |
+
direction,
|
| 796 |
+
features,
|
| 797 |
+
language,
|
| 798 |
+
stroke_width,
|
| 799 |
+
embedded_color,
|
| 800 |
+
font_size=font_size,
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
|
| 805 |
+
"""
|
| 806 |
+
A simple 2D drawing interface for PIL images.
|
| 807 |
+
|
| 808 |
+
:param im: The image to draw in.
|
| 809 |
+
:param mode: Optional mode to use for color values. For RGB
|
| 810 |
+
images, this argument can be RGB or RGBA (to blend the
|
| 811 |
+
drawing into the image). For all other modes, this argument
|
| 812 |
+
must be the same as the image mode. If omitted, the mode
|
| 813 |
+
defaults to the mode of the image.
|
| 814 |
+
"""
|
| 815 |
+
try:
|
| 816 |
+
return getattr(im, "getdraw")(mode)
|
| 817 |
+
except AttributeError:
|
| 818 |
+
return ImageDraw(im, mode)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]:
|
| 822 |
+
"""
|
| 823 |
+
:param im: The image to draw in.
|
| 824 |
+
:returns: A (drawing context, drawing resource factory) tuple.
|
| 825 |
+
"""
|
| 826 |
+
from . import ImageDraw2
|
| 827 |
+
|
| 828 |
+
draw = ImageDraw2.Draw(im) if im is not None else None
|
| 829 |
+
return draw, ImageDraw2
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
def floodfill(
|
| 833 |
+
image: Image.Image,
|
| 834 |
+
xy: tuple[int, int],
|
| 835 |
+
value: float | tuple[int, ...],
|
| 836 |
+
border: float | tuple[int, ...] | None = None,
|
| 837 |
+
thresh: float = 0,
|
| 838 |
+
) -> None:
|
| 839 |
+
"""
|
| 840 |
+
.. warning:: This method is experimental.
|
| 841 |
+
|
| 842 |
+
Fills a bounded region with a given color.
|
| 843 |
+
|
| 844 |
+
:param image: Target image.
|
| 845 |
+
:param xy: Seed position (a 2-item coordinate tuple). See
|
| 846 |
+
:ref:`coordinate-system`.
|
| 847 |
+
:param value: Fill color.
|
| 848 |
+
:param border: Optional border value. If given, the region consists of
|
| 849 |
+
pixels with a color different from the border color. If not given,
|
| 850 |
+
the region consists of pixels having the same color as the seed
|
| 851 |
+
pixel.
|
| 852 |
+
:param thresh: Optional threshold value which specifies a maximum
|
| 853 |
+
tolerable difference of a pixel value from the 'background' in
|
| 854 |
+
order for it to be replaced. Useful for filling regions of
|
| 855 |
+
non-homogeneous, but similar, colors.
|
| 856 |
+
"""
|
| 857 |
+
# based on an implementation by Eric S. Raymond
|
| 858 |
+
# amended by yo1995 @20180806
|
| 859 |
+
pixel = image.load()
|
| 860 |
+
assert pixel is not None
|
| 861 |
+
x, y = xy
|
| 862 |
+
try:
|
| 863 |
+
background = pixel[x, y]
|
| 864 |
+
if _color_diff(value, background) <= thresh:
|
| 865 |
+
return # seed point already has fill color
|
| 866 |
+
pixel[x, y] = value
|
| 867 |
+
except (ValueError, IndexError):
|
| 868 |
+
return # seed point outside image
|
| 869 |
+
edge = {(x, y)}
|
| 870 |
+
# use a set to keep record of current and previous edge pixels
|
| 871 |
+
# to reduce memory consumption
|
| 872 |
+
full_edge = set()
|
| 873 |
+
while edge:
|
| 874 |
+
new_edge = set()
|
| 875 |
+
for x, y in edge: # 4 adjacent method
|
| 876 |
+
for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
| 877 |
+
# If already processed, or if a coordinate is negative, skip
|
| 878 |
+
if (s, t) in full_edge or s < 0 or t < 0:
|
| 879 |
+
continue
|
| 880 |
+
try:
|
| 881 |
+
p = pixel[s, t]
|
| 882 |
+
except (ValueError, IndexError):
|
| 883 |
+
pass
|
| 884 |
+
else:
|
| 885 |
+
full_edge.add((s, t))
|
| 886 |
+
if border is None:
|
| 887 |
+
fill = _color_diff(p, background) <= thresh
|
| 888 |
+
else:
|
| 889 |
+
fill = p not in (value, border)
|
| 890 |
+
if fill:
|
| 891 |
+
pixel[s, t] = value
|
| 892 |
+
new_edge.add((s, t))
|
| 893 |
+
full_edge = edge # discard pixels processed
|
| 894 |
+
edge = new_edge
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def _compute_regular_polygon_vertices(
|
| 898 |
+
bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
|
| 899 |
+
) -> list[tuple[float, float]]:
|
| 900 |
+
"""
|
| 901 |
+
Generate a list of vertices for a 2D regular polygon.
|
| 902 |
+
|
| 903 |
+
:param bounding_circle: The bounding circle is a sequence defined
|
| 904 |
+
by a point and radius. The polygon is inscribed in this circle.
|
| 905 |
+
(e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
|
| 906 |
+
:param n_sides: Number of sides
|
| 907 |
+
(e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
|
| 908 |
+
:param rotation: Apply an arbitrary rotation to the polygon
|
| 909 |
+
(e.g. ``rotation=90``, applies a 90 degree rotation)
|
| 910 |
+
:return: List of regular polygon vertices
|
| 911 |
+
(e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
|
| 912 |
+
|
| 913 |
+
How are the vertices computed?
|
| 914 |
+
1. Compute the following variables
|
| 915 |
+
- theta: Angle between the apothem & the nearest polygon vertex
|
| 916 |
+
- side_length: Length of each polygon edge
|
| 917 |
+
- centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
|
| 918 |
+
- polygon_radius: Polygon radius (last element of bounding_circle)
|
| 919 |
+
- angles: Location of each polygon vertex in polar grid
|
| 920 |
+
(e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
|
| 921 |
+
|
| 922 |
+
2. For each angle in angles, get the polygon vertex at that angle
|
| 923 |
+
The vertex is computed using the equation below.
|
| 924 |
+
X= xcos(φ) + ysin(φ)
|
| 925 |
+
Y= −xsin(φ) + ycos(φ)
|
| 926 |
+
|
| 927 |
+
Note:
|
| 928 |
+
φ = angle in degrees
|
| 929 |
+
x = 0
|
| 930 |
+
y = polygon_radius
|
| 931 |
+
|
| 932 |
+
The formula above assumes rotation around the origin.
|
| 933 |
+
In our case, we are rotating around the centroid.
|
| 934 |
+
To account for this, we use the formula below
|
| 935 |
+
X = xcos(φ) + ysin(φ) + centroid_x
|
| 936 |
+
Y = −xsin(φ) + ycos(φ) + centroid_y
|
| 937 |
+
"""
|
| 938 |
+
# 1. Error Handling
|
| 939 |
+
# 1.1 Check `n_sides` has an appropriate value
|
| 940 |
+
if not isinstance(n_sides, int):
|
| 941 |
+
msg = "n_sides should be an int" # type: ignore[unreachable]
|
| 942 |
+
raise TypeError(msg)
|
| 943 |
+
if n_sides < 3:
|
| 944 |
+
msg = "n_sides should be an int > 2"
|
| 945 |
+
raise ValueError(msg)
|
| 946 |
+
|
| 947 |
+
# 1.2 Check `bounding_circle` has an appropriate value
|
| 948 |
+
if not isinstance(bounding_circle, (list, tuple)):
|
| 949 |
+
msg = "bounding_circle should be a sequence"
|
| 950 |
+
raise TypeError(msg)
|
| 951 |
+
|
| 952 |
+
if len(bounding_circle) == 3:
|
| 953 |
+
if not all(isinstance(i, (int, float)) for i in bounding_circle):
|
| 954 |
+
msg = "bounding_circle should only contain numeric data"
|
| 955 |
+
raise ValueError(msg)
|
| 956 |
+
|
| 957 |
+
*centroid, polygon_radius = cast(list[float], list(bounding_circle))
|
| 958 |
+
elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
|
| 959 |
+
if not all(
|
| 960 |
+
isinstance(i, (int, float)) for i in bounding_circle[0]
|
| 961 |
+
) or not isinstance(bounding_circle[1], (int, float)):
|
| 962 |
+
msg = "bounding_circle should only contain numeric data"
|
| 963 |
+
raise ValueError(msg)
|
| 964 |
+
|
| 965 |
+
if len(bounding_circle[0]) != 2:
|
| 966 |
+
msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
|
| 967 |
+
raise ValueError(msg)
|
| 968 |
+
|
| 969 |
+
centroid = cast(list[float], list(bounding_circle[0]))
|
| 970 |
+
polygon_radius = cast(float, bounding_circle[1])
|
| 971 |
+
else:
|
| 972 |
+
msg = (
|
| 973 |
+
"bounding_circle should contain 2D coordinates "
|
| 974 |
+
"and a radius (e.g. (x, y, r) or ((x, y), r) )"
|
| 975 |
+
)
|
| 976 |
+
raise ValueError(msg)
|
| 977 |
+
|
| 978 |
+
if polygon_radius <= 0:
|
| 979 |
+
msg = "bounding_circle radius should be > 0"
|
| 980 |
+
raise ValueError(msg)
|
| 981 |
+
|
| 982 |
+
# 1.3 Check `rotation` has an appropriate value
|
| 983 |
+
if not isinstance(rotation, (int, float)):
|
| 984 |
+
msg = "rotation should be an int or float" # type: ignore[unreachable]
|
| 985 |
+
raise ValueError(msg)
|
| 986 |
+
|
| 987 |
+
# 2. Define Helper Functions
|
| 988 |
+
def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
|
| 989 |
+
return (
|
| 990 |
+
round(
|
| 991 |
+
point[0] * math.cos(math.radians(360 - degrees))
|
| 992 |
+
- point[1] * math.sin(math.radians(360 - degrees))
|
| 993 |
+
+ centroid[0],
|
| 994 |
+
2,
|
| 995 |
+
),
|
| 996 |
+
round(
|
| 997 |
+
point[1] * math.cos(math.radians(360 - degrees))
|
| 998 |
+
+ point[0] * math.sin(math.radians(360 - degrees))
|
| 999 |
+
+ centroid[1],
|
| 1000 |
+
2,
|
| 1001 |
+
),
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
|
| 1005 |
+
start_point = [polygon_radius, 0]
|
| 1006 |
+
return _apply_rotation(start_point, angle)
|
| 1007 |
+
|
| 1008 |
+
def _get_angles(n_sides: int, rotation: float) -> list[float]:
|
| 1009 |
+
angles = []
|
| 1010 |
+
degrees = 360 / n_sides
|
| 1011 |
+
# Start with the bottom left polygon vertex
|
| 1012 |
+
current_angle = (270 - 0.5 * degrees) + rotation
|
| 1013 |
+
for _ in range(n_sides):
|
| 1014 |
+
angles.append(current_angle)
|
| 1015 |
+
current_angle += degrees
|
| 1016 |
+
if current_angle > 360:
|
| 1017 |
+
current_angle -= 360
|
| 1018 |
+
return angles
|
| 1019 |
+
|
| 1020 |
+
# 3. Variable Declarations
|
| 1021 |
+
angles = _get_angles(n_sides, rotation)
|
| 1022 |
+
|
| 1023 |
+
# 4. Compute Vertices
|
| 1024 |
+
return [_compute_polygon_vertex(angle) for angle in angles]
|
| 1025 |
+
|
| 1026 |
+
|
| 1027 |
+
def _color_diff(
|
| 1028 |
+
color1: float | tuple[int, ...], color2: float | tuple[int, ...]
|
| 1029 |
+
) -> float:
|
| 1030 |
+
"""
|
| 1031 |
+
Uses 1-norm distance to calculate difference between two values.
|
| 1032 |
+
"""
|
| 1033 |
+
first = color1 if isinstance(color1, tuple) else (color1,)
|
| 1034 |
+
second = color2 if isinstance(color2, tuple) else (color2,)
|
| 1035 |
+
|
| 1036 |
+
return sum(abs(first[i] - second[i]) for i in range(len(second)))
|
.venv/lib/python3.12/site-packages/PIL/ImageDraw2.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Any, AnyStr, BinaryIO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
|
| 30 |
+
from ._typing import Coords, 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: tuple[float, float, float, float, float, float] | None = None
|
| 78 |
+
|
| 79 |
+
def flush(self) -> Image.Image:
|
| 80 |
+
return self.image
|
| 81 |
+
|
| 82 |
+
def render(
|
| 83 |
+
self,
|
| 84 |
+
op: str,
|
| 85 |
+
xy: Coords,
|
| 86 |
+
pen: Pen | Brush | None,
|
| 87 |
+
brush: Brush | Pen | None = None,
|
| 88 |
+
**kwargs: Any,
|
| 89 |
+
) -> None:
|
| 90 |
+
# handle color arguments
|
| 91 |
+
outline = fill = None
|
| 92 |
+
width = 1
|
| 93 |
+
if isinstance(pen, Pen):
|
| 94 |
+
outline = pen.color
|
| 95 |
+
width = pen.width
|
| 96 |
+
elif isinstance(brush, Pen):
|
| 97 |
+
outline = brush.color
|
| 98 |
+
width = brush.width
|
| 99 |
+
if isinstance(brush, Brush):
|
| 100 |
+
fill = brush.color
|
| 101 |
+
elif isinstance(pen, Brush):
|
| 102 |
+
fill = pen.color
|
| 103 |
+
# handle transformation
|
| 104 |
+
if self.transform:
|
| 105 |
+
path = ImagePath.Path(xy)
|
| 106 |
+
path.transform(self.transform)
|
| 107 |
+
xy = path
|
| 108 |
+
# render the item
|
| 109 |
+
if op in ("arc", "line"):
|
| 110 |
+
kwargs.setdefault("fill", outline)
|
| 111 |
+
else:
|
| 112 |
+
kwargs.setdefault("fill", fill)
|
| 113 |
+
kwargs.setdefault("outline", outline)
|
| 114 |
+
if op == "line":
|
| 115 |
+
kwargs.setdefault("width", width)
|
| 116 |
+
getattr(self.draw, op)(xy, **kwargs)
|
| 117 |
+
|
| 118 |
+
def settransform(self, offset: tuple[float, float]) -> None:
|
| 119 |
+
"""Sets a transformation offset."""
|
| 120 |
+
(xoffset, yoffset) = offset
|
| 121 |
+
self.transform = (1, 0, xoffset, 0, 1, yoffset)
|
| 122 |
+
|
| 123 |
+
def arc(
|
| 124 |
+
self,
|
| 125 |
+
xy: Coords,
|
| 126 |
+
pen: Pen | Brush | None,
|
| 127 |
+
start: float,
|
| 128 |
+
end: float,
|
| 129 |
+
*options: Any,
|
| 130 |
+
) -> None:
|
| 131 |
+
"""
|
| 132 |
+
Draws an arc (a portion of a circle outline) between the start and end
|
| 133 |
+
angles, inside the given bounding box.
|
| 134 |
+
|
| 135 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
| 136 |
+
"""
|
| 137 |
+
self.render("arc", xy, pen, *options, start=start, end=end)
|
| 138 |
+
|
| 139 |
+
def chord(
|
| 140 |
+
self,
|
| 141 |
+
xy: Coords,
|
| 142 |
+
pen: Pen | Brush | None,
|
| 143 |
+
start: float,
|
| 144 |
+
end: float,
|
| 145 |
+
*options: Any,
|
| 146 |
+
) -> None:
|
| 147 |
+
"""
|
| 148 |
+
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
|
| 149 |
+
with a straight line.
|
| 150 |
+
|
| 151 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
| 152 |
+
"""
|
| 153 |
+
self.render("chord", xy, pen, *options, start=start, end=end)
|
| 154 |
+
|
| 155 |
+
def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 156 |
+
"""
|
| 157 |
+
Draws an ellipse inside the given bounding box.
|
| 158 |
+
|
| 159 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
| 160 |
+
"""
|
| 161 |
+
self.render("ellipse", xy, pen, *options)
|
| 162 |
+
|
| 163 |
+
def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 164 |
+
"""
|
| 165 |
+
Draws a line between the coordinates in the ``xy`` list.
|
| 166 |
+
|
| 167 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
| 168 |
+
"""
|
| 169 |
+
self.render("line", xy, pen, *options)
|
| 170 |
+
|
| 171 |
+
def pieslice(
|
| 172 |
+
self,
|
| 173 |
+
xy: Coords,
|
| 174 |
+
pen: Pen | Brush | None,
|
| 175 |
+
start: float,
|
| 176 |
+
end: float,
|
| 177 |
+
*options: Any,
|
| 178 |
+
) -> None:
|
| 179 |
+
"""
|
| 180 |
+
Same as arc, but also draws straight lines between the end points and the
|
| 181 |
+
center of the bounding box.
|
| 182 |
+
|
| 183 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
| 184 |
+
"""
|
| 185 |
+
self.render("pieslice", xy, pen, *options, start=start, end=end)
|
| 186 |
+
|
| 187 |
+
def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 188 |
+
"""
|
| 189 |
+
Draws a polygon.
|
| 190 |
+
|
| 191 |
+
The polygon outline consists of straight lines between the given
|
| 192 |
+
coordinates, plus a straight line between the last and the first
|
| 193 |
+
coordinate.
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
| 197 |
+
"""
|
| 198 |
+
self.render("polygon", xy, pen, *options)
|
| 199 |
+
|
| 200 |
+
def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 201 |
+
"""
|
| 202 |
+
Draws a rectangle.
|
| 203 |
+
|
| 204 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
| 205 |
+
"""
|
| 206 |
+
self.render("rectangle", xy, pen, *options)
|
| 207 |
+
|
| 208 |
+
def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
|
| 209 |
+
"""
|
| 210 |
+
Draws the string at the given position.
|
| 211 |
+
|
| 212 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
| 213 |
+
"""
|
| 214 |
+
if self.transform:
|
| 215 |
+
path = ImagePath.Path(xy)
|
| 216 |
+
path.transform(self.transform)
|
| 217 |
+
xy = path
|
| 218 |
+
self.draw.text(xy, text, font=font.font, fill=font.color)
|
| 219 |
+
|
| 220 |
+
def textbbox(
|
| 221 |
+
self, xy: tuple[float, float], text: AnyStr, font: Font
|
| 222 |
+
) -> tuple[float, float, float, float]:
|
| 223 |
+
"""
|
| 224 |
+
Returns bounding box (in pixels) of given text.
|
| 225 |
+
|
| 226 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 227 |
+
|
| 228 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
|
| 229 |
+
"""
|
| 230 |
+
if self.transform:
|
| 231 |
+
path = ImagePath.Path(xy)
|
| 232 |
+
path.transform(self.transform)
|
| 233 |
+
xy = path
|
| 234 |
+
return self.draw.textbbox(xy, text, font=font.font)
|
| 235 |
+
|
| 236 |
+
def textlength(self, text: AnyStr, font: Font) -> float:
|
| 237 |
+
"""
|
| 238 |
+
Returns length (in pixels) of given text.
|
| 239 |
+
This is the amount by which following text should be offset.
|
| 240 |
+
|
| 241 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
|
| 242 |
+
"""
|
| 243 |
+
return self.draw.textlength(text, font=font.font)
|
.venv/lib/python3.12/site-packages/PIL/ImageEnhance.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
if self.intermediate_mode != image.mode:
|
| 59 |
+
image = image.convert(self.intermediate_mode).convert(image.mode)
|
| 60 |
+
self.degenerate = image
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Contrast(_Enhance):
|
| 64 |
+
"""Adjust image contrast.
|
| 65 |
+
|
| 66 |
+
This class can be used to control the contrast of an image, similar
|
| 67 |
+
to the contrast control on a TV set. An enhancement factor of 0.0
|
| 68 |
+
gives a solid gray image. A factor of 1.0 gives the original image.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(self, image: Image.Image) -> None:
|
| 72 |
+
self.image = image
|
| 73 |
+
if image.mode != "L":
|
| 74 |
+
image = image.convert("L")
|
| 75 |
+
mean = int(ImageStat.Stat(image).mean[0] + 0.5)
|
| 76 |
+
self.degenerate = Image.new("L", image.size, mean)
|
| 77 |
+
if self.degenerate.mode != self.image.mode:
|
| 78 |
+
self.degenerate = self.degenerate.convert(self.image.mode)
|
| 79 |
+
|
| 80 |
+
if "A" in self.image.getbands():
|
| 81 |
+
self.degenerate.putalpha(self.image.getchannel("A"))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Brightness(_Enhance):
|
| 85 |
+
"""Adjust image brightness.
|
| 86 |
+
|
| 87 |
+
This class can be used to control the brightness of an image. An
|
| 88 |
+
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
|
| 89 |
+
original image.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def __init__(self, image: Image.Image) -> None:
|
| 93 |
+
self.image = image
|
| 94 |
+
self.degenerate = Image.new(image.mode, image.size, 0)
|
| 95 |
+
|
| 96 |
+
if "A" in image.getbands():
|
| 97 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class Sharpness(_Enhance):
|
| 101 |
+
"""Adjust image sharpness.
|
| 102 |
+
|
| 103 |
+
This class can be used to adjust the sharpness of an image. An
|
| 104 |
+
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
|
| 105 |
+
original image, and a factor of 2.0 gives a sharpened image.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, image: Image.Image) -> None:
|
| 109 |
+
self.image = image
|
| 110 |
+
self.degenerate = image.filter(ImageFilter.SMOOTH)
|
| 111 |
+
|
| 112 |
+
if "A" in image.getbands():
|
| 113 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
.venv/lib/python3.12/site-packages/PIL/ImageFilter.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 collections.abc import Sequence
|
| 22 |
+
from typing import cast
|
| 23 |
+
|
| 24 |
+
TYPE_CHECKING = False
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from collections.abc import Callable
|
| 27 |
+
from types import ModuleType
|
| 28 |
+
from typing import Any
|
| 29 |
+
|
| 30 |
+
from . import _imaging
|
| 31 |
+
from ._typing import NumpyArray
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Filter(abc.ABC):
|
| 35 |
+
@abc.abstractmethod
|
| 36 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class MultibandFilter(Filter):
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class BuiltinFilter(MultibandFilter):
|
| 45 |
+
filterargs: tuple[Any, ...]
|
| 46 |
+
|
| 47 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 48 |
+
if image.mode == "P":
|
| 49 |
+
msg = "cannot filter palette images"
|
| 50 |
+
raise ValueError(msg)
|
| 51 |
+
return image.filter(*self.filterargs)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Kernel(BuiltinFilter):
|
| 55 |
+
"""
|
| 56 |
+
Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
|
| 57 |
+
point kernels.
|
| 58 |
+
|
| 59 |
+
Kernels can only be applied to "L" and "RGB" images.
|
| 60 |
+
|
| 61 |
+
:param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
|
| 62 |
+
:param kernel: A sequence containing kernel weights. The kernel will be flipped
|
| 63 |
+
vertically before being applied to the image.
|
| 64 |
+
:param scale: Scale factor. If given, the result for each pixel is divided by this
|
| 65 |
+
value. The default is the sum of the kernel weights.
|
| 66 |
+
:param offset: Offset. If given, this value is added to the result, after it has
|
| 67 |
+
been divided by the scale factor.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
name = "Kernel"
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
size: tuple[int, int],
|
| 75 |
+
kernel: Sequence[float],
|
| 76 |
+
scale: float | None = None,
|
| 77 |
+
offset: float = 0,
|
| 78 |
+
) -> None:
|
| 79 |
+
if scale is None:
|
| 80 |
+
# default scale is sum of kernel
|
| 81 |
+
scale = functools.reduce(lambda a, b: a + b, kernel)
|
| 82 |
+
if size[0] * size[1] != len(kernel):
|
| 83 |
+
msg = "not enough coefficients in kernel"
|
| 84 |
+
raise ValueError(msg)
|
| 85 |
+
self.filterargs = size, scale, offset, kernel
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class RankFilter(Filter):
|
| 89 |
+
"""
|
| 90 |
+
Create a rank filter. The rank filter sorts all pixels in
|
| 91 |
+
a window of the given size, and returns the ``rank``'th value.
|
| 92 |
+
|
| 93 |
+
:param size: The kernel size, in pixels.
|
| 94 |
+
:param rank: What pixel value to pick. Use 0 for a min filter,
|
| 95 |
+
``size * size / 2`` for a median filter, ``size * size - 1``
|
| 96 |
+
for a max filter, etc.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
name = "Rank"
|
| 100 |
+
|
| 101 |
+
def __init__(self, size: int, rank: int) -> None:
|
| 102 |
+
self.size = size
|
| 103 |
+
self.rank = rank
|
| 104 |
+
|
| 105 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 106 |
+
if image.mode == "P":
|
| 107 |
+
msg = "cannot filter palette images"
|
| 108 |
+
raise ValueError(msg)
|
| 109 |
+
image = image.expand(self.size // 2, self.size // 2)
|
| 110 |
+
return image.rankfilter(self.size, self.rank)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class MedianFilter(RankFilter):
|
| 114 |
+
"""
|
| 115 |
+
Create a median filter. Picks the median pixel value in a window with the
|
| 116 |
+
given size.
|
| 117 |
+
|
| 118 |
+
:param size: The kernel size, in pixels.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
name = "Median"
|
| 122 |
+
|
| 123 |
+
def __init__(self, size: int = 3) -> None:
|
| 124 |
+
self.size = size
|
| 125 |
+
self.rank = size * size // 2
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class MinFilter(RankFilter):
|
| 129 |
+
"""
|
| 130 |
+
Create a min filter. Picks the lowest pixel value in a window with the
|
| 131 |
+
given size.
|
| 132 |
+
|
| 133 |
+
:param size: The kernel size, in pixels.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
name = "Min"
|
| 137 |
+
|
| 138 |
+
def __init__(self, size: int = 3) -> None:
|
| 139 |
+
self.size = size
|
| 140 |
+
self.rank = 0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class MaxFilter(RankFilter):
|
| 144 |
+
"""
|
| 145 |
+
Create a max filter. Picks the largest pixel value in a window with the
|
| 146 |
+
given size.
|
| 147 |
+
|
| 148 |
+
:param size: The kernel size, in pixels.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
name = "Max"
|
| 152 |
+
|
| 153 |
+
def __init__(self, size: int = 3) -> None:
|
| 154 |
+
self.size = size
|
| 155 |
+
self.rank = size * size - 1
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class ModeFilter(Filter):
|
| 159 |
+
"""
|
| 160 |
+
Create a mode filter. Picks the most frequent pixel value in a box with the
|
| 161 |
+
given size. Pixel values that occur only once or twice are ignored; if no
|
| 162 |
+
pixel value occurs more than twice, the original pixel value is preserved.
|
| 163 |
+
|
| 164 |
+
:param size: The kernel size, in pixels.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
name = "Mode"
|
| 168 |
+
|
| 169 |
+
def __init__(self, size: int = 3) -> None:
|
| 170 |
+
self.size = size
|
| 171 |
+
|
| 172 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 173 |
+
return image.modefilter(self.size)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class GaussianBlur(MultibandFilter):
|
| 177 |
+
"""Blurs the image with a sequence of extended box filters, which
|
| 178 |
+
approximates a Gaussian kernel. For details on accuracy see
|
| 179 |
+
<https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
|
| 180 |
+
|
| 181 |
+
:param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
|
| 182 |
+
numbers for x and y, or a single number for both.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
name = "GaussianBlur"
|
| 186 |
+
|
| 187 |
+
def __init__(self, radius: float | Sequence[float] = 2) -> None:
|
| 188 |
+
self.radius = radius
|
| 189 |
+
|
| 190 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 191 |
+
xy = self.radius
|
| 192 |
+
if isinstance(xy, (int, float)):
|
| 193 |
+
xy = (xy, xy)
|
| 194 |
+
if xy == (0, 0):
|
| 195 |
+
return image.copy()
|
| 196 |
+
return image.gaussian_blur(xy)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class BoxBlur(MultibandFilter):
|
| 200 |
+
"""Blurs the image by setting each pixel to the average value of the pixels
|
| 201 |
+
in a square box extending radius pixels in each direction.
|
| 202 |
+
Supports float radius of arbitrary size. Uses an optimized implementation
|
| 203 |
+
which runs in linear time relative to the size of the image
|
| 204 |
+
for any radius value.
|
| 205 |
+
|
| 206 |
+
:param radius: Size of the box in a direction. Either a sequence of two numbers for
|
| 207 |
+
x and y, or a single number for both.
|
| 208 |
+
|
| 209 |
+
Radius 0 does not blur, returns an identical image.
|
| 210 |
+
Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
name = "BoxBlur"
|
| 214 |
+
|
| 215 |
+
def __init__(self, radius: float | Sequence[float]) -> None:
|
| 216 |
+
xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
|
| 217 |
+
if xy[0] < 0 or xy[1] < 0:
|
| 218 |
+
msg = "radius must be >= 0"
|
| 219 |
+
raise ValueError(msg)
|
| 220 |
+
self.radius = radius
|
| 221 |
+
|
| 222 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 223 |
+
xy = self.radius
|
| 224 |
+
if isinstance(xy, (int, float)):
|
| 225 |
+
xy = (xy, xy)
|
| 226 |
+
if xy == (0, 0):
|
| 227 |
+
return image.copy()
|
| 228 |
+
return image.box_blur(xy)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class UnsharpMask(MultibandFilter):
|
| 232 |
+
"""Unsharp mask filter.
|
| 233 |
+
|
| 234 |
+
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
|
| 235 |
+
the parameters.
|
| 236 |
+
|
| 237 |
+
:param radius: Blur Radius
|
| 238 |
+
:param percent: Unsharp strength, in percent
|
| 239 |
+
:param threshold: Threshold controls the minimum brightness change that
|
| 240 |
+
will be sharpened
|
| 241 |
+
|
| 242 |
+
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
|
| 243 |
+
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
name = "UnsharpMask"
|
| 247 |
+
|
| 248 |
+
def __init__(
|
| 249 |
+
self, radius: float = 2, percent: int = 150, threshold: int = 3
|
| 250 |
+
) -> None:
|
| 251 |
+
self.radius = radius
|
| 252 |
+
self.percent = percent
|
| 253 |
+
self.threshold = threshold
|
| 254 |
+
|
| 255 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 256 |
+
return image.unsharp_mask(self.radius, self.percent, self.threshold)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class BLUR(BuiltinFilter):
|
| 260 |
+
name = "Blur"
|
| 261 |
+
# fmt: off
|
| 262 |
+
filterargs = (5, 5), 16, 0, (
|
| 263 |
+
1, 1, 1, 1, 1,
|
| 264 |
+
1, 0, 0, 0, 1,
|
| 265 |
+
1, 0, 0, 0, 1,
|
| 266 |
+
1, 0, 0, 0, 1,
|
| 267 |
+
1, 1, 1, 1, 1,
|
| 268 |
+
)
|
| 269 |
+
# fmt: on
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class CONTOUR(BuiltinFilter):
|
| 273 |
+
name = "Contour"
|
| 274 |
+
# fmt: off
|
| 275 |
+
filterargs = (3, 3), 1, 255, (
|
| 276 |
+
-1, -1, -1,
|
| 277 |
+
-1, 8, -1,
|
| 278 |
+
-1, -1, -1,
|
| 279 |
+
)
|
| 280 |
+
# fmt: on
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class DETAIL(BuiltinFilter):
|
| 284 |
+
name = "Detail"
|
| 285 |
+
# fmt: off
|
| 286 |
+
filterargs = (3, 3), 6, 0, (
|
| 287 |
+
0, -1, 0,
|
| 288 |
+
-1, 10, -1,
|
| 289 |
+
0, -1, 0,
|
| 290 |
+
)
|
| 291 |
+
# fmt: on
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class EDGE_ENHANCE(BuiltinFilter):
|
| 295 |
+
name = "Edge-enhance"
|
| 296 |
+
# fmt: off
|
| 297 |
+
filterargs = (3, 3), 2, 0, (
|
| 298 |
+
-1, -1, -1,
|
| 299 |
+
-1, 10, -1,
|
| 300 |
+
-1, -1, -1,
|
| 301 |
+
)
|
| 302 |
+
# fmt: on
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class EDGE_ENHANCE_MORE(BuiltinFilter):
|
| 306 |
+
name = "Edge-enhance More"
|
| 307 |
+
# fmt: off
|
| 308 |
+
filterargs = (3, 3), 1, 0, (
|
| 309 |
+
-1, -1, -1,
|
| 310 |
+
-1, 9, -1,
|
| 311 |
+
-1, -1, -1,
|
| 312 |
+
)
|
| 313 |
+
# fmt: on
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class EMBOSS(BuiltinFilter):
|
| 317 |
+
name = "Emboss"
|
| 318 |
+
# fmt: off
|
| 319 |
+
filterargs = (3, 3), 1, 128, (
|
| 320 |
+
-1, 0, 0,
|
| 321 |
+
0, 1, 0,
|
| 322 |
+
0, 0, 0,
|
| 323 |
+
)
|
| 324 |
+
# fmt: on
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class FIND_EDGES(BuiltinFilter):
|
| 328 |
+
name = "Find Edges"
|
| 329 |
+
# fmt: off
|
| 330 |
+
filterargs = (3, 3), 1, 0, (
|
| 331 |
+
-1, -1, -1,
|
| 332 |
+
-1, 8, -1,
|
| 333 |
+
-1, -1, -1,
|
| 334 |
+
)
|
| 335 |
+
# fmt: on
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class SHARPEN(BuiltinFilter):
|
| 339 |
+
name = "Sharpen"
|
| 340 |
+
# fmt: off
|
| 341 |
+
filterargs = (3, 3), 16, 0, (
|
| 342 |
+
-2, -2, -2,
|
| 343 |
+
-2, 32, -2,
|
| 344 |
+
-2, -2, -2,
|
| 345 |
+
)
|
| 346 |
+
# fmt: on
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class SMOOTH(BuiltinFilter):
|
| 350 |
+
name = "Smooth"
|
| 351 |
+
# fmt: off
|
| 352 |
+
filterargs = (3, 3), 13, 0, (
|
| 353 |
+
1, 1, 1,
|
| 354 |
+
1, 5, 1,
|
| 355 |
+
1, 1, 1,
|
| 356 |
+
)
|
| 357 |
+
# fmt: on
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class SMOOTH_MORE(BuiltinFilter):
|
| 361 |
+
name = "Smooth More"
|
| 362 |
+
# fmt: off
|
| 363 |
+
filterargs = (5, 5), 100, 0, (
|
| 364 |
+
1, 1, 1, 1, 1,
|
| 365 |
+
1, 5, 5, 5, 1,
|
| 366 |
+
1, 5, 44, 5, 1,
|
| 367 |
+
1, 5, 5, 5, 1,
|
| 368 |
+
1, 1, 1, 1, 1,
|
| 369 |
+
)
|
| 370 |
+
# fmt: on
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class Color3DLUT(MultibandFilter):
|
| 374 |
+
"""Three-dimensional color lookup table.
|
| 375 |
+
|
| 376 |
+
Transforms 3-channel pixels using the values of the channels as coordinates
|
| 377 |
+
in the 3D lookup table and interpolating the nearest elements.
|
| 378 |
+
|
| 379 |
+
This method allows you to apply almost any color transformation
|
| 380 |
+
in constant time by using pre-calculated decimated tables.
|
| 381 |
+
|
| 382 |
+
.. versionadded:: 5.2.0
|
| 383 |
+
|
| 384 |
+
:param size: Size of the table. One int or tuple of (int, int, int).
|
| 385 |
+
Minimal size in any dimension is 2, maximum is 65.
|
| 386 |
+
:param table: Flat lookup table. A list of ``channels * size**3``
|
| 387 |
+
float elements or a list of ``size**3`` channels-sized
|
| 388 |
+
tuples with floats. Channels are changed first,
|
| 389 |
+
then first dimension, then second, then third.
|
| 390 |
+
Value 0.0 corresponds lowest value of output, 1.0 highest.
|
| 391 |
+
:param channels: Number of channels in the table. Could be 3 or 4.
|
| 392 |
+
Default is 3.
|
| 393 |
+
:param target_mode: A mode for the result image. Should have not less
|
| 394 |
+
than ``channels`` channels. Default is ``None``,
|
| 395 |
+
which means that mode wouldn't be changed.
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
name = "Color 3D LUT"
|
| 399 |
+
|
| 400 |
+
def __init__(
|
| 401 |
+
self,
|
| 402 |
+
size: int | tuple[int, int, int],
|
| 403 |
+
table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
|
| 404 |
+
channels: int = 3,
|
| 405 |
+
target_mode: str | None = None,
|
| 406 |
+
**kwargs: bool,
|
| 407 |
+
) -> None:
|
| 408 |
+
if channels not in (3, 4):
|
| 409 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 410 |
+
raise ValueError(msg)
|
| 411 |
+
self.size = size = self._check_size(size)
|
| 412 |
+
self.channels = channels
|
| 413 |
+
self.mode = target_mode
|
| 414 |
+
|
| 415 |
+
# Hidden flag `_copy_table=False` could be used to avoid extra copying
|
| 416 |
+
# of the table if the table is specially made for the constructor.
|
| 417 |
+
copy_table = kwargs.get("_copy_table", True)
|
| 418 |
+
items = size[0] * size[1] * size[2]
|
| 419 |
+
wrong_size = False
|
| 420 |
+
|
| 421 |
+
numpy: ModuleType | None = None
|
| 422 |
+
if hasattr(table, "shape"):
|
| 423 |
+
try:
|
| 424 |
+
import numpy
|
| 425 |
+
except ImportError:
|
| 426 |
+
pass
|
| 427 |
+
|
| 428 |
+
if numpy and isinstance(table, numpy.ndarray):
|
| 429 |
+
numpy_table: NumpyArray = table
|
| 430 |
+
if copy_table:
|
| 431 |
+
numpy_table = numpy_table.copy()
|
| 432 |
+
|
| 433 |
+
if numpy_table.shape in [
|
| 434 |
+
(items * channels,),
|
| 435 |
+
(items, channels),
|
| 436 |
+
(size[2], size[1], size[0], channels),
|
| 437 |
+
]:
|
| 438 |
+
table = numpy_table.reshape(items * channels)
|
| 439 |
+
else:
|
| 440 |
+
wrong_size = True
|
| 441 |
+
|
| 442 |
+
else:
|
| 443 |
+
if copy_table:
|
| 444 |
+
table = list(table)
|
| 445 |
+
|
| 446 |
+
# Convert to a flat list
|
| 447 |
+
if table and isinstance(table[0], (list, tuple)):
|
| 448 |
+
raw_table = cast(Sequence[Sequence[int]], table)
|
| 449 |
+
flat_table: list[int] = []
|
| 450 |
+
for pixel in raw_table:
|
| 451 |
+
if len(pixel) != channels:
|
| 452 |
+
msg = (
|
| 453 |
+
"The elements of the table should "
|
| 454 |
+
f"have a length of {channels}."
|
| 455 |
+
)
|
| 456 |
+
raise ValueError(msg)
|
| 457 |
+
flat_table.extend(pixel)
|
| 458 |
+
table = flat_table
|
| 459 |
+
|
| 460 |
+
if wrong_size or len(table) != items * channels:
|
| 461 |
+
msg = (
|
| 462 |
+
"The table should have either channels * size**3 float items "
|
| 463 |
+
"or size**3 items of channels-sized tuples with floats. "
|
| 464 |
+
f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
|
| 465 |
+
f"Actual length: {len(table)}"
|
| 466 |
+
)
|
| 467 |
+
raise ValueError(msg)
|
| 468 |
+
self.table = table
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def _check_size(size: Any) -> tuple[int, int, int]:
|
| 472 |
+
try:
|
| 473 |
+
_, _, _ = size
|
| 474 |
+
except ValueError as e:
|
| 475 |
+
msg = "Size should be either an integer or a tuple of three integers."
|
| 476 |
+
raise ValueError(msg) from e
|
| 477 |
+
except TypeError:
|
| 478 |
+
size = (size, size, size)
|
| 479 |
+
size = tuple(int(x) for x in size)
|
| 480 |
+
for size_1d in size:
|
| 481 |
+
if not 2 <= size_1d <= 65:
|
| 482 |
+
msg = "Size should be in [2, 65] range."
|
| 483 |
+
raise ValueError(msg)
|
| 484 |
+
return size
|
| 485 |
+
|
| 486 |
+
@classmethod
|
| 487 |
+
def generate(
|
| 488 |
+
cls,
|
| 489 |
+
size: int | tuple[int, int, int],
|
| 490 |
+
callback: Callable[[float, float, float], tuple[float, ...]],
|
| 491 |
+
channels: int = 3,
|
| 492 |
+
target_mode: str | None = None,
|
| 493 |
+
) -> Color3DLUT:
|
| 494 |
+
"""Generates new LUT using provided callback.
|
| 495 |
+
|
| 496 |
+
:param size: Size of the table. Passed to the constructor.
|
| 497 |
+
:param callback: Function with three parameters which correspond
|
| 498 |
+
three color channels. Will be called ``size**3``
|
| 499 |
+
times with values from 0.0 to 1.0 and should return
|
| 500 |
+
a tuple with ``channels`` elements.
|
| 501 |
+
:param channels: The number of channels which should return callback.
|
| 502 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 503 |
+
lookup table.
|
| 504 |
+
"""
|
| 505 |
+
size_1d, size_2d, size_3d = cls._check_size(size)
|
| 506 |
+
if channels not in (3, 4):
|
| 507 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 508 |
+
raise ValueError(msg)
|
| 509 |
+
|
| 510 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
|
| 511 |
+
idx_out = 0
|
| 512 |
+
for b in range(size_3d):
|
| 513 |
+
for g in range(size_2d):
|
| 514 |
+
for r in range(size_1d):
|
| 515 |
+
table[idx_out : idx_out + channels] = callback(
|
| 516 |
+
r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
|
| 517 |
+
)
|
| 518 |
+
idx_out += channels
|
| 519 |
+
|
| 520 |
+
return cls(
|
| 521 |
+
(size_1d, size_2d, size_3d),
|
| 522 |
+
table,
|
| 523 |
+
channels=channels,
|
| 524 |
+
target_mode=target_mode,
|
| 525 |
+
_copy_table=False,
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
def transform(
|
| 529 |
+
self,
|
| 530 |
+
callback: Callable[..., tuple[float, ...]],
|
| 531 |
+
with_normals: bool = False,
|
| 532 |
+
channels: int | None = None,
|
| 533 |
+
target_mode: str | None = None,
|
| 534 |
+
) -> Color3DLUT:
|
| 535 |
+
"""Transforms the table values using provided callback and returns
|
| 536 |
+
a new LUT with altered values.
|
| 537 |
+
|
| 538 |
+
:param callback: A function which takes old lookup table values
|
| 539 |
+
and returns a new set of values. The number
|
| 540 |
+
of arguments which function should take is
|
| 541 |
+
``self.channels`` or ``3 + self.channels``
|
| 542 |
+
if ``with_normals`` flag is set.
|
| 543 |
+
Should return a tuple of ``self.channels`` or
|
| 544 |
+
``channels`` elements if it is set.
|
| 545 |
+
:param with_normals: If true, ``callback`` will be called with
|
| 546 |
+
coordinates in the color cube as the first
|
| 547 |
+
three arguments. Otherwise, ``callback``
|
| 548 |
+
will be called only with actual color values.
|
| 549 |
+
:param channels: The number of channels in the resulting lookup table.
|
| 550 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 551 |
+
lookup table.
|
| 552 |
+
"""
|
| 553 |
+
if channels not in (None, 3, 4):
|
| 554 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 555 |
+
raise ValueError(msg)
|
| 556 |
+
ch_in = self.channels
|
| 557 |
+
ch_out = channels or ch_in
|
| 558 |
+
size_1d, size_2d, size_3d = self.size
|
| 559 |
+
|
| 560 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
|
| 561 |
+
idx_in = 0
|
| 562 |
+
idx_out = 0
|
| 563 |
+
for b in range(size_3d):
|
| 564 |
+
for g in range(size_2d):
|
| 565 |
+
for r in range(size_1d):
|
| 566 |
+
values = self.table[idx_in : idx_in + ch_in]
|
| 567 |
+
if with_normals:
|
| 568 |
+
values = callback(
|
| 569 |
+
r / (size_1d - 1),
|
| 570 |
+
g / (size_2d - 1),
|
| 571 |
+
b / (size_3d - 1),
|
| 572 |
+
*values,
|
| 573 |
+
)
|
| 574 |
+
else:
|
| 575 |
+
values = callback(*values)
|
| 576 |
+
table[idx_out : idx_out + ch_out] = values
|
| 577 |
+
idx_in += ch_in
|
| 578 |
+
idx_out += ch_out
|
| 579 |
+
|
| 580 |
+
return type(self)(
|
| 581 |
+
self.size,
|
| 582 |
+
table,
|
| 583 |
+
channels=ch_out,
|
| 584 |
+
target_mode=target_mode or self.mode,
|
| 585 |
+
_copy_table=False,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def __repr__(self) -> str:
|
| 589 |
+
r = [
|
| 590 |
+
f"{self.__class__.__name__} from {self.table.__class__.__name__}",
|
| 591 |
+
"size={:d}x{:d}x{:d}".format(*self.size),
|
| 592 |
+
f"channels={self.channels:d}",
|
| 593 |
+
]
|
| 594 |
+
if self.mode:
|
| 595 |
+
r.append(f"target_mode={self.mode}")
|
| 596 |
+
return "<{}>".format(" ".join(r))
|
| 597 |
+
|
| 598 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 599 |
+
from . import Image
|
| 600 |
+
|
| 601 |
+
return image.color_lut_3d(
|
| 602 |
+
self.mode or image.mode,
|
| 603 |
+
Image.Resampling.BILINEAR,
|
| 604 |
+
self.channels,
|
| 605 |
+
self.size,
|
| 606 |
+
self.table,
|
| 607 |
+
)
|
.venv/lib/python3.12/site-packages/PIL/ImageGrab.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 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 |
+
TYPE_CHECKING = False
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from . import ImageWin
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def grab(
|
| 34 |
+
bbox: tuple[int, int, int, int] | None = None,
|
| 35 |
+
include_layered_windows: bool = False,
|
| 36 |
+
all_screens: bool = False,
|
| 37 |
+
xdisplay: str | None = None,
|
| 38 |
+
window: int | ImageWin.HWND | None = None,
|
| 39 |
+
) -> Image.Image:
|
| 40 |
+
im: Image.Image
|
| 41 |
+
if xdisplay is None:
|
| 42 |
+
if sys.platform == "darwin":
|
| 43 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 44 |
+
os.close(fh)
|
| 45 |
+
args = ["screencapture"]
|
| 46 |
+
if bbox:
|
| 47 |
+
left, top, right, bottom = bbox
|
| 48 |
+
args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
|
| 49 |
+
subprocess.call(args + ["-x", filepath])
|
| 50 |
+
im = Image.open(filepath)
|
| 51 |
+
im.load()
|
| 52 |
+
os.unlink(filepath)
|
| 53 |
+
if bbox:
|
| 54 |
+
im_resized = im.resize((right - left, bottom - top))
|
| 55 |
+
im.close()
|
| 56 |
+
return im_resized
|
| 57 |
+
return im
|
| 58 |
+
elif sys.platform == "win32":
|
| 59 |
+
if window is not None:
|
| 60 |
+
all_screens = -1
|
| 61 |
+
offset, size, data = Image.core.grabscreen_win32(
|
| 62 |
+
include_layered_windows,
|
| 63 |
+
all_screens,
|
| 64 |
+
int(window) if window is not None else 0,
|
| 65 |
+
)
|
| 66 |
+
im = Image.frombytes(
|
| 67 |
+
"RGB",
|
| 68 |
+
size,
|
| 69 |
+
data,
|
| 70 |
+
# RGB, 32-bit line padding, origin lower left corner
|
| 71 |
+
"raw",
|
| 72 |
+
"BGR",
|
| 73 |
+
(size[0] * 3 + 3) & -4,
|
| 74 |
+
-1,
|
| 75 |
+
)
|
| 76 |
+
if bbox:
|
| 77 |
+
x0, y0 = offset
|
| 78 |
+
left, top, right, bottom = bbox
|
| 79 |
+
im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
|
| 80 |
+
return im
|
| 81 |
+
# Cast to Optional[str] needed for Windows and macOS.
|
| 82 |
+
display_name: str | None = xdisplay
|
| 83 |
+
try:
|
| 84 |
+
if not Image.core.HAVE_XCB:
|
| 85 |
+
msg = "Pillow was built without XCB support"
|
| 86 |
+
raise OSError(msg)
|
| 87 |
+
size, data = Image.core.grabscreen_x11(display_name)
|
| 88 |
+
except OSError:
|
| 89 |
+
if display_name is None and sys.platform not in ("darwin", "win32"):
|
| 90 |
+
if shutil.which("gnome-screenshot"):
|
| 91 |
+
args = ["gnome-screenshot", "-f"]
|
| 92 |
+
elif shutil.which("grim"):
|
| 93 |
+
args = ["grim"]
|
| 94 |
+
elif shutil.which("spectacle"):
|
| 95 |
+
args = ["spectacle", "-n", "-b", "-f", "-o"]
|
| 96 |
+
else:
|
| 97 |
+
raise
|
| 98 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 99 |
+
os.close(fh)
|
| 100 |
+
subprocess.call(args + [filepath])
|
| 101 |
+
im = Image.open(filepath)
|
| 102 |
+
im.load()
|
| 103 |
+
os.unlink(filepath)
|
| 104 |
+
if bbox:
|
| 105 |
+
im_cropped = im.crop(bbox)
|
| 106 |
+
im.close()
|
| 107 |
+
return im_cropped
|
| 108 |
+
return im
|
| 109 |
+
else:
|
| 110 |
+
raise
|
| 111 |
+
else:
|
| 112 |
+
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
|
| 113 |
+
if bbox:
|
| 114 |
+
im = im.crop(bbox)
|
| 115 |
+
return im
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def grabclipboard() -> Image.Image | list[str] | None:
|
| 119 |
+
if sys.platform == "darwin":
|
| 120 |
+
p = subprocess.run(
|
| 121 |
+
["osascript", "-e", "get the clipboard as «class PNGf»"],
|
| 122 |
+
capture_output=True,
|
| 123 |
+
)
|
| 124 |
+
if p.returncode != 0:
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
import binascii
|
| 128 |
+
|
| 129 |
+
data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
|
| 130 |
+
return Image.open(data)
|
| 131 |
+
elif sys.platform == "win32":
|
| 132 |
+
fmt, data = Image.core.grabclipboard_win32()
|
| 133 |
+
if fmt == "file": # CF_HDROP
|
| 134 |
+
import struct
|
| 135 |
+
|
| 136 |
+
o = struct.unpack_from("I", data)[0]
|
| 137 |
+
if data[16] == 0:
|
| 138 |
+
files = data[o:].decode("mbcs").split("\0")
|
| 139 |
+
else:
|
| 140 |
+
files = data[o:].decode("utf-16le").split("\0")
|
| 141 |
+
return files[: files.index("")]
|
| 142 |
+
if isinstance(data, bytes):
|
| 143 |
+
data = io.BytesIO(data)
|
| 144 |
+
if fmt == "png":
|
| 145 |
+
from . import PngImagePlugin
|
| 146 |
+
|
| 147 |
+
return PngImagePlugin.PngImageFile(data)
|
| 148 |
+
elif fmt == "DIB":
|
| 149 |
+
from . import BmpImagePlugin
|
| 150 |
+
|
| 151 |
+
return BmpImagePlugin.DibImageFile(data)
|
| 152 |
+
return None
|
| 153 |
+
else:
|
| 154 |
+
if os.getenv("WAYLAND_DISPLAY"):
|
| 155 |
+
session_type = "wayland"
|
| 156 |
+
elif os.getenv("DISPLAY"):
|
| 157 |
+
session_type = "x11"
|
| 158 |
+
else: # Session type check failed
|
| 159 |
+
session_type = None
|
| 160 |
+
|
| 161 |
+
if shutil.which("wl-paste") and session_type in ("wayland", None):
|
| 162 |
+
args = ["wl-paste", "-t", "image"]
|
| 163 |
+
elif shutil.which("xclip") and session_type in ("x11", None):
|
| 164 |
+
args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
|
| 165 |
+
else:
|
| 166 |
+
msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
|
| 167 |
+
raise NotImplementedError(msg)
|
| 168 |
+
|
| 169 |
+
p = subprocess.run(args, capture_output=True)
|
| 170 |
+
if p.returncode != 0:
|
| 171 |
+
err = p.stderr
|
| 172 |
+
for silent_error in [
|
| 173 |
+
# wl-paste, when the clipboard is empty
|
| 174 |
+
b"Nothing is copied",
|
| 175 |
+
# Ubuntu/Debian wl-paste, when the clipboard is empty
|
| 176 |
+
b"No selection",
|
| 177 |
+
# Ubuntu/Debian wl-paste, when an image isn't available
|
| 178 |
+
b"No suitable type of content copied",
|
| 179 |
+
# wl-paste or Ubuntu/Debian xclip, when an image isn't available
|
| 180 |
+
b" not available",
|
| 181 |
+
# xclip, when an image isn't available
|
| 182 |
+
b"cannot convert ",
|
| 183 |
+
# xclip, when the clipboard isn't initialized
|
| 184 |
+
b"xclip: Error: There is no owner for the ",
|
| 185 |
+
]:
|
| 186 |
+
if silent_error in err:
|
| 187 |
+
return None
|
| 188 |
+
msg = f"{args[0]} error"
|
| 189 |
+
if err:
|
| 190 |
+
msg += f": {err.strip().decode()}"
|
| 191 |
+
raise ChildProcessError(msg)
|
| 192 |
+
|
| 193 |
+
data = io.BytesIO(p.stdout)
|
| 194 |
+
im = Image.open(data)
|
| 195 |
+
im.load()
|
| 196 |
+
return im
|
.venv/lib/python3.12/site-packages/PIL/ImageM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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 |
+
|
| 21 |
+
from . import Image, _imagingmath
|
| 22 |
+
|
| 23 |
+
TYPE_CHECKING = False
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from collections.abc import Callable
|
| 26 |
+
from types import CodeType
|
| 27 |
+
from typing import Any
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class _Operand:
|
| 31 |
+
"""Wraps an image operand, providing standard operators"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, im: Image.Image):
|
| 34 |
+
self.im = im
|
| 35 |
+
|
| 36 |
+
def __fixup(self, im1: _Operand | float) -> Image.Image:
|
| 37 |
+
# convert image to suitable mode
|
| 38 |
+
if isinstance(im1, _Operand):
|
| 39 |
+
# argument was an image.
|
| 40 |
+
if im1.im.mode in ("1", "L"):
|
| 41 |
+
return im1.im.convert("I")
|
| 42 |
+
elif im1.im.mode in ("I", "F"):
|
| 43 |
+
return im1.im
|
| 44 |
+
else:
|
| 45 |
+
msg = f"unsupported mode: {im1.im.mode}"
|
| 46 |
+
raise ValueError(msg)
|
| 47 |
+
else:
|
| 48 |
+
# argument was a constant
|
| 49 |
+
if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
|
| 50 |
+
return Image.new("I", self.im.size, im1)
|
| 51 |
+
else:
|
| 52 |
+
return Image.new("F", self.im.size, im1)
|
| 53 |
+
|
| 54 |
+
def apply(
|
| 55 |
+
self,
|
| 56 |
+
op: str,
|
| 57 |
+
im1: _Operand | float,
|
| 58 |
+
im2: _Operand | float | None = None,
|
| 59 |
+
mode: str | None = None,
|
| 60 |
+
) -> _Operand:
|
| 61 |
+
im_1 = self.__fixup(im1)
|
| 62 |
+
if im2 is None:
|
| 63 |
+
# unary operation
|
| 64 |
+
out = Image.new(mode or im_1.mode, im_1.size, None)
|
| 65 |
+
try:
|
| 66 |
+
op = getattr(_imagingmath, f"{op}_{im_1.mode}")
|
| 67 |
+
except AttributeError as e:
|
| 68 |
+
msg = f"bad operand type for '{op}'"
|
| 69 |
+
raise TypeError(msg) from e
|
| 70 |
+
_imagingmath.unop(op, out.getim(), im_1.getim())
|
| 71 |
+
else:
|
| 72 |
+
# binary operation
|
| 73 |
+
im_2 = self.__fixup(im2)
|
| 74 |
+
if im_1.mode != im_2.mode:
|
| 75 |
+
# convert both arguments to floating point
|
| 76 |
+
if im_1.mode != "F":
|
| 77 |
+
im_1 = im_1.convert("F")
|
| 78 |
+
if im_2.mode != "F":
|
| 79 |
+
im_2 = im_2.convert("F")
|
| 80 |
+
if im_1.size != im_2.size:
|
| 81 |
+
# crop both arguments to a common size
|
| 82 |
+
size = (
|
| 83 |
+
min(im_1.size[0], im_2.size[0]),
|
| 84 |
+
min(im_1.size[1], im_2.size[1]),
|
| 85 |
+
)
|
| 86 |
+
if im_1.size != size:
|
| 87 |
+
im_1 = im_1.crop((0, 0) + size)
|
| 88 |
+
if im_2.size != size:
|
| 89 |
+
im_2 = im_2.crop((0, 0) + size)
|
| 90 |
+
out = Image.new(mode or im_1.mode, im_1.size, None)
|
| 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.getim(), im_1.getim(), im_2.getim())
|
| 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: _Operand | float) -> _Operand: # type: ignore[override]
|
| 180 |
+
return self.apply("eq", self, other)
|
| 181 |
+
|
| 182 |
+
def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
|
| 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(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any:
|
| 240 |
+
"""
|
| 241 |
+
Returns the result of an image function.
|
| 242 |
+
|
| 243 |
+
:py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
|
| 244 |
+
images, use the :py:meth:`~PIL.Image.Image.split` method or
|
| 245 |
+
:py:func:`~PIL.Image.merge` function.
|
| 246 |
+
|
| 247 |
+
:param expression: A function that receives a dictionary.
|
| 248 |
+
:param **kw: Values to add to the function's dictionary.
|
| 249 |
+
:return: The expression result. This is usually an image object, but can
|
| 250 |
+
also be an integer, a floating point value, or a pixel tuple,
|
| 251 |
+
depending on the expression.
|
| 252 |
+
"""
|
| 253 |
+
|
| 254 |
+
args: dict[str, Any] = ops.copy()
|
| 255 |
+
args.update(kw)
|
| 256 |
+
for k, v in args.items():
|
| 257 |
+
if isinstance(v, Image.Image):
|
| 258 |
+
args[k] = _Operand(v)
|
| 259 |
+
|
| 260 |
+
out = expression(args)
|
| 261 |
+
try:
|
| 262 |
+
return out.im
|
| 263 |
+
except AttributeError:
|
| 264 |
+
return out
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def unsafe_eval(expression: str, **kw: Any) -> Any:
|
| 268 |
+
"""
|
| 269 |
+
Evaluates an image expression. This uses Python's ``eval()`` function to process
|
| 270 |
+
the expression string, and carries the security risks of doing so. It is not
|
| 271 |
+
recommended to process expressions without considering this.
|
| 272 |
+
:py:meth:`~lambda_eval` is a more secure alternative.
|
| 273 |
+
|
| 274 |
+
:py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
|
| 275 |
+
images, use the :py:meth:`~PIL.Image.Image.split` method or
|
| 276 |
+
:py:func:`~PIL.Image.merge` function.
|
| 277 |
+
|
| 278 |
+
:param expression: A string containing a Python-style expression.
|
| 279 |
+
:param **kw: Values to add to the evaluation context.
|
| 280 |
+
:return: The evaluated expression. This is usually an image object, but can
|
| 281 |
+
also be an integer, a floating point value, or a pixel tuple,
|
| 282 |
+
depending on the expression.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
# build execution namespace
|
| 286 |
+
args: dict[str, Any] = ops.copy()
|
| 287 |
+
for k in kw:
|
| 288 |
+
if "__" in k or hasattr(builtins, k):
|
| 289 |
+
msg = f"'{k}' not allowed"
|
| 290 |
+
raise ValueError(msg)
|
| 291 |
+
|
| 292 |
+
args.update(kw)
|
| 293 |
+
for k, v in args.items():
|
| 294 |
+
if isinstance(v, Image.Image):
|
| 295 |
+
args[k] = _Operand(v)
|
| 296 |
+
|
| 297 |
+
compiled_code = compile(expression, "<string>", "eval")
|
| 298 |
+
|
| 299 |
+
def scan(code: CodeType) -> None:
|
| 300 |
+
for const in code.co_consts:
|
| 301 |
+
if type(const) is type(compiled_code):
|
| 302 |
+
scan(const)
|
| 303 |
+
|
| 304 |
+
for name in code.co_names:
|
| 305 |
+
if name not in args and name != "abs":
|
| 306 |
+
msg = f"'{name}' not allowed"
|
| 307 |
+
raise ValueError(msg)
|
| 308 |
+
|
| 309 |
+
scan(compiled_code)
|
| 310 |
+
out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
|
| 311 |
+
try:
|
| 312 |
+
return out.im
|
| 313 |
+
except AttributeError:
|
| 314 |
+
return out
|
.venv/lib/python3.12/site-packages/PIL/ImagePalette.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# image palette object
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-03-11 fl Rewritten.
|
| 9 |
+
# 1997-01-03 fl Up and 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 collections.abc import Sequence
|
| 22 |
+
from typing import IO
|
| 23 |
+
|
| 24 |
+
from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
|
| 25 |
+
|
| 26 |
+
TYPE_CHECKING = False
|
| 27 |
+
if TYPE_CHECKING:
|
| 28 |
+
from . import Image
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ImagePalette:
|
| 32 |
+
"""
|
| 33 |
+
Color palette for palette mapped images
|
| 34 |
+
|
| 35 |
+
:param mode: The mode to use for the palette. See:
|
| 36 |
+
:ref:`concept-modes`. Defaults to "RGB"
|
| 37 |
+
:param palette: An optional palette. If given, it must be a bytearray,
|
| 38 |
+
an array or a list of ints between 0-255. The list must consist of
|
| 39 |
+
all channels for one color followed by the next color (e.g. RGBRGBRGB).
|
| 40 |
+
Defaults to an empty palette.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
mode: str = "RGB",
|
| 46 |
+
palette: Sequence[int] | bytes | bytearray | None = None,
|
| 47 |
+
) -> None:
|
| 48 |
+
self.mode = mode
|
| 49 |
+
self.rawmode: str | None = None # if set, palette contains raw data
|
| 50 |
+
self.palette = palette or bytearray()
|
| 51 |
+
self.dirty: int | None = None
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def palette(self) -> Sequence[int] | bytes | bytearray:
|
| 55 |
+
return self._palette
|
| 56 |
+
|
| 57 |
+
@palette.setter
|
| 58 |
+
def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
|
| 59 |
+
self._colors: dict[tuple[int, ...], int] | None = None
|
| 60 |
+
self._palette = palette
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def colors(self) -> dict[tuple[int, ...], int]:
|
| 64 |
+
if self._colors is None:
|
| 65 |
+
mode_len = len(self.mode)
|
| 66 |
+
self._colors = {}
|
| 67 |
+
for i in range(0, len(self.palette), mode_len):
|
| 68 |
+
color = tuple(self.palette[i : i + mode_len])
|
| 69 |
+
if color in self._colors:
|
| 70 |
+
continue
|
| 71 |
+
self._colors[color] = i // mode_len
|
| 72 |
+
return self._colors
|
| 73 |
+
|
| 74 |
+
@colors.setter
|
| 75 |
+
def colors(self, colors: dict[tuple[int, ...], int]) -> None:
|
| 76 |
+
self._colors = colors
|
| 77 |
+
|
| 78 |
+
def copy(self) -> ImagePalette:
|
| 79 |
+
new = ImagePalette()
|
| 80 |
+
|
| 81 |
+
new.mode = self.mode
|
| 82 |
+
new.rawmode = self.rawmode
|
| 83 |
+
if self.palette is not None:
|
| 84 |
+
new.palette = self.palette[:]
|
| 85 |
+
new.dirty = self.dirty
|
| 86 |
+
|
| 87 |
+
return new
|
| 88 |
+
|
| 89 |
+
def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
|
| 90 |
+
"""
|
| 91 |
+
Get palette contents in format suitable for the low-level
|
| 92 |
+
``im.putpalette`` primitive.
|
| 93 |
+
|
| 94 |
+
.. warning:: This method is experimental.
|
| 95 |
+
"""
|
| 96 |
+
if self.rawmode:
|
| 97 |
+
return self.rawmode, self.palette
|
| 98 |
+
return self.mode, self.tobytes()
|
| 99 |
+
|
| 100 |
+
def tobytes(self) -> bytes:
|
| 101 |
+
"""Convert palette to bytes.
|
| 102 |
+
|
| 103 |
+
.. warning:: This method is experimental.
|
| 104 |
+
"""
|
| 105 |
+
if self.rawmode:
|
| 106 |
+
msg = "palette contains raw palette data"
|
| 107 |
+
raise ValueError(msg)
|
| 108 |
+
if isinstance(self.palette, bytes):
|
| 109 |
+
return self.palette
|
| 110 |
+
arr = array.array("B", self.palette)
|
| 111 |
+
return arr.tobytes()
|
| 112 |
+
|
| 113 |
+
# Declare tostring as an alias for tobytes
|
| 114 |
+
tostring = tobytes
|
| 115 |
+
|
| 116 |
+
def _new_color_index(
|
| 117 |
+
self, image: Image.Image | None = None, e: Exception | None = None
|
| 118 |
+
) -> int:
|
| 119 |
+
if not isinstance(self.palette, bytearray):
|
| 120 |
+
self._palette = bytearray(self.palette)
|
| 121 |
+
index = len(self.palette) // 3
|
| 122 |
+
special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
|
| 123 |
+
if image:
|
| 124 |
+
special_colors = (
|
| 125 |
+
image.info.get("background"),
|
| 126 |
+
image.info.get("transparency"),
|
| 127 |
+
)
|
| 128 |
+
while index in special_colors:
|
| 129 |
+
index += 1
|
| 130 |
+
if index >= 256:
|
| 131 |
+
if image:
|
| 132 |
+
# Search for an unused index
|
| 133 |
+
for i, count in reversed(list(enumerate(image.histogram()))):
|
| 134 |
+
if count == 0 and i not in special_colors:
|
| 135 |
+
index = i
|
| 136 |
+
break
|
| 137 |
+
if index >= 256:
|
| 138 |
+
msg = "cannot allocate more than 256 colors"
|
| 139 |
+
raise ValueError(msg) from e
|
| 140 |
+
return index
|
| 141 |
+
|
| 142 |
+
def getcolor(
|
| 143 |
+
self,
|
| 144 |
+
color: tuple[int, ...],
|
| 145 |
+
image: Image.Image | None = None,
|
| 146 |
+
) -> int:
|
| 147 |
+
"""Given an rgb tuple, allocate palette entry.
|
| 148 |
+
|
| 149 |
+
.. warning:: This method is experimental.
|
| 150 |
+
"""
|
| 151 |
+
if self.rawmode:
|
| 152 |
+
msg = "palette contains raw palette data"
|
| 153 |
+
raise ValueError(msg)
|
| 154 |
+
if isinstance(color, tuple):
|
| 155 |
+
if self.mode == "RGB":
|
| 156 |
+
if len(color) == 4:
|
| 157 |
+
if color[3] != 255:
|
| 158 |
+
msg = "cannot add non-opaque RGBA color to RGB palette"
|
| 159 |
+
raise ValueError(msg)
|
| 160 |
+
color = color[:3]
|
| 161 |
+
elif self.mode == "RGBA":
|
| 162 |
+
if len(color) == 3:
|
| 163 |
+
color += (255,)
|
| 164 |
+
try:
|
| 165 |
+
return self.colors[color]
|
| 166 |
+
except KeyError as e:
|
| 167 |
+
# allocate new color slot
|
| 168 |
+
index = self._new_color_index(image, e)
|
| 169 |
+
assert isinstance(self._palette, bytearray)
|
| 170 |
+
self.colors[color] = index
|
| 171 |
+
if index * 3 < len(self.palette):
|
| 172 |
+
self._palette = (
|
| 173 |
+
self._palette[: index * 3]
|
| 174 |
+
+ bytes(color)
|
| 175 |
+
+ self._palette[index * 3 + 3 :]
|
| 176 |
+
)
|
| 177 |
+
else:
|
| 178 |
+
self._palette += bytes(color)
|
| 179 |
+
self.dirty = 1
|
| 180 |
+
return index
|
| 181 |
+
else:
|
| 182 |
+
msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
|
| 183 |
+
raise ValueError(msg)
|
| 184 |
+
|
| 185 |
+
def save(self, fp: str | IO[str]) -> None:
|
| 186 |
+
"""Save palette to text file.
|
| 187 |
+
|
| 188 |
+
.. warning:: This method is experimental.
|
| 189 |
+
"""
|
| 190 |
+
if self.rawmode:
|
| 191 |
+
msg = "palette contains raw palette data"
|
| 192 |
+
raise ValueError(msg)
|
| 193 |
+
if isinstance(fp, str):
|
| 194 |
+
fp = open(fp, "w")
|
| 195 |
+
fp.write("# Palette\n")
|
| 196 |
+
fp.write(f"# Mode: {self.mode}\n")
|
| 197 |
+
for i in range(256):
|
| 198 |
+
fp.write(f"{i}")
|
| 199 |
+
for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
|
| 200 |
+
try:
|
| 201 |
+
fp.write(f" {self.palette[j]}")
|
| 202 |
+
except IndexError:
|
| 203 |
+
fp.write(" 0")
|
| 204 |
+
fp.write("\n")
|
| 205 |
+
fp.close()
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# --------------------------------------------------------------------
|
| 209 |
+
# Internal
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
|
| 213 |
+
palette = ImagePalette()
|
| 214 |
+
palette.rawmode = rawmode
|
| 215 |
+
palette.palette = data
|
| 216 |
+
palette.dirty = 1
|
| 217 |
+
return palette
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# --------------------------------------------------------------------
|
| 221 |
+
# Factories
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def make_linear_lut(black: int, white: float) -> list[int]:
|
| 225 |
+
if black == 0:
|
| 226 |
+
return [int(white * i // 255) for i in range(256)]
|
| 227 |
+
|
| 228 |
+
msg = "unavailable when black is non-zero"
|
| 229 |
+
raise NotImplementedError(msg) # FIXME
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def make_gamma_lut(exp: float) -> list[int]:
|
| 233 |
+
return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def negative(mode: str = "RGB") -> ImagePalette:
|
| 237 |
+
palette = list(range(256 * len(mode)))
|
| 238 |
+
palette.reverse()
|
| 239 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def random(mode: str = "RGB") -> ImagePalette:
|
| 243 |
+
from random import randint
|
| 244 |
+
|
| 245 |
+
palette = [randint(0, 255) for _ in range(256 * len(mode))]
|
| 246 |
+
return ImagePalette(mode, palette)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def sepia(white: str = "#fff0c0") -> ImagePalette:
|
| 250 |
+
bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
|
| 251 |
+
return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def wedge(mode: str = "RGB") -> ImagePalette:
|
| 255 |
+
palette = list(range(256 * len(mode)))
|
| 256 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def load(filename: str) -> tuple[bytes, str]:
|
| 260 |
+
# FIXME: supports GIMP gradients only
|
| 261 |
+
|
| 262 |
+
with open(filename, "rb") as fp:
|
| 263 |
+
paletteHandlers: list[
|
| 264 |
+
type[
|
| 265 |
+
GimpPaletteFile.GimpPaletteFile
|
| 266 |
+
| GimpGradientFile.GimpGradientFile
|
| 267 |
+
| PaletteFile.PaletteFile
|
| 268 |
+
]
|
| 269 |
+
] = [
|
| 270 |
+
GimpPaletteFile.GimpPaletteFile,
|
| 271 |
+
GimpGradientFile.GimpGradientFile,
|
| 272 |
+
PaletteFile.PaletteFile,
|
| 273 |
+
]
|
| 274 |
+
for paletteHandler in paletteHandlers:
|
| 275 |
+
try:
|
| 276 |
+
fp.seek(0)
|
| 277 |
+
lut = paletteHandler(fp).getpalette()
|
| 278 |
+
if lut:
|
| 279 |
+
break
|
| 280 |
+
except (SyntaxError, ValueError):
|
| 281 |
+
pass
|
| 282 |
+
else:
|
| 283 |
+
msg = "cannot load palette"
|
| 284 |
+
raise OSError(msg)
|
| 285 |
+
|
| 286 |
+
return lut # data, rawmode
|
.venv/lib/python3.12/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
|
.venv/lib/python3.12/site-packages/PIL/ImageText.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from . import ImageFont
|
| 4 |
+
from ._typing import _Ink
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Text:
|
| 8 |
+
def __init__(
|
| 9 |
+
self,
|
| 10 |
+
text: str | bytes,
|
| 11 |
+
font: (
|
| 12 |
+
ImageFont.ImageFont
|
| 13 |
+
| ImageFont.FreeTypeFont
|
| 14 |
+
| ImageFont.TransposedFont
|
| 15 |
+
| None
|
| 16 |
+
) = None,
|
| 17 |
+
mode: str = "RGB",
|
| 18 |
+
spacing: float = 4,
|
| 19 |
+
direction: str | None = None,
|
| 20 |
+
features: list[str] | None = None,
|
| 21 |
+
language: str | None = None,
|
| 22 |
+
) -> None:
|
| 23 |
+
"""
|
| 24 |
+
:param text: String to be drawn.
|
| 25 |
+
:param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance,
|
| 26 |
+
:py:class:`~PIL.ImageFont.FreeTypeFont` instance,
|
| 27 |
+
:py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If
|
| 28 |
+
``None``, the default font from :py:meth:`.ImageFont.load_default`
|
| 29 |
+
will be used.
|
| 30 |
+
:param mode: The image mode this will be used with.
|
| 31 |
+
:param spacing: The number of pixels between lines.
|
| 32 |
+
:param direction: Direction of the text. It can be ``"rtl"`` (right to left),
|
| 33 |
+
``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
|
| 34 |
+
Requires libraqm.
|
| 35 |
+
:param features: A list of OpenType font features to be used during text
|
| 36 |
+
layout. This is usually used to turn on optional font features
|
| 37 |
+
that are not enabled by default, for example ``"dlig"`` or
|
| 38 |
+
``"ss01"``, but can be also used to turn off default font
|
| 39 |
+
features, for example ``"-liga"`` to disable ligatures or
|
| 40 |
+
``"-kern"`` to disable kerning. To get all supported
|
| 41 |
+
features, see `OpenType docs`_.
|
| 42 |
+
Requires libraqm.
|
| 43 |
+
:param language: Language of the text. Different languages may use
|
| 44 |
+
different glyph shapes or ligatures. This parameter tells
|
| 45 |
+
the font which language the text is in, and to apply the
|
| 46 |
+
correct substitutions as appropriate, if available.
|
| 47 |
+
It should be a `BCP 47 language code`_.
|
| 48 |
+
Requires libraqm.
|
| 49 |
+
"""
|
| 50 |
+
self.text = text
|
| 51 |
+
self.font = font or ImageFont.load_default()
|
| 52 |
+
|
| 53 |
+
self.mode = mode
|
| 54 |
+
self.spacing = spacing
|
| 55 |
+
self.direction = direction
|
| 56 |
+
self.features = features
|
| 57 |
+
self.language = language
|
| 58 |
+
|
| 59 |
+
self.embedded_color = False
|
| 60 |
+
|
| 61 |
+
self.stroke_width: float = 0
|
| 62 |
+
self.stroke_fill: _Ink | None = None
|
| 63 |
+
|
| 64 |
+
def embed_color(self) -> None:
|
| 65 |
+
"""
|
| 66 |
+
Use embedded color glyphs (COLR, CBDT, SBIX).
|
| 67 |
+
"""
|
| 68 |
+
if self.mode not in ("RGB", "RGBA"):
|
| 69 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
| 70 |
+
raise ValueError(msg)
|
| 71 |
+
self.embedded_color = True
|
| 72 |
+
|
| 73 |
+
def stroke(self, width: float = 0, fill: _Ink | None = None) -> None:
|
| 74 |
+
"""
|
| 75 |
+
:param width: The width of the text stroke.
|
| 76 |
+
:param fill: Color to use for the text stroke when drawing. If not given, will
|
| 77 |
+
default to the ``fill`` parameter from
|
| 78 |
+
:py:meth:`.ImageDraw.ImageDraw.text`.
|
| 79 |
+
"""
|
| 80 |
+
self.stroke_width = width
|
| 81 |
+
self.stroke_fill = fill
|
| 82 |
+
|
| 83 |
+
def _get_fontmode(self) -> str:
|
| 84 |
+
if self.mode in ("1", "P", "I", "F"):
|
| 85 |
+
return "1"
|
| 86 |
+
elif self.embedded_color:
|
| 87 |
+
return "RGBA"
|
| 88 |
+
else:
|
| 89 |
+
return "L"
|
| 90 |
+
|
| 91 |
+
def get_length(self):
|
| 92 |
+
"""
|
| 93 |
+
Returns length (in pixels with 1/64 precision) of text.
|
| 94 |
+
|
| 95 |
+
This is the amount by which following text should be offset.
|
| 96 |
+
Text bounding box may extend past the length in some fonts,
|
| 97 |
+
e.g. when using italics or accents.
|
| 98 |
+
|
| 99 |
+
The result is returned as a float; it is a whole number if using basic layout.
|
| 100 |
+
|
| 101 |
+
Note that the sum of two lengths may not equal the length of a concatenated
|
| 102 |
+
string due to kerning. If you need to adjust for kerning, include the following
|
| 103 |
+
character and subtract its length.
|
| 104 |
+
|
| 105 |
+
For example, instead of::
|
| 106 |
+
|
| 107 |
+
hello = ImageText.Text("Hello", font).get_length()
|
| 108 |
+
world = ImageText.Text("World", font).get_length()
|
| 109 |
+
helloworld = ImageText.Text("HelloWorld", font).get_length()
|
| 110 |
+
assert hello + world == helloworld
|
| 111 |
+
|
| 112 |
+
use::
|
| 113 |
+
|
| 114 |
+
hello = (
|
| 115 |
+
ImageText.Text("HelloW", font).get_length() -
|
| 116 |
+
ImageText.Text("W", font).get_length()
|
| 117 |
+
) # adjusted for kerning
|
| 118 |
+
world = ImageText.Text("World", font).get_length()
|
| 119 |
+
helloworld = ImageText.Text("HelloWorld", font).get_length()
|
| 120 |
+
assert hello + world == helloworld
|
| 121 |
+
|
| 122 |
+
or disable kerning with (requires libraqm)::
|
| 123 |
+
|
| 124 |
+
hello = ImageText.Text("Hello", font, features=["-kern"]).get_length()
|
| 125 |
+
world = ImageText.Text("World", font, features=["-kern"]).get_length()
|
| 126 |
+
helloworld = ImageText.Text(
|
| 127 |
+
"HelloWorld", font, features=["-kern"]
|
| 128 |
+
).get_length()
|
| 129 |
+
assert hello + world == helloworld
|
| 130 |
+
|
| 131 |
+
:return: Either width for horizontal text, or height for vertical text.
|
| 132 |
+
"""
|
| 133 |
+
split_character = "\n" if isinstance(self.text, str) else b"\n"
|
| 134 |
+
if split_character in self.text:
|
| 135 |
+
msg = "can't measure length of multiline text"
|
| 136 |
+
raise ValueError(msg)
|
| 137 |
+
return self.font.getlength(
|
| 138 |
+
self.text,
|
| 139 |
+
self._get_fontmode(),
|
| 140 |
+
self.direction,
|
| 141 |
+
self.features,
|
| 142 |
+
self.language,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def _split(
|
| 146 |
+
self, xy: tuple[float, float], anchor: str | None, align: str
|
| 147 |
+
) -> list[tuple[tuple[float, float], str, str | bytes]]:
|
| 148 |
+
if anchor is None:
|
| 149 |
+
anchor = "lt" if self.direction == "ttb" else "la"
|
| 150 |
+
elif len(anchor) != 2:
|
| 151 |
+
msg = "anchor must be a 2 character string"
|
| 152 |
+
raise ValueError(msg)
|
| 153 |
+
|
| 154 |
+
lines = (
|
| 155 |
+
self.text.split("\n")
|
| 156 |
+
if isinstance(self.text, str)
|
| 157 |
+
else self.text.split(b"\n")
|
| 158 |
+
)
|
| 159 |
+
if len(lines) == 1:
|
| 160 |
+
return [(xy, anchor, self.text)]
|
| 161 |
+
|
| 162 |
+
if anchor[1] in "tb" and self.direction != "ttb":
|
| 163 |
+
msg = "anchor not supported for multiline text"
|
| 164 |
+
raise ValueError(msg)
|
| 165 |
+
|
| 166 |
+
fontmode = self._get_fontmode()
|
| 167 |
+
line_spacing = (
|
| 168 |
+
self.font.getbbox(
|
| 169 |
+
"A",
|
| 170 |
+
fontmode,
|
| 171 |
+
None,
|
| 172 |
+
self.features,
|
| 173 |
+
self.language,
|
| 174 |
+
self.stroke_width,
|
| 175 |
+
)[3]
|
| 176 |
+
+ self.stroke_width
|
| 177 |
+
+ self.spacing
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
top = xy[1]
|
| 181 |
+
parts = []
|
| 182 |
+
if self.direction == "ttb":
|
| 183 |
+
left = xy[0]
|
| 184 |
+
for line in lines:
|
| 185 |
+
parts.append(((left, top), anchor, line))
|
| 186 |
+
left += line_spacing
|
| 187 |
+
else:
|
| 188 |
+
widths = []
|
| 189 |
+
max_width: float = 0
|
| 190 |
+
for line in lines:
|
| 191 |
+
line_width = self.font.getlength(
|
| 192 |
+
line, fontmode, self.direction, self.features, self.language
|
| 193 |
+
)
|
| 194 |
+
widths.append(line_width)
|
| 195 |
+
max_width = max(max_width, line_width)
|
| 196 |
+
|
| 197 |
+
if anchor[1] == "m":
|
| 198 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
| 199 |
+
elif anchor[1] == "d":
|
| 200 |
+
top -= (len(lines) - 1) * line_spacing
|
| 201 |
+
|
| 202 |
+
idx = -1
|
| 203 |
+
for line in lines:
|
| 204 |
+
left = xy[0]
|
| 205 |
+
idx += 1
|
| 206 |
+
width_difference = max_width - widths[idx]
|
| 207 |
+
|
| 208 |
+
# align by align parameter
|
| 209 |
+
if align in ("left", "justify"):
|
| 210 |
+
pass
|
| 211 |
+
elif align == "center":
|
| 212 |
+
left += width_difference / 2.0
|
| 213 |
+
elif align == "right":
|
| 214 |
+
left += width_difference
|
| 215 |
+
else:
|
| 216 |
+
msg = 'align must be "left", "center", "right" or "justify"'
|
| 217 |
+
raise ValueError(msg)
|
| 218 |
+
|
| 219 |
+
if (
|
| 220 |
+
align == "justify"
|
| 221 |
+
and width_difference != 0
|
| 222 |
+
and idx != len(lines) - 1
|
| 223 |
+
):
|
| 224 |
+
words = (
|
| 225 |
+
line.split(" ") if isinstance(line, str) else line.split(b" ")
|
| 226 |
+
)
|
| 227 |
+
if len(words) > 1:
|
| 228 |
+
# align left by anchor
|
| 229 |
+
if anchor[0] == "m":
|
| 230 |
+
left -= max_width / 2.0
|
| 231 |
+
elif anchor[0] == "r":
|
| 232 |
+
left -= max_width
|
| 233 |
+
|
| 234 |
+
word_widths = [
|
| 235 |
+
self.font.getlength(
|
| 236 |
+
word,
|
| 237 |
+
fontmode,
|
| 238 |
+
self.direction,
|
| 239 |
+
self.features,
|
| 240 |
+
self.language,
|
| 241 |
+
)
|
| 242 |
+
for word in words
|
| 243 |
+
]
|
| 244 |
+
word_anchor = "l" + anchor[1]
|
| 245 |
+
width_difference = max_width - sum(word_widths)
|
| 246 |
+
i = 0
|
| 247 |
+
for word in words:
|
| 248 |
+
parts.append(((left, top), word_anchor, word))
|
| 249 |
+
left += word_widths[i] + width_difference / (len(words) - 1)
|
| 250 |
+
i += 1
|
| 251 |
+
top += line_spacing
|
| 252 |
+
continue
|
| 253 |
+
|
| 254 |
+
# align left by anchor
|
| 255 |
+
if anchor[0] == "m":
|
| 256 |
+
left -= width_difference / 2.0
|
| 257 |
+
elif anchor[0] == "r":
|
| 258 |
+
left -= width_difference
|
| 259 |
+
parts.append(((left, top), anchor, line))
|
| 260 |
+
top += line_spacing
|
| 261 |
+
|
| 262 |
+
return parts
|
| 263 |
+
|
| 264 |
+
def get_bbox(
|
| 265 |
+
self,
|
| 266 |
+
xy: tuple[float, float] = (0, 0),
|
| 267 |
+
anchor: str | None = None,
|
| 268 |
+
align: str = "left",
|
| 269 |
+
) -> tuple[float, float, float, float]:
|
| 270 |
+
"""
|
| 271 |
+
Returns bounding box (in pixels) of text.
|
| 272 |
+
|
| 273 |
+
Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel
|
| 274 |
+
precision. The bounding box includes extra margins for some fonts, e.g. italics
|
| 275 |
+
or accents.
|
| 276 |
+
|
| 277 |
+
:param xy: The anchor coordinates of the text.
|
| 278 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 279 |
+
the anchor to the text. The default alignment is top left,
|
| 280 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 281 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 282 |
+
:param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or
|
| 283 |
+
``"justify"`` determines the relative alignment of lines. Use the
|
| 284 |
+
``anchor`` parameter to specify the alignment to ``xy``.
|
| 285 |
+
|
| 286 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 287 |
+
"""
|
| 288 |
+
bbox: tuple[float, float, float, float] | None = None
|
| 289 |
+
fontmode = self._get_fontmode()
|
| 290 |
+
for xy, anchor, line in self._split(xy, anchor, align):
|
| 291 |
+
bbox_line = self.font.getbbox(
|
| 292 |
+
line,
|
| 293 |
+
fontmode,
|
| 294 |
+
self.direction,
|
| 295 |
+
self.features,
|
| 296 |
+
self.language,
|
| 297 |
+
self.stroke_width,
|
| 298 |
+
anchor,
|
| 299 |
+
)
|
| 300 |
+
bbox_line = (
|
| 301 |
+
bbox_line[0] + xy[0],
|
| 302 |
+
bbox_line[1] + xy[1],
|
| 303 |
+
bbox_line[2] + xy[0],
|
| 304 |
+
bbox_line[3] + xy[1],
|
| 305 |
+
)
|
| 306 |
+
if bbox is None:
|
| 307 |
+
bbox = bbox_line
|
| 308 |
+
else:
|
| 309 |
+
bbox = (
|
| 310 |
+
min(bbox[0], bbox_line[0]),
|
| 311 |
+
min(bbox[1], bbox_line[1]),
|
| 312 |
+
max(bbox[2], bbox_line[2]),
|
| 313 |
+
max(bbox[3], bbox_line[3]),
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
if bbox is None:
|
| 317 |
+
return xy[0], xy[1], xy[0], xy[1]
|
| 318 |
+
return bbox
|
.venv/lib/python3.12/site-packages/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import Any
|
| 32 |
+
|
| 33 |
+
from . import Image, ImageFile
|
| 34 |
+
|
| 35 |
+
TYPE_CHECKING = False
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from ._typing import CapsuleType
|
| 38 |
+
|
| 39 |
+
# --------------------------------------------------------------------
|
| 40 |
+
# Check for Tkinter interface hooks
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
|
| 44 |
+
source = None
|
| 45 |
+
if "file" in kw:
|
| 46 |
+
source = kw.pop("file")
|
| 47 |
+
elif "data" in kw:
|
| 48 |
+
source = BytesIO(kw.pop("data"))
|
| 49 |
+
if not source:
|
| 50 |
+
return None
|
| 51 |
+
return Image.open(source)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _pyimagingtkcall(
|
| 55 |
+
command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType
|
| 56 |
+
) -> None:
|
| 57 |
+
tk = photo.tk
|
| 58 |
+
try:
|
| 59 |
+
tk.call(command, photo, repr(ptr))
|
| 60 |
+
except tkinter.TclError:
|
| 61 |
+
# activate Tkinter hook
|
| 62 |
+
# may raise an error if it cannot attach to Tkinter
|
| 63 |
+
from . import _imagingtk
|
| 64 |
+
|
| 65 |
+
_imagingtk.tkinit(tk.interpaddr())
|
| 66 |
+
tk.call(command, photo, repr(ptr))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# --------------------------------------------------------------------
|
| 70 |
+
# PhotoImage
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PhotoImage:
|
| 74 |
+
"""
|
| 75 |
+
A Tkinter-compatible photo image. This can be used
|
| 76 |
+
everywhere Tkinter expects an image object. If the image is an RGBA
|
| 77 |
+
image, pixels having alpha 0 are treated as transparent.
|
| 78 |
+
|
| 79 |
+
The constructor takes either a PIL image, or a mode and a size.
|
| 80 |
+
Alternatively, you can use the ``file`` or ``data`` options to initialize
|
| 81 |
+
the photo image object.
|
| 82 |
+
|
| 83 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
| 84 |
+
used, a size must also be given.
|
| 85 |
+
:param size: If the first argument is a mode string, this defines the size
|
| 86 |
+
of the image.
|
| 87 |
+
:keyword file: A filename to load the image from (using
|
| 88 |
+
``Image.open(file)``).
|
| 89 |
+
:keyword data: An 8-bit string containing image data (as loaded from an
|
| 90 |
+
image file).
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
image: Image.Image | str | None = None,
|
| 96 |
+
size: tuple[int, int] | None = None,
|
| 97 |
+
**kw: Any,
|
| 98 |
+
) -> None:
|
| 99 |
+
# Tk compatibility: file or data
|
| 100 |
+
if image is None:
|
| 101 |
+
image = _get_image_from_kw(kw)
|
| 102 |
+
|
| 103 |
+
if image is None:
|
| 104 |
+
msg = "Image is required"
|
| 105 |
+
raise ValueError(msg)
|
| 106 |
+
elif isinstance(image, str):
|
| 107 |
+
mode = image
|
| 108 |
+
image = None
|
| 109 |
+
|
| 110 |
+
if size is None:
|
| 111 |
+
msg = "If first argument is mode, size is required"
|
| 112 |
+
raise ValueError(msg)
|
| 113 |
+
else:
|
| 114 |
+
# got an image instead of a mode
|
| 115 |
+
mode = image.mode
|
| 116 |
+
if mode == "P":
|
| 117 |
+
# palette mapped data
|
| 118 |
+
image.apply_transparency()
|
| 119 |
+
image.load()
|
| 120 |
+
mode = image.palette.mode if image.palette else "RGB"
|
| 121 |
+
size = image.size
|
| 122 |
+
kw["width"], kw["height"] = size
|
| 123 |
+
|
| 124 |
+
if mode not in ["1", "L", "RGB", "RGBA"]:
|
| 125 |
+
mode = Image.getmodebase(mode)
|
| 126 |
+
|
| 127 |
+
self.__mode = mode
|
| 128 |
+
self.__size = size
|
| 129 |
+
self.__photo = tkinter.PhotoImage(**kw)
|
| 130 |
+
self.tk = self.__photo.tk
|
| 131 |
+
if image:
|
| 132 |
+
self.paste(image)
|
| 133 |
+
|
| 134 |
+
def __del__(self) -> None:
|
| 135 |
+
try:
|
| 136 |
+
name = self.__photo.name
|
| 137 |
+
except AttributeError:
|
| 138 |
+
return
|
| 139 |
+
self.__photo.name = None
|
| 140 |
+
try:
|
| 141 |
+
self.__photo.tk.call("image", "delete", name)
|
| 142 |
+
except Exception:
|
| 143 |
+
pass # ignore internal errors
|
| 144 |
+
|
| 145 |
+
def __str__(self) -> str:
|
| 146 |
+
"""
|
| 147 |
+
Get the Tkinter photo image identifier. This method is automatically
|
| 148 |
+
called by Tkinter whenever a PhotoImage object is passed to a Tkinter
|
| 149 |
+
method.
|
| 150 |
+
|
| 151 |
+
:return: A Tkinter photo image identifier (a string).
|
| 152 |
+
"""
|
| 153 |
+
return str(self.__photo)
|
| 154 |
+
|
| 155 |
+
def width(self) -> int:
|
| 156 |
+
"""
|
| 157 |
+
Get the width of the image.
|
| 158 |
+
|
| 159 |
+
:return: The width, in pixels.
|
| 160 |
+
"""
|
| 161 |
+
return self.__size[0]
|
| 162 |
+
|
| 163 |
+
def height(self) -> int:
|
| 164 |
+
"""
|
| 165 |
+
Get the height of the image.
|
| 166 |
+
|
| 167 |
+
:return: The height, in pixels.
|
| 168 |
+
"""
|
| 169 |
+
return self.__size[1]
|
| 170 |
+
|
| 171 |
+
def paste(self, im: Image.Image) -> None:
|
| 172 |
+
"""
|
| 173 |
+
Paste a PIL image into the photo image. Note that this can
|
| 174 |
+
be very slow if the photo image is displayed.
|
| 175 |
+
|
| 176 |
+
:param im: A PIL image. The size must match the target region. If the
|
| 177 |
+
mode does not match, the image is converted to the mode of
|
| 178 |
+
the bitmap image.
|
| 179 |
+
"""
|
| 180 |
+
# convert to blittable
|
| 181 |
+
ptr = im.getim()
|
| 182 |
+
image = im.im
|
| 183 |
+
if not image.isblock() or im.mode != self.__mode:
|
| 184 |
+
block = Image.core.new_block(self.__mode, im.size)
|
| 185 |
+
image.convert2(block, image) # convert directly between buffers
|
| 186 |
+
ptr = block.ptr
|
| 187 |
+
|
| 188 |
+
_pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# --------------------------------------------------------------------
|
| 192 |
+
# BitmapImage
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class BitmapImage:
|
| 196 |
+
"""
|
| 197 |
+
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
|
| 198 |
+
expects an image object.
|
| 199 |
+
|
| 200 |
+
The given image must have mode "1". Pixels having value 0 are treated as
|
| 201 |
+
transparent. Options, if any, are passed on to Tkinter. The most commonly
|
| 202 |
+
used option is ``foreground``, which is used to specify the color for the
|
| 203 |
+
non-transparent parts. See the Tkinter documentation for information on
|
| 204 |
+
how to specify colours.
|
| 205 |
+
|
| 206 |
+
:param image: A PIL image.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:
|
| 210 |
+
# Tk compatibility: file or data
|
| 211 |
+
if image is None:
|
| 212 |
+
image = _get_image_from_kw(kw)
|
| 213 |
+
|
| 214 |
+
if image is None:
|
| 215 |
+
msg = "Image is required"
|
| 216 |
+
raise ValueError(msg)
|
| 217 |
+
self.__mode = image.mode
|
| 218 |
+
self.__size = image.size
|
| 219 |
+
|
| 220 |
+
self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)
|
| 221 |
+
|
| 222 |
+
def __del__(self) -> None:
|
| 223 |
+
try:
|
| 224 |
+
name = self.__photo.name
|
| 225 |
+
except AttributeError:
|
| 226 |
+
return
|
| 227 |
+
self.__photo.name = None
|
| 228 |
+
try:
|
| 229 |
+
self.__photo.tk.call("image", "delete", name)
|
| 230 |
+
except Exception:
|
| 231 |
+
pass # ignore internal errors
|
| 232 |
+
|
| 233 |
+
def width(self) -> int:
|
| 234 |
+
"""
|
| 235 |
+
Get the width of the image.
|
| 236 |
+
|
| 237 |
+
:return: The width, in pixels.
|
| 238 |
+
"""
|
| 239 |
+
return self.__size[0]
|
| 240 |
+
|
| 241 |
+
def height(self) -> int:
|
| 242 |
+
"""
|
| 243 |
+
Get the height of the image.
|
| 244 |
+
|
| 245 |
+
:return: The height, in pixels.
|
| 246 |
+
"""
|
| 247 |
+
return self.__size[1]
|
| 248 |
+
|
| 249 |
+
def __str__(self) -> str:
|
| 250 |
+
"""
|
| 251 |
+
Get the Tkinter bitmap image identifier. This method is automatically
|
| 252 |
+
called by Tkinter whenever a BitmapImage object is passed to a Tkinter
|
| 253 |
+
method.
|
| 254 |
+
|
| 255 |
+
:return: A Tkinter bitmap image identifier (a string).
|
| 256 |
+
"""
|
| 257 |
+
return str(self.__photo)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def getimage(photo: PhotoImage) -> Image.Image:
|
| 261 |
+
"""Copies the contents of a PhotoImage to a PIL image memory."""
|
| 262 |
+
im = Image.new("RGBA", (photo.width(), photo.height()))
|
| 263 |
+
|
| 264 |
+
_pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())
|
| 265 |
+
|
| 266 |
+
return im
|
.venv/lib/python3.12/site-packages/PIL/JpegImagePlugin.py
ADDED
|
@@ -0,0 +1,888 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# JPEG (JFIF) file handling
|
| 6 |
+
#
|
| 7 |
+
# See "Digital Compression and Coding of Continuous-Tone Still Images,
|
| 8 |
+
# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
|
| 9 |
+
#
|
| 10 |
+
# History:
|
| 11 |
+
# 1995-09-09 fl Created
|
| 12 |
+
# 1995-09-13 fl Added full parser
|
| 13 |
+
# 1996-03-25 fl Added hack to use the IJG command line utilities
|
| 14 |
+
# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
|
| 15 |
+
# 1996-05-28 fl Added draft support, JFIF version (0.1)
|
| 16 |
+
# 1996-12-30 fl Added encoder options, added progression property (0.2)
|
| 17 |
+
# 1997-08-27 fl Save mode 1 images as BW (0.3)
|
| 18 |
+
# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
|
| 19 |
+
# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
|
| 20 |
+
# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
|
| 21 |
+
# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
|
| 22 |
+
# 2003-04-25 fl Added experimental EXIF decoder (0.5)
|
| 23 |
+
# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
|
| 24 |
+
# 2003-09-13 fl Extract COM markers
|
| 25 |
+
# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
|
| 26 |
+
# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
|
| 27 |
+
# 2009-03-08 fl Added subsampling support (from Justin Huff).
|
| 28 |
+
#
|
| 29 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 30 |
+
# Copyright (c) 1995-1996 by Fredrik Lundh.
|
| 31 |
+
#
|
| 32 |
+
# See the README file for information on usage and redistribution.
|
| 33 |
+
#
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import array
|
| 37 |
+
import io
|
| 38 |
+
import math
|
| 39 |
+
import os
|
| 40 |
+
import struct
|
| 41 |
+
import subprocess
|
| 42 |
+
import sys
|
| 43 |
+
import tempfile
|
| 44 |
+
import warnings
|
| 45 |
+
|
| 46 |
+
from . import Image, ImageFile
|
| 47 |
+
from ._binary import i16be as i16
|
| 48 |
+
from ._binary import i32be as i32
|
| 49 |
+
from ._binary import o8
|
| 50 |
+
from ._binary import o16be as o16
|
| 51 |
+
from .JpegPresets import presets
|
| 52 |
+
|
| 53 |
+
TYPE_CHECKING = False
|
| 54 |
+
if TYPE_CHECKING:
|
| 55 |
+
from typing import IO, Any
|
| 56 |
+
|
| 57 |
+
from .MpoImagePlugin import MpoImageFile
|
| 58 |
+
|
| 59 |
+
#
|
| 60 |
+
# Parser
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def Skip(self: JpegImageFile, marker: int) -> None:
|
| 64 |
+
n = i16(self.fp.read(2)) - 2
|
| 65 |
+
ImageFile._safe_read(self.fp, n)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def APP(self: JpegImageFile, marker: int) -> None:
|
| 69 |
+
#
|
| 70 |
+
# Application marker. Store these in the APP dictionary.
|
| 71 |
+
# Also look for well-known application markers.
|
| 72 |
+
|
| 73 |
+
n = i16(self.fp.read(2)) - 2
|
| 74 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 75 |
+
|
| 76 |
+
app = f"APP{marker & 15}"
|
| 77 |
+
|
| 78 |
+
self.app[app] = s # compatibility
|
| 79 |
+
self.applist.append((app, s))
|
| 80 |
+
|
| 81 |
+
if marker == 0xFFE0 and s.startswith(b"JFIF"):
|
| 82 |
+
# extract JFIF information
|
| 83 |
+
self.info["jfif"] = version = i16(s, 5) # version
|
| 84 |
+
self.info["jfif_version"] = divmod(version, 256)
|
| 85 |
+
# extract JFIF properties
|
| 86 |
+
try:
|
| 87 |
+
jfif_unit = s[7]
|
| 88 |
+
jfif_density = i16(s, 8), i16(s, 10)
|
| 89 |
+
except Exception:
|
| 90 |
+
pass
|
| 91 |
+
else:
|
| 92 |
+
if jfif_unit == 1:
|
| 93 |
+
self.info["dpi"] = jfif_density
|
| 94 |
+
elif jfif_unit == 2: # cm
|
| 95 |
+
# 1 dpcm = 2.54 dpi
|
| 96 |
+
self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)
|
| 97 |
+
self.info["jfif_unit"] = jfif_unit
|
| 98 |
+
self.info["jfif_density"] = jfif_density
|
| 99 |
+
elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):
|
| 100 |
+
# extract EXIF information
|
| 101 |
+
if "exif" in self.info:
|
| 102 |
+
self.info["exif"] += s[6:]
|
| 103 |
+
else:
|
| 104 |
+
self.info["exif"] = s
|
| 105 |
+
self._exif_offset = self.fp.tell() - n + 6
|
| 106 |
+
elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
|
| 107 |
+
self.info["xmp"] = s.split(b"\x00", 1)[1]
|
| 108 |
+
elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):
|
| 109 |
+
# extract FlashPix information (incomplete)
|
| 110 |
+
self.info["flashpix"] = s # FIXME: value will change
|
| 111 |
+
elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):
|
| 112 |
+
# Since an ICC profile can be larger than the maximum size of
|
| 113 |
+
# a JPEG marker (64K), we need provisions to split it into
|
| 114 |
+
# multiple markers. The format defined by the ICC specifies
|
| 115 |
+
# one or more APP2 markers containing the following data:
|
| 116 |
+
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
|
| 117 |
+
# Marker sequence number 1, 2, etc (1 byte)
|
| 118 |
+
# Number of markers Total of APP2's used (1 byte)
|
| 119 |
+
# Profile data (remainder of APP2 data)
|
| 120 |
+
# Decoders should use the marker sequence numbers to
|
| 121 |
+
# reassemble the profile, rather than assuming that the APP2
|
| 122 |
+
# markers appear in the correct sequence.
|
| 123 |
+
self.icclist.append(s)
|
| 124 |
+
elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):
|
| 125 |
+
# parse the image resource block
|
| 126 |
+
offset = 14
|
| 127 |
+
photoshop = self.info.setdefault("photoshop", {})
|
| 128 |
+
while s[offset : offset + 4] == b"8BIM":
|
| 129 |
+
try:
|
| 130 |
+
offset += 4
|
| 131 |
+
# resource code
|
| 132 |
+
code = i16(s, offset)
|
| 133 |
+
offset += 2
|
| 134 |
+
# resource name (usually empty)
|
| 135 |
+
name_len = s[offset]
|
| 136 |
+
# name = s[offset+1:offset+1+name_len]
|
| 137 |
+
offset += 1 + name_len
|
| 138 |
+
offset += offset & 1 # align
|
| 139 |
+
# resource data block
|
| 140 |
+
size = i32(s, offset)
|
| 141 |
+
offset += 4
|
| 142 |
+
data = s[offset : offset + size]
|
| 143 |
+
if code == 0x03ED: # ResolutionInfo
|
| 144 |
+
photoshop[code] = {
|
| 145 |
+
"XResolution": i32(data, 0) / 65536,
|
| 146 |
+
"DisplayedUnitsX": i16(data, 4),
|
| 147 |
+
"YResolution": i32(data, 8) / 65536,
|
| 148 |
+
"DisplayedUnitsY": i16(data, 12),
|
| 149 |
+
}
|
| 150 |
+
else:
|
| 151 |
+
photoshop[code] = data
|
| 152 |
+
offset += size
|
| 153 |
+
offset += offset & 1 # align
|
| 154 |
+
except struct.error:
|
| 155 |
+
break # insufficient data
|
| 156 |
+
|
| 157 |
+
elif marker == 0xFFEE and s.startswith(b"Adobe"):
|
| 158 |
+
self.info["adobe"] = i16(s, 5)
|
| 159 |
+
# extract Adobe custom properties
|
| 160 |
+
try:
|
| 161 |
+
adobe_transform = s[11]
|
| 162 |
+
except IndexError:
|
| 163 |
+
pass
|
| 164 |
+
else:
|
| 165 |
+
self.info["adobe_transform"] = adobe_transform
|
| 166 |
+
elif marker == 0xFFE2 and s.startswith(b"MPF\0"):
|
| 167 |
+
# extract MPO information
|
| 168 |
+
self.info["mp"] = s[4:]
|
| 169 |
+
# offset is current location minus buffer size
|
| 170 |
+
# plus constant header size
|
| 171 |
+
self.info["mpoffset"] = self.fp.tell() - n + 4
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def COM(self: JpegImageFile, marker: int) -> None:
|
| 175 |
+
#
|
| 176 |
+
# Comment marker. Store these in the APP dictionary.
|
| 177 |
+
n = i16(self.fp.read(2)) - 2
|
| 178 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 179 |
+
|
| 180 |
+
self.info["comment"] = s
|
| 181 |
+
self.app["COM"] = s # compatibility
|
| 182 |
+
self.applist.append(("COM", s))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def SOF(self: JpegImageFile, marker: int) -> None:
|
| 186 |
+
#
|
| 187 |
+
# Start of frame marker. Defines the size and mode of the
|
| 188 |
+
# image. JPEG is colour blind, so we use some simple
|
| 189 |
+
# heuristics to map the number of layers to an appropriate
|
| 190 |
+
# mode. Note that this could be made a bit brighter, by
|
| 191 |
+
# looking for JFIF and Adobe APP markers.
|
| 192 |
+
|
| 193 |
+
n = i16(self.fp.read(2)) - 2
|
| 194 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 195 |
+
self._size = i16(s, 3), i16(s, 1)
|
| 196 |
+
if self._im is not None and self.size != self.im.size:
|
| 197 |
+
self._im = None
|
| 198 |
+
|
| 199 |
+
self.bits = s[0]
|
| 200 |
+
if self.bits != 8:
|
| 201 |
+
msg = f"cannot handle {self.bits}-bit layers"
|
| 202 |
+
raise SyntaxError(msg)
|
| 203 |
+
|
| 204 |
+
self.layers = s[5]
|
| 205 |
+
if self.layers == 1:
|
| 206 |
+
self._mode = "L"
|
| 207 |
+
elif self.layers == 3:
|
| 208 |
+
self._mode = "RGB"
|
| 209 |
+
elif self.layers == 4:
|
| 210 |
+
self._mode = "CMYK"
|
| 211 |
+
else:
|
| 212 |
+
msg = f"cannot handle {self.layers}-layer images"
|
| 213 |
+
raise SyntaxError(msg)
|
| 214 |
+
|
| 215 |
+
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
|
| 216 |
+
self.info["progressive"] = self.info["progression"] = 1
|
| 217 |
+
|
| 218 |
+
if self.icclist:
|
| 219 |
+
# fixup icc profile
|
| 220 |
+
self.icclist.sort() # sort by sequence number
|
| 221 |
+
if self.icclist[0][13] == len(self.icclist):
|
| 222 |
+
profile = [p[14:] for p in self.icclist]
|
| 223 |
+
icc_profile = b"".join(profile)
|
| 224 |
+
else:
|
| 225 |
+
icc_profile = None # wrong number of fragments
|
| 226 |
+
self.info["icc_profile"] = icc_profile
|
| 227 |
+
self.icclist = []
|
| 228 |
+
|
| 229 |
+
for i in range(6, len(s), 3):
|
| 230 |
+
t = s[i : i + 3]
|
| 231 |
+
# 4-tuples: id, vsamp, hsamp, qtable
|
| 232 |
+
self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def DQT(self: JpegImageFile, marker: int) -> None:
|
| 236 |
+
#
|
| 237 |
+
# Define quantization table. Note that there might be more
|
| 238 |
+
# than one table in each marker.
|
| 239 |
+
|
| 240 |
+
# FIXME: The quantization tables can be used to estimate the
|
| 241 |
+
# compression quality.
|
| 242 |
+
|
| 243 |
+
n = i16(self.fp.read(2)) - 2
|
| 244 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 245 |
+
while len(s):
|
| 246 |
+
v = s[0]
|
| 247 |
+
precision = 1 if (v // 16 == 0) else 2 # in bytes
|
| 248 |
+
qt_length = 1 + precision * 64
|
| 249 |
+
if len(s) < qt_length:
|
| 250 |
+
msg = "bad quantization table marker"
|
| 251 |
+
raise SyntaxError(msg)
|
| 252 |
+
data = array.array("B" if precision == 1 else "H", s[1:qt_length])
|
| 253 |
+
if sys.byteorder == "little" and precision > 1:
|
| 254 |
+
data.byteswap() # the values are always big-endian
|
| 255 |
+
self.quantization[v & 15] = [data[i] for i in zigzag_index]
|
| 256 |
+
s = s[qt_length:]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
#
|
| 260 |
+
# JPEG marker table
|
| 261 |
+
|
| 262 |
+
MARKER = {
|
| 263 |
+
0xFFC0: ("SOF0", "Baseline DCT", SOF),
|
| 264 |
+
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
|
| 265 |
+
0xFFC2: ("SOF2", "Progressive DCT", SOF),
|
| 266 |
+
0xFFC3: ("SOF3", "Spatial lossless", SOF),
|
| 267 |
+
0xFFC4: ("DHT", "Define Huffman table", Skip),
|
| 268 |
+
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
|
| 269 |
+
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
|
| 270 |
+
0xFFC7: ("SOF7", "Differential spatial", SOF),
|
| 271 |
+
0xFFC8: ("JPG", "Extension", None),
|
| 272 |
+
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
|
| 273 |
+
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
|
| 274 |
+
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
|
| 275 |
+
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
|
| 276 |
+
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
|
| 277 |
+
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
|
| 278 |
+
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
|
| 279 |
+
0xFFD0: ("RST0", "Restart 0", None),
|
| 280 |
+
0xFFD1: ("RST1", "Restart 1", None),
|
| 281 |
+
0xFFD2: ("RST2", "Restart 2", None),
|
| 282 |
+
0xFFD3: ("RST3", "Restart 3", None),
|
| 283 |
+
0xFFD4: ("RST4", "Restart 4", None),
|
| 284 |
+
0xFFD5: ("RST5", "Restart 5", None),
|
| 285 |
+
0xFFD6: ("RST6", "Restart 6", None),
|
| 286 |
+
0xFFD7: ("RST7", "Restart 7", None),
|
| 287 |
+
0xFFD8: ("SOI", "Start of image", None),
|
| 288 |
+
0xFFD9: ("EOI", "End of image", None),
|
| 289 |
+
0xFFDA: ("SOS", "Start of scan", Skip),
|
| 290 |
+
0xFFDB: ("DQT", "Define quantization table", DQT),
|
| 291 |
+
0xFFDC: ("DNL", "Define number of lines", Skip),
|
| 292 |
+
0xFFDD: ("DRI", "Define restart interval", Skip),
|
| 293 |
+
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
|
| 294 |
+
0xFFDF: ("EXP", "Expand reference component", Skip),
|
| 295 |
+
0xFFE0: ("APP0", "Application segment 0", APP),
|
| 296 |
+
0xFFE1: ("APP1", "Application segment 1", APP),
|
| 297 |
+
0xFFE2: ("APP2", "Application segment 2", APP),
|
| 298 |
+
0xFFE3: ("APP3", "Application segment 3", APP),
|
| 299 |
+
0xFFE4: ("APP4", "Application segment 4", APP),
|
| 300 |
+
0xFFE5: ("APP5", "Application segment 5", APP),
|
| 301 |
+
0xFFE6: ("APP6", "Application segment 6", APP),
|
| 302 |
+
0xFFE7: ("APP7", "Application segment 7", APP),
|
| 303 |
+
0xFFE8: ("APP8", "Application segment 8", APP),
|
| 304 |
+
0xFFE9: ("APP9", "Application segment 9", APP),
|
| 305 |
+
0xFFEA: ("APP10", "Application segment 10", APP),
|
| 306 |
+
0xFFEB: ("APP11", "Application segment 11", APP),
|
| 307 |
+
0xFFEC: ("APP12", "Application segment 12", APP),
|
| 308 |
+
0xFFED: ("APP13", "Application segment 13", APP),
|
| 309 |
+
0xFFEE: ("APP14", "Application segment 14", APP),
|
| 310 |
+
0xFFEF: ("APP15", "Application segment 15", APP),
|
| 311 |
+
0xFFF0: ("JPG0", "Extension 0", None),
|
| 312 |
+
0xFFF1: ("JPG1", "Extension 1", None),
|
| 313 |
+
0xFFF2: ("JPG2", "Extension 2", None),
|
| 314 |
+
0xFFF3: ("JPG3", "Extension 3", None),
|
| 315 |
+
0xFFF4: ("JPG4", "Extension 4", None),
|
| 316 |
+
0xFFF5: ("JPG5", "Extension 5", None),
|
| 317 |
+
0xFFF6: ("JPG6", "Extension 6", None),
|
| 318 |
+
0xFFF7: ("JPG7", "Extension 7", None),
|
| 319 |
+
0xFFF8: ("JPG8", "Extension 8", None),
|
| 320 |
+
0xFFF9: ("JPG9", "Extension 9", None),
|
| 321 |
+
0xFFFA: ("JPG10", "Extension 10", None),
|
| 322 |
+
0xFFFB: ("JPG11", "Extension 11", None),
|
| 323 |
+
0xFFFC: ("JPG12", "Extension 12", None),
|
| 324 |
+
0xFFFD: ("JPG13", "Extension 13", None),
|
| 325 |
+
0xFFFE: ("COM", "Comment", COM),
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _accept(prefix: bytes) -> bool:
|
| 330 |
+
# Magic number was taken from https://en.wikipedia.org/wiki/JPEG
|
| 331 |
+
return prefix.startswith(b"\xff\xd8\xff")
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
##
|
| 335 |
+
# Image plugin for JPEG and JFIF images.
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class JpegImageFile(ImageFile.ImageFile):
|
| 339 |
+
format = "JPEG"
|
| 340 |
+
format_description = "JPEG (ISO 10918)"
|
| 341 |
+
|
| 342 |
+
def _open(self) -> None:
|
| 343 |
+
s = self.fp.read(3)
|
| 344 |
+
|
| 345 |
+
if not _accept(s):
|
| 346 |
+
msg = "not a JPEG file"
|
| 347 |
+
raise SyntaxError(msg)
|
| 348 |
+
s = b"\xff"
|
| 349 |
+
|
| 350 |
+
# Create attributes
|
| 351 |
+
self.bits = self.layers = 0
|
| 352 |
+
self._exif_offset = 0
|
| 353 |
+
|
| 354 |
+
# JPEG specifics (internal)
|
| 355 |
+
self.layer: list[tuple[int, int, int, int]] = []
|
| 356 |
+
self._huffman_dc: dict[Any, Any] = {}
|
| 357 |
+
self._huffman_ac: dict[Any, Any] = {}
|
| 358 |
+
self.quantization: dict[int, list[int]] = {}
|
| 359 |
+
self.app: dict[str, bytes] = {} # compatibility
|
| 360 |
+
self.applist: list[tuple[str, bytes]] = []
|
| 361 |
+
self.icclist: list[bytes] = []
|
| 362 |
+
|
| 363 |
+
while True:
|
| 364 |
+
i = s[0]
|
| 365 |
+
if i == 0xFF:
|
| 366 |
+
s = s + self.fp.read(1)
|
| 367 |
+
i = i16(s)
|
| 368 |
+
else:
|
| 369 |
+
# Skip non-0xFF junk
|
| 370 |
+
s = self.fp.read(1)
|
| 371 |
+
continue
|
| 372 |
+
|
| 373 |
+
if i in MARKER:
|
| 374 |
+
name, description, handler = MARKER[i]
|
| 375 |
+
if handler is not None:
|
| 376 |
+
handler(self, i)
|
| 377 |
+
if i == 0xFFDA: # start of scan
|
| 378 |
+
rawmode = self.mode
|
| 379 |
+
if self.mode == "CMYK":
|
| 380 |
+
rawmode = "CMYK;I" # assume adobe conventions
|
| 381 |
+
self.tile = [
|
| 382 |
+
ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, ""))
|
| 383 |
+
]
|
| 384 |
+
# self.__offset = self.fp.tell()
|
| 385 |
+
break
|
| 386 |
+
s = self.fp.read(1)
|
| 387 |
+
elif i in {0, 0xFFFF}:
|
| 388 |
+
# padded marker or junk; move on
|
| 389 |
+
s = b"\xff"
|
| 390 |
+
elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
|
| 391 |
+
s = self.fp.read(1)
|
| 392 |
+
else:
|
| 393 |
+
msg = "no marker found"
|
| 394 |
+
raise SyntaxError(msg)
|
| 395 |
+
|
| 396 |
+
self._read_dpi_from_exif()
|
| 397 |
+
|
| 398 |
+
def __getstate__(self) -> list[Any]:
|
| 399 |
+
return super().__getstate__() + [self.layers, self.layer]
|
| 400 |
+
|
| 401 |
+
def __setstate__(self, state: list[Any]) -> None:
|
| 402 |
+
self.layers, self.layer = state[6:]
|
| 403 |
+
super().__setstate__(state)
|
| 404 |
+
|
| 405 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 406 |
+
"""
|
| 407 |
+
internal: read more image data
|
| 408 |
+
For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
|
| 409 |
+
so libjpeg can finish decoding
|
| 410 |
+
"""
|
| 411 |
+
s = self.fp.read(read_bytes)
|
| 412 |
+
|
| 413 |
+
if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
|
| 414 |
+
# Premature EOF.
|
| 415 |
+
# Pretend file is finished adding EOI marker
|
| 416 |
+
self._ended = True
|
| 417 |
+
return b"\xff\xd9"
|
| 418 |
+
|
| 419 |
+
return s
|
| 420 |
+
|
| 421 |
+
def draft(
|
| 422 |
+
self, mode: str | None, size: tuple[int, int] | None
|
| 423 |
+
) -> tuple[str, tuple[int, int, float, float]] | None:
|
| 424 |
+
if len(self.tile) != 1:
|
| 425 |
+
return None
|
| 426 |
+
|
| 427 |
+
# Protect from second call
|
| 428 |
+
if self.decoderconfig:
|
| 429 |
+
return None
|
| 430 |
+
|
| 431 |
+
d, e, o, a = self.tile[0]
|
| 432 |
+
scale = 1
|
| 433 |
+
original_size = self.size
|
| 434 |
+
|
| 435 |
+
assert isinstance(a, tuple)
|
| 436 |
+
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
|
| 437 |
+
self._mode = mode
|
| 438 |
+
a = mode, ""
|
| 439 |
+
|
| 440 |
+
if size:
|
| 441 |
+
scale = min(self.size[0] // size[0], self.size[1] // size[1])
|
| 442 |
+
for s in [8, 4, 2, 1]:
|
| 443 |
+
if scale >= s:
|
| 444 |
+
break
|
| 445 |
+
assert e is not None
|
| 446 |
+
e = (
|
| 447 |
+
e[0],
|
| 448 |
+
e[1],
|
| 449 |
+
(e[2] - e[0] + s - 1) // s + e[0],
|
| 450 |
+
(e[3] - e[1] + s - 1) // s + e[1],
|
| 451 |
+
)
|
| 452 |
+
self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
|
| 453 |
+
scale = s
|
| 454 |
+
|
| 455 |
+
self.tile = [ImageFile._Tile(d, e, o, a)]
|
| 456 |
+
self.decoderconfig = (scale, 0)
|
| 457 |
+
|
| 458 |
+
box = (0, 0, original_size[0] / scale, original_size[1] / scale)
|
| 459 |
+
return self.mode, box
|
| 460 |
+
|
| 461 |
+
def load_djpeg(self) -> None:
|
| 462 |
+
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
|
| 463 |
+
|
| 464 |
+
f, path = tempfile.mkstemp()
|
| 465 |
+
os.close(f)
|
| 466 |
+
if os.path.exists(self.filename):
|
| 467 |
+
subprocess.check_call(["djpeg", "-outfile", path, self.filename])
|
| 468 |
+
else:
|
| 469 |
+
try:
|
| 470 |
+
os.unlink(path)
|
| 471 |
+
except OSError:
|
| 472 |
+
pass
|
| 473 |
+
|
| 474 |
+
msg = "Invalid Filename"
|
| 475 |
+
raise ValueError(msg)
|
| 476 |
+
|
| 477 |
+
try:
|
| 478 |
+
with Image.open(path) as _im:
|
| 479 |
+
_im.load()
|
| 480 |
+
self.im = _im.im
|
| 481 |
+
finally:
|
| 482 |
+
try:
|
| 483 |
+
os.unlink(path)
|
| 484 |
+
except OSError:
|
| 485 |
+
pass
|
| 486 |
+
|
| 487 |
+
self._mode = self.im.mode
|
| 488 |
+
self._size = self.im.size
|
| 489 |
+
|
| 490 |
+
self.tile = []
|
| 491 |
+
|
| 492 |
+
def _getexif(self) -> dict[int, Any] | None:
|
| 493 |
+
return _getexif(self)
|
| 494 |
+
|
| 495 |
+
def _read_dpi_from_exif(self) -> None:
|
| 496 |
+
# If DPI isn't in JPEG header, fetch from EXIF
|
| 497 |
+
if "dpi" in self.info or "exif" not in self.info:
|
| 498 |
+
return
|
| 499 |
+
try:
|
| 500 |
+
exif = self.getexif()
|
| 501 |
+
resolution_unit = exif[0x0128]
|
| 502 |
+
x_resolution = exif[0x011A]
|
| 503 |
+
try:
|
| 504 |
+
dpi = float(x_resolution[0]) / x_resolution[1]
|
| 505 |
+
except TypeError:
|
| 506 |
+
dpi = x_resolution
|
| 507 |
+
if math.isnan(dpi):
|
| 508 |
+
msg = "DPI is not a number"
|
| 509 |
+
raise ValueError(msg)
|
| 510 |
+
if resolution_unit == 3: # cm
|
| 511 |
+
# 1 dpcm = 2.54 dpi
|
| 512 |
+
dpi *= 2.54
|
| 513 |
+
self.info["dpi"] = dpi, dpi
|
| 514 |
+
except (
|
| 515 |
+
struct.error, # truncated EXIF
|
| 516 |
+
KeyError, # dpi not included
|
| 517 |
+
SyntaxError, # invalid/unreadable EXIF
|
| 518 |
+
TypeError, # dpi is an invalid float
|
| 519 |
+
ValueError, # dpi is an invalid float
|
| 520 |
+
ZeroDivisionError, # invalid dpi rational value
|
| 521 |
+
):
|
| 522 |
+
self.info["dpi"] = 72, 72
|
| 523 |
+
|
| 524 |
+
def _getmp(self) -> dict[int, Any] | None:
|
| 525 |
+
return _getmp(self)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _getexif(self: JpegImageFile) -> dict[int, Any] | None:
|
| 529 |
+
if "exif" not in self.info:
|
| 530 |
+
return None
|
| 531 |
+
return self.getexif()._get_merged_dict()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _getmp(self: JpegImageFile) -> dict[int, Any] | None:
|
| 535 |
+
# Extract MP information. This method was inspired by the "highly
|
| 536 |
+
# experimental" _getexif version that's been in use for years now,
|
| 537 |
+
# itself based on the ImageFileDirectory class in the TIFF plugin.
|
| 538 |
+
|
| 539 |
+
# The MP record essentially consists of a TIFF file embedded in a JPEG
|
| 540 |
+
# application marker.
|
| 541 |
+
try:
|
| 542 |
+
data = self.info["mp"]
|
| 543 |
+
except KeyError:
|
| 544 |
+
return None
|
| 545 |
+
file_contents = io.BytesIO(data)
|
| 546 |
+
head = file_contents.read(8)
|
| 547 |
+
endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"
|
| 548 |
+
# process dictionary
|
| 549 |
+
from . import TiffImagePlugin
|
| 550 |
+
|
| 551 |
+
try:
|
| 552 |
+
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
| 553 |
+
file_contents.seek(info.next)
|
| 554 |
+
info.load(file_contents)
|
| 555 |
+
mp = dict(info)
|
| 556 |
+
except Exception as e:
|
| 557 |
+
msg = "malformed MP Index (unreadable directory)"
|
| 558 |
+
raise SyntaxError(msg) from e
|
| 559 |
+
# it's an error not to have a number of images
|
| 560 |
+
try:
|
| 561 |
+
quant = mp[0xB001]
|
| 562 |
+
except KeyError as e:
|
| 563 |
+
msg = "malformed MP Index (no number of images)"
|
| 564 |
+
raise SyntaxError(msg) from e
|
| 565 |
+
# get MP entries
|
| 566 |
+
mpentries = []
|
| 567 |
+
try:
|
| 568 |
+
rawmpentries = mp[0xB002]
|
| 569 |
+
for entrynum in range(quant):
|
| 570 |
+
unpackedentry = struct.unpack_from(
|
| 571 |
+
f"{endianness}LLLHH", rawmpentries, entrynum * 16
|
| 572 |
+
)
|
| 573 |
+
labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")
|
| 574 |
+
mpentry = dict(zip(labels, unpackedentry))
|
| 575 |
+
mpentryattr = {
|
| 576 |
+
"DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),
|
| 577 |
+
"DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),
|
| 578 |
+
"RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),
|
| 579 |
+
"Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,
|
| 580 |
+
"ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,
|
| 581 |
+
"MPType": mpentry["Attribute"] & 0x00FFFFFF,
|
| 582 |
+
}
|
| 583 |
+
if mpentryattr["ImageDataFormat"] == 0:
|
| 584 |
+
mpentryattr["ImageDataFormat"] = "JPEG"
|
| 585 |
+
else:
|
| 586 |
+
msg = "unsupported picture format in MPO"
|
| 587 |
+
raise SyntaxError(msg)
|
| 588 |
+
mptypemap = {
|
| 589 |
+
0x000000: "Undefined",
|
| 590 |
+
0x010001: "Large Thumbnail (VGA Equivalent)",
|
| 591 |
+
0x010002: "Large Thumbnail (Full HD Equivalent)",
|
| 592 |
+
0x020001: "Multi-Frame Image (Panorama)",
|
| 593 |
+
0x020002: "Multi-Frame Image: (Disparity)",
|
| 594 |
+
0x020003: "Multi-Frame Image: (Multi-Angle)",
|
| 595 |
+
0x030000: "Baseline MP Primary Image",
|
| 596 |
+
}
|
| 597 |
+
mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")
|
| 598 |
+
mpentry["Attribute"] = mpentryattr
|
| 599 |
+
mpentries.append(mpentry)
|
| 600 |
+
mp[0xB002] = mpentries
|
| 601 |
+
except KeyError as e:
|
| 602 |
+
msg = "malformed MP Index (bad MP Entry)"
|
| 603 |
+
raise SyntaxError(msg) from e
|
| 604 |
+
# Next we should try and parse the individual image unique ID list;
|
| 605 |
+
# we don't because I've never seen this actually used in a real MPO
|
| 606 |
+
# file and so can't test it.
|
| 607 |
+
return mp
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
# --------------------------------------------------------------------
|
| 611 |
+
# stuff to save JPEG files
|
| 612 |
+
|
| 613 |
+
RAWMODE = {
|
| 614 |
+
"1": "L",
|
| 615 |
+
"L": "L",
|
| 616 |
+
"RGB": "RGB",
|
| 617 |
+
"RGBX": "RGB",
|
| 618 |
+
"CMYK": "CMYK;I", # assume adobe conventions
|
| 619 |
+
"YCbCr": "YCbCr",
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
# fmt: off
|
| 623 |
+
zigzag_index = (
|
| 624 |
+
0, 1, 5, 6, 14, 15, 27, 28,
|
| 625 |
+
2, 4, 7, 13, 16, 26, 29, 42,
|
| 626 |
+
3, 8, 12, 17, 25, 30, 41, 43,
|
| 627 |
+
9, 11, 18, 24, 31, 40, 44, 53,
|
| 628 |
+
10, 19, 23, 32, 39, 45, 52, 54,
|
| 629 |
+
20, 22, 33, 38, 46, 51, 55, 60,
|
| 630 |
+
21, 34, 37, 47, 50, 56, 59, 61,
|
| 631 |
+
35, 36, 48, 49, 57, 58, 62, 63,
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
samplings = {
|
| 635 |
+
(1, 1, 1, 1, 1, 1): 0,
|
| 636 |
+
(2, 1, 1, 1, 1, 1): 1,
|
| 637 |
+
(2, 2, 1, 1, 1, 1): 2,
|
| 638 |
+
}
|
| 639 |
+
# fmt: on
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def get_sampling(im: Image.Image) -> int:
|
| 643 |
+
# There's no subsampling when images have only 1 layer
|
| 644 |
+
# (grayscale images) or when they are CMYK (4 layers),
|
| 645 |
+
# so set subsampling to the default value.
|
| 646 |
+
#
|
| 647 |
+
# NOTE: currently Pillow can't encode JPEG to YCCK format.
|
| 648 |
+
# If YCCK support is added in the future, subsampling code will have
|
| 649 |
+
# to be updated (here and in JpegEncode.c) to deal with 4 layers.
|
| 650 |
+
if not isinstance(im, JpegImageFile) or im.layers in (1, 4):
|
| 651 |
+
return -1
|
| 652 |
+
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
|
| 653 |
+
return samplings.get(sampling, -1)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 657 |
+
if im.width == 0 or im.height == 0:
|
| 658 |
+
msg = "cannot write empty image as JPEG"
|
| 659 |
+
raise ValueError(msg)
|
| 660 |
+
|
| 661 |
+
try:
|
| 662 |
+
rawmode = RAWMODE[im.mode]
|
| 663 |
+
except KeyError as e:
|
| 664 |
+
msg = f"cannot write mode {im.mode} as JPEG"
|
| 665 |
+
raise OSError(msg) from e
|
| 666 |
+
|
| 667 |
+
info = im.encoderinfo
|
| 668 |
+
|
| 669 |
+
dpi = [round(x) for x in info.get("dpi", (0, 0))]
|
| 670 |
+
|
| 671 |
+
quality = info.get("quality", -1)
|
| 672 |
+
subsampling = info.get("subsampling", -1)
|
| 673 |
+
qtables = info.get("qtables")
|
| 674 |
+
|
| 675 |
+
if quality == "keep":
|
| 676 |
+
quality = -1
|
| 677 |
+
subsampling = "keep"
|
| 678 |
+
qtables = "keep"
|
| 679 |
+
elif quality in presets:
|
| 680 |
+
preset = presets[quality]
|
| 681 |
+
quality = -1
|
| 682 |
+
subsampling = preset.get("subsampling", -1)
|
| 683 |
+
qtables = preset.get("quantization")
|
| 684 |
+
elif not isinstance(quality, int):
|
| 685 |
+
msg = "Invalid quality setting"
|
| 686 |
+
raise ValueError(msg)
|
| 687 |
+
else:
|
| 688 |
+
if subsampling in presets:
|
| 689 |
+
subsampling = presets[subsampling].get("subsampling", -1)
|
| 690 |
+
if isinstance(qtables, str) and qtables in presets:
|
| 691 |
+
qtables = presets[qtables].get("quantization")
|
| 692 |
+
|
| 693 |
+
if subsampling == "4:4:4":
|
| 694 |
+
subsampling = 0
|
| 695 |
+
elif subsampling == "4:2:2":
|
| 696 |
+
subsampling = 1
|
| 697 |
+
elif subsampling == "4:2:0":
|
| 698 |
+
subsampling = 2
|
| 699 |
+
elif subsampling == "4:1:1":
|
| 700 |
+
# For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.
|
| 701 |
+
# Set 4:2:0 if someone is still using that value.
|
| 702 |
+
subsampling = 2
|
| 703 |
+
elif subsampling == "keep":
|
| 704 |
+
if im.format != "JPEG":
|
| 705 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 706 |
+
raise ValueError(msg)
|
| 707 |
+
subsampling = get_sampling(im)
|
| 708 |
+
|
| 709 |
+
def validate_qtables(
|
| 710 |
+
qtables: (
|
| 711 |
+
str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None
|
| 712 |
+
),
|
| 713 |
+
) -> list[list[int]] | None:
|
| 714 |
+
if qtables is None:
|
| 715 |
+
return qtables
|
| 716 |
+
if isinstance(qtables, str):
|
| 717 |
+
try:
|
| 718 |
+
lines = [
|
| 719 |
+
int(num)
|
| 720 |
+
for line in qtables.splitlines()
|
| 721 |
+
for num in line.split("#", 1)[0].split()
|
| 722 |
+
]
|
| 723 |
+
except ValueError as e:
|
| 724 |
+
msg = "Invalid quantization table"
|
| 725 |
+
raise ValueError(msg) from e
|
| 726 |
+
else:
|
| 727 |
+
qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]
|
| 728 |
+
if isinstance(qtables, (tuple, list, dict)):
|
| 729 |
+
if isinstance(qtables, dict):
|
| 730 |
+
qtables = [
|
| 731 |
+
qtables[key] for key in range(len(qtables)) if key in qtables
|
| 732 |
+
]
|
| 733 |
+
elif isinstance(qtables, tuple):
|
| 734 |
+
qtables = list(qtables)
|
| 735 |
+
if not (0 < len(qtables) < 5):
|
| 736 |
+
msg = "None or too many quantization tables"
|
| 737 |
+
raise ValueError(msg)
|
| 738 |
+
for idx, table in enumerate(qtables):
|
| 739 |
+
try:
|
| 740 |
+
if len(table) != 64:
|
| 741 |
+
msg = "Invalid quantization table"
|
| 742 |
+
raise TypeError(msg)
|
| 743 |
+
table_array = array.array("H", table)
|
| 744 |
+
except TypeError as e:
|
| 745 |
+
msg = "Invalid quantization table"
|
| 746 |
+
raise ValueError(msg) from e
|
| 747 |
+
else:
|
| 748 |
+
qtables[idx] = list(table_array)
|
| 749 |
+
return qtables
|
| 750 |
+
|
| 751 |
+
if qtables == "keep":
|
| 752 |
+
if im.format != "JPEG":
|
| 753 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 754 |
+
raise ValueError(msg)
|
| 755 |
+
qtables = getattr(im, "quantization", None)
|
| 756 |
+
qtables = validate_qtables(qtables)
|
| 757 |
+
|
| 758 |
+
extra = info.get("extra", b"")
|
| 759 |
+
|
| 760 |
+
MAX_BYTES_IN_MARKER = 65533
|
| 761 |
+
if xmp := info.get("xmp"):
|
| 762 |
+
overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00"
|
| 763 |
+
max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
|
| 764 |
+
if len(xmp) > max_data_bytes_in_marker:
|
| 765 |
+
msg = "XMP data is too long"
|
| 766 |
+
raise ValueError(msg)
|
| 767 |
+
size = o16(2 + overhead_len + len(xmp))
|
| 768 |
+
extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp
|
| 769 |
+
|
| 770 |
+
if icc_profile := info.get("icc_profile"):
|
| 771 |
+
overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers))
|
| 772 |
+
max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
|
| 773 |
+
markers = []
|
| 774 |
+
while icc_profile:
|
| 775 |
+
markers.append(icc_profile[:max_data_bytes_in_marker])
|
| 776 |
+
icc_profile = icc_profile[max_data_bytes_in_marker:]
|
| 777 |
+
i = 1
|
| 778 |
+
for marker in markers:
|
| 779 |
+
size = o16(2 + overhead_len + len(marker))
|
| 780 |
+
extra += (
|
| 781 |
+
b"\xff\xe2"
|
| 782 |
+
+ size
|
| 783 |
+
+ b"ICC_PROFILE\0"
|
| 784 |
+
+ o8(i)
|
| 785 |
+
+ o8(len(markers))
|
| 786 |
+
+ marker
|
| 787 |
+
)
|
| 788 |
+
i += 1
|
| 789 |
+
|
| 790 |
+
comment = info.get("comment", im.info.get("comment"))
|
| 791 |
+
|
| 792 |
+
# "progressive" is the official name, but older documentation
|
| 793 |
+
# says "progression"
|
| 794 |
+
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
|
| 795 |
+
progressive = info.get("progressive", False) or info.get("progression", False)
|
| 796 |
+
|
| 797 |
+
optimize = info.get("optimize", False)
|
| 798 |
+
|
| 799 |
+
exif = info.get("exif", b"")
|
| 800 |
+
if isinstance(exif, Image.Exif):
|
| 801 |
+
exif = exif.tobytes()
|
| 802 |
+
if len(exif) > MAX_BYTES_IN_MARKER:
|
| 803 |
+
msg = "EXIF data is too long"
|
| 804 |
+
raise ValueError(msg)
|
| 805 |
+
|
| 806 |
+
# get keyword arguments
|
| 807 |
+
im.encoderconfig = (
|
| 808 |
+
quality,
|
| 809 |
+
progressive,
|
| 810 |
+
info.get("smooth", 0),
|
| 811 |
+
optimize,
|
| 812 |
+
info.get("keep_rgb", False),
|
| 813 |
+
info.get("streamtype", 0),
|
| 814 |
+
dpi,
|
| 815 |
+
subsampling,
|
| 816 |
+
info.get("restart_marker_blocks", 0),
|
| 817 |
+
info.get("restart_marker_rows", 0),
|
| 818 |
+
qtables,
|
| 819 |
+
comment,
|
| 820 |
+
extra,
|
| 821 |
+
exif,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
# if we optimize, libjpeg needs a buffer big enough to hold the whole image
|
| 825 |
+
# in a shot. Guessing on the size, at im.size bytes. (raw pixel size is
|
| 826 |
+
# channels*size, this is a value that's been used in a django patch.
|
| 827 |
+
# https://github.com/matthewwithanm/django-imagekit/issues/50
|
| 828 |
+
if optimize or progressive:
|
| 829 |
+
# CMYK can be bigger
|
| 830 |
+
if im.mode == "CMYK":
|
| 831 |
+
bufsize = 4 * im.size[0] * im.size[1]
|
| 832 |
+
# keep sets quality to -1, but the actual value may be high.
|
| 833 |
+
elif quality >= 95 or quality == -1:
|
| 834 |
+
bufsize = 2 * im.size[0] * im.size[1]
|
| 835 |
+
else:
|
| 836 |
+
bufsize = im.size[0] * im.size[1]
|
| 837 |
+
if exif:
|
| 838 |
+
bufsize += len(exif) + 5
|
| 839 |
+
if extra:
|
| 840 |
+
bufsize += len(extra) + 1
|
| 841 |
+
else:
|
| 842 |
+
# The EXIF info needs to be written as one block, + APP1, + one spare byte.
|
| 843 |
+
# Ensure that our buffer is big enough. Same with the icc_profile block.
|
| 844 |
+
bufsize = max(len(exif) + 5, len(extra) + 1)
|
| 845 |
+
|
| 846 |
+
ImageFile._save(
|
| 847 |
+
im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
##
|
| 852 |
+
# Factory for making JPEG and MPO instances
|
| 853 |
+
def jpeg_factory(
|
| 854 |
+
fp: IO[bytes], filename: str | bytes | None = None
|
| 855 |
+
) -> JpegImageFile | MpoImageFile:
|
| 856 |
+
im = JpegImageFile(fp, filename)
|
| 857 |
+
try:
|
| 858 |
+
mpheader = im._getmp()
|
| 859 |
+
if mpheader is not None and mpheader[45057] > 1:
|
| 860 |
+
for segment, content in im.applist:
|
| 861 |
+
if segment == "APP1" and b' hdrgm:Version="' in content:
|
| 862 |
+
# Ultra HDR images are not yet supported
|
| 863 |
+
return im
|
| 864 |
+
# It's actually an MPO
|
| 865 |
+
from .MpoImagePlugin import MpoImageFile
|
| 866 |
+
|
| 867 |
+
# Don't reload everything, just convert it.
|
| 868 |
+
im = MpoImageFile.adopt(im, mpheader)
|
| 869 |
+
except (TypeError, IndexError):
|
| 870 |
+
# It is really a JPEG
|
| 871 |
+
pass
|
| 872 |
+
except SyntaxError:
|
| 873 |
+
warnings.warn(
|
| 874 |
+
"Image appears to be a malformed MPO file, it will be "
|
| 875 |
+
"interpreted as a base JPEG file"
|
| 876 |
+
)
|
| 877 |
+
return im
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
# ---------------------------------------------------------------------
|
| 881 |
+
# Registry stuff
|
| 882 |
+
|
| 883 |
+
Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
|
| 884 |
+
Image.register_save(JpegImageFile.format, _save)
|
| 885 |
+
|
| 886 |
+
Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])
|
| 887 |
+
|
| 888 |
+
Image.register_mime(JpegImageFile.format, "image/jpeg")
|
.venv/lib/python3.12/site-packages/PIL/JpegPresets.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JPEG quality settings equivalent to the Photoshop settings.
|
| 3 |
+
Can be used when saving JPEG files.
|
| 4 |
+
|
| 5 |
+
The following presets are available by default:
|
| 6 |
+
``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
|
| 7 |
+
``low``, ``medium``, ``high``, ``maximum``.
|
| 8 |
+
More presets can be added to the :py:data:`presets` dict if needed.
|
| 9 |
+
|
| 10 |
+
To apply the preset, specify::
|
| 11 |
+
|
| 12 |
+
quality="preset_name"
|
| 13 |
+
|
| 14 |
+
To apply only the quantization table::
|
| 15 |
+
|
| 16 |
+
qtables="preset_name"
|
| 17 |
+
|
| 18 |
+
To apply only the subsampling setting::
|
| 19 |
+
|
| 20 |
+
subsampling="preset_name"
|
| 21 |
+
|
| 22 |
+
Example::
|
| 23 |
+
|
| 24 |
+
im.save("image_name.jpg", quality="web_high")
|
| 25 |
+
|
| 26 |
+
Subsampling
|
| 27 |
+
-----------
|
| 28 |
+
|
| 29 |
+
Subsampling is the practice of encoding images by implementing less resolution
|
| 30 |
+
for chroma information than for luma information.
|
| 31 |
+
(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
|
| 32 |
+
|
| 33 |
+
Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and
|
| 34 |
+
4:2:0.
|
| 35 |
+
|
| 36 |
+
You can get the subsampling of a JPEG with the
|
| 37 |
+
:func:`.JpegImagePlugin.get_sampling` function.
|
| 38 |
+
|
| 39 |
+
In JPEG compressed data a JPEG marker is used instead of an EXIF tag.
|
| 40 |
+
(ref.: https://exiv2.org/tags.html)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
Quantization tables
|
| 44 |
+
-------------------
|
| 45 |
+
|
| 46 |
+
They are values use by the DCT (Discrete cosine transform) to remove
|
| 47 |
+
*unnecessary* information from the image (the lossy part of the compression).
|
| 48 |
+
(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
|
| 49 |
+
https://en.wikipedia.org/wiki/JPEG#Quantization)
|
| 50 |
+
|
| 51 |
+
You can get the quantization tables of a JPEG with::
|
| 52 |
+
|
| 53 |
+
im.quantization
|
| 54 |
+
|
| 55 |
+
This will return a dict with a number of lists. You can pass this dict
|
| 56 |
+
directly as the qtables argument when saving a JPEG.
|
| 57 |
+
|
| 58 |
+
The quantization table format in presets is a list with sublists. These formats
|
| 59 |
+
are interchangeable.
|
| 60 |
+
|
| 61 |
+
Libjpeg ref.:
|
| 62 |
+
https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
from __future__ import annotations
|
| 67 |
+
|
| 68 |
+
# fmt: off
|
| 69 |
+
presets = {
|
| 70 |
+
'web_low': {'subsampling': 2, # "4:2:0"
|
| 71 |
+
'quantization': [
|
| 72 |
+
[20, 16, 25, 39, 50, 46, 62, 68,
|
| 73 |
+
16, 18, 23, 38, 38, 53, 65, 68,
|
| 74 |
+
25, 23, 31, 38, 53, 65, 68, 68,
|
| 75 |
+
39, 38, 38, 53, 65, 68, 68, 68,
|
| 76 |
+
50, 38, 53, 65, 68, 68, 68, 68,
|
| 77 |
+
46, 53, 65, 68, 68, 68, 68, 68,
|
| 78 |
+
62, 65, 68, 68, 68, 68, 68, 68,
|
| 79 |
+
68, 68, 68, 68, 68, 68, 68, 68],
|
| 80 |
+
[21, 25, 32, 38, 54, 68, 68, 68,
|
| 81 |
+
25, 28, 24, 38, 54, 68, 68, 68,
|
| 82 |
+
32, 24, 32, 43, 66, 68, 68, 68,
|
| 83 |
+
38, 38, 43, 53, 68, 68, 68, 68,
|
| 84 |
+
54, 54, 66, 68, 68, 68, 68, 68,
|
| 85 |
+
68, 68, 68, 68, 68, 68, 68, 68,
|
| 86 |
+
68, 68, 68, 68, 68, 68, 68, 68,
|
| 87 |
+
68, 68, 68, 68, 68, 68, 68, 68]
|
| 88 |
+
]},
|
| 89 |
+
'web_medium': {'subsampling': 2, # "4:2:0"
|
| 90 |
+
'quantization': [
|
| 91 |
+
[16, 11, 11, 16, 23, 27, 31, 30,
|
| 92 |
+
11, 12, 12, 15, 20, 23, 23, 30,
|
| 93 |
+
11, 12, 13, 16, 23, 26, 35, 47,
|
| 94 |
+
16, 15, 16, 23, 26, 37, 47, 64,
|
| 95 |
+
23, 20, 23, 26, 39, 51, 64, 64,
|
| 96 |
+
27, 23, 26, 37, 51, 64, 64, 64,
|
| 97 |
+
31, 23, 35, 47, 64, 64, 64, 64,
|
| 98 |
+
30, 30, 47, 64, 64, 64, 64, 64],
|
| 99 |
+
[17, 15, 17, 21, 20, 26, 38, 48,
|
| 100 |
+
15, 19, 18, 17, 20, 26, 35, 43,
|
| 101 |
+
17, 18, 20, 22, 26, 30, 46, 53,
|
| 102 |
+
21, 17, 22, 28, 30, 39, 53, 64,
|
| 103 |
+
20, 20, 26, 30, 39, 48, 64, 64,
|
| 104 |
+
26, 26, 30, 39, 48, 63, 64, 64,
|
| 105 |
+
38, 35, 46, 53, 64, 64, 64, 64,
|
| 106 |
+
48, 43, 53, 64, 64, 64, 64, 64]
|
| 107 |
+
]},
|
| 108 |
+
'web_high': {'subsampling': 0, # "4:4:4"
|
| 109 |
+
'quantization': [
|
| 110 |
+
[6, 4, 4, 6, 9, 11, 12, 16,
|
| 111 |
+
4, 5, 5, 6, 8, 10, 12, 12,
|
| 112 |
+
4, 5, 5, 6, 10, 12, 14, 19,
|
| 113 |
+
6, 6, 6, 11, 12, 15, 19, 28,
|
| 114 |
+
9, 8, 10, 12, 16, 20, 27, 31,
|
| 115 |
+
11, 10, 12, 15, 20, 27, 31, 31,
|
| 116 |
+
12, 12, 14, 19, 27, 31, 31, 31,
|
| 117 |
+
16, 12, 19, 28, 31, 31, 31, 31],
|
| 118 |
+
[7, 7, 13, 24, 26, 31, 31, 31,
|
| 119 |
+
7, 12, 16, 21, 31, 31, 31, 31,
|
| 120 |
+
13, 16, 17, 31, 31, 31, 31, 31,
|
| 121 |
+
24, 21, 31, 31, 31, 31, 31, 31,
|
| 122 |
+
26, 31, 31, 31, 31, 31, 31, 31,
|
| 123 |
+
31, 31, 31, 31, 31, 31, 31, 31,
|
| 124 |
+
31, 31, 31, 31, 31, 31, 31, 31,
|
| 125 |
+
31, 31, 31, 31, 31, 31, 31, 31]
|
| 126 |
+
]},
|
| 127 |
+
'web_very_high': {'subsampling': 0, # "4:4:4"
|
| 128 |
+
'quantization': [
|
| 129 |
+
[2, 2, 2, 2, 3, 4, 5, 6,
|
| 130 |
+
2, 2, 2, 2, 3, 4, 5, 6,
|
| 131 |
+
2, 2, 2, 2, 4, 5, 7, 9,
|
| 132 |
+
2, 2, 2, 4, 5, 7, 9, 12,
|
| 133 |
+
3, 3, 4, 5, 8, 10, 12, 12,
|
| 134 |
+
4, 4, 5, 7, 10, 12, 12, 12,
|
| 135 |
+
5, 5, 7, 9, 12, 12, 12, 12,
|
| 136 |
+
6, 6, 9, 12, 12, 12, 12, 12],
|
| 137 |
+
[3, 3, 5, 9, 13, 15, 15, 15,
|
| 138 |
+
3, 4, 6, 11, 14, 12, 12, 12,
|
| 139 |
+
5, 6, 9, 14, 12, 12, 12, 12,
|
| 140 |
+
9, 11, 14, 12, 12, 12, 12, 12,
|
| 141 |
+
13, 14, 12, 12, 12, 12, 12, 12,
|
| 142 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 143 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 144 |
+
15, 12, 12, 12, 12, 12, 12, 12]
|
| 145 |
+
]},
|
| 146 |
+
'web_maximum': {'subsampling': 0, # "4:4:4"
|
| 147 |
+
'quantization': [
|
| 148 |
+
[1, 1, 1, 1, 1, 1, 1, 1,
|
| 149 |
+
1, 1, 1, 1, 1, 1, 1, 1,
|
| 150 |
+
1, 1, 1, 1, 1, 1, 1, 2,
|
| 151 |
+
1, 1, 1, 1, 1, 1, 2, 2,
|
| 152 |
+
1, 1, 1, 1, 1, 2, 2, 3,
|
| 153 |
+
1, 1, 1, 1, 2, 2, 3, 3,
|
| 154 |
+
1, 1, 1, 2, 2, 3, 3, 3,
|
| 155 |
+
1, 1, 2, 2, 3, 3, 3, 3],
|
| 156 |
+
[1, 1, 1, 2, 2, 3, 3, 3,
|
| 157 |
+
1, 1, 1, 2, 3, 3, 3, 3,
|
| 158 |
+
1, 1, 1, 3, 3, 3, 3, 3,
|
| 159 |
+
2, 2, 3, 3, 3, 3, 3, 3,
|
| 160 |
+
2, 3, 3, 3, 3, 3, 3, 3,
|
| 161 |
+
3, 3, 3, 3, 3, 3, 3, 3,
|
| 162 |
+
3, 3, 3, 3, 3, 3, 3, 3,
|
| 163 |
+
3, 3, 3, 3, 3, 3, 3, 3]
|
| 164 |
+
]},
|
| 165 |
+
'low': {'subsampling': 2, # "4:2:0"
|
| 166 |
+
'quantization': [
|
| 167 |
+
[18, 14, 14, 21, 30, 35, 34, 17,
|
| 168 |
+
14, 16, 16, 19, 26, 23, 12, 12,
|
| 169 |
+
14, 16, 17, 21, 23, 12, 12, 12,
|
| 170 |
+
21, 19, 21, 23, 12, 12, 12, 12,
|
| 171 |
+
30, 26, 23, 12, 12, 12, 12, 12,
|
| 172 |
+
35, 23, 12, 12, 12, 12, 12, 12,
|
| 173 |
+
34, 12, 12, 12, 12, 12, 12, 12,
|
| 174 |
+
17, 12, 12, 12, 12, 12, 12, 12],
|
| 175 |
+
[20, 19, 22, 27, 20, 20, 17, 17,
|
| 176 |
+
19, 25, 23, 14, 14, 12, 12, 12,
|
| 177 |
+
22, 23, 14, 14, 12, 12, 12, 12,
|
| 178 |
+
27, 14, 14, 12, 12, 12, 12, 12,
|
| 179 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 180 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 181 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 182 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 183 |
+
]},
|
| 184 |
+
'medium': {'subsampling': 2, # "4:2:0"
|
| 185 |
+
'quantization': [
|
| 186 |
+
[12, 8, 8, 12, 17, 21, 24, 17,
|
| 187 |
+
8, 9, 9, 11, 15, 19, 12, 12,
|
| 188 |
+
8, 9, 10, 12, 19, 12, 12, 12,
|
| 189 |
+
12, 11, 12, 21, 12, 12, 12, 12,
|
| 190 |
+
17, 15, 19, 12, 12, 12, 12, 12,
|
| 191 |
+
21, 19, 12, 12, 12, 12, 12, 12,
|
| 192 |
+
24, 12, 12, 12, 12, 12, 12, 12,
|
| 193 |
+
17, 12, 12, 12, 12, 12, 12, 12],
|
| 194 |
+
[13, 11, 13, 16, 20, 20, 17, 17,
|
| 195 |
+
11, 14, 14, 14, 14, 12, 12, 12,
|
| 196 |
+
13, 14, 14, 14, 12, 12, 12, 12,
|
| 197 |
+
16, 14, 14, 12, 12, 12, 12, 12,
|
| 198 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 199 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 200 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 201 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 202 |
+
]},
|
| 203 |
+
'high': {'subsampling': 0, # "4:4:4"
|
| 204 |
+
'quantization': [
|
| 205 |
+
[6, 4, 4, 6, 9, 11, 12, 16,
|
| 206 |
+
4, 5, 5, 6, 8, 10, 12, 12,
|
| 207 |
+
4, 5, 5, 6, 10, 12, 12, 12,
|
| 208 |
+
6, 6, 6, 11, 12, 12, 12, 12,
|
| 209 |
+
9, 8, 10, 12, 12, 12, 12, 12,
|
| 210 |
+
11, 10, 12, 12, 12, 12, 12, 12,
|
| 211 |
+
12, 12, 12, 12, 12, 12, 12, 12,
|
| 212 |
+
16, 12, 12, 12, 12, 12, 12, 12],
|
| 213 |
+
[7, 7, 13, 24, 20, 20, 17, 17,
|
| 214 |
+
7, 12, 16, 14, 14, 12, 12, 12,
|
| 215 |
+
13, 16, 14, 14, 12, 12, 12, 12,
|
| 216 |
+
24, 14, 14, 12, 12, 12, 12, 12,
|
| 217 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 218 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 219 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 220 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 221 |
+
]},
|
| 222 |
+
'maximum': {'subsampling': 0, # "4:4:4"
|
| 223 |
+
'quantization': [
|
| 224 |
+
[2, 2, 2, 2, 3, 4, 5, 6,
|
| 225 |
+
2, 2, 2, 2, 3, 4, 5, 6,
|
| 226 |
+
2, 2, 2, 2, 4, 5, 7, 9,
|
| 227 |
+
2, 2, 2, 4, 5, 7, 9, 12,
|
| 228 |
+
3, 3, 4, 5, 8, 10, 12, 12,
|
| 229 |
+
4, 4, 5, 7, 10, 12, 12, 12,
|
| 230 |
+
5, 5, 7, 9, 12, 12, 12, 12,
|
| 231 |
+
6, 6, 9, 12, 12, 12, 12, 12],
|
| 232 |
+
[3, 3, 5, 9, 13, 15, 15, 15,
|
| 233 |
+
3, 4, 6, 10, 14, 12, 12, 12,
|
| 234 |
+
5, 6, 9, 14, 12, 12, 12, 12,
|
| 235 |
+
9, 10, 14, 12, 12, 12, 12, 12,
|
| 236 |
+
13, 14, 12, 12, 12, 12, 12, 12,
|
| 237 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 238 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 239 |
+
15, 12, 12, 12, 12, 12, 12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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PNG support code
|
| 6 |
+
#
|
| 7 |
+
# See "PNG (Portable Network Graphics) Specification, version 1.0;
|
| 8 |
+
# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
|
| 9 |
+
#
|
| 10 |
+
# history:
|
| 11 |
+
# 1996-05-06 fl Created (couldn't resist it)
|
| 12 |
+
# 1996-12-14 fl Upgraded, added read and verify support (0.2)
|
| 13 |
+
# 1996-12-15 fl Separate PNG stream parser
|
| 14 |
+
# 1996-12-29 fl Added write support, added getchunks
|
| 15 |
+
# 1996-12-30 fl Eliminated circular references in decoder (0.3)
|
| 16 |
+
# 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
|
| 17 |
+
# 2001-02-08 fl Added transparency support (from Zircon) (0.5)
|
| 18 |
+
# 2001-04-16 fl Don't close data source in "open" method (0.6)
|
| 19 |
+
# 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
|
| 20 |
+
# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
|
| 21 |
+
# 2004-09-20 fl Added PngInfo chunk container
|
| 22 |
+
# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
|
| 23 |
+
# 2008-08-13 fl Added tRNS support for RGB images
|
| 24 |
+
# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
|
| 25 |
+
# 2009-03-08 fl Added zTXT support (from Lowell Alleman)
|
| 26 |
+
# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
|
| 27 |
+
#
|
| 28 |
+
# Copyright (c) 1997-2009 by Secret Labs AB
|
| 29 |
+
# Copyright (c) 1996 by Fredrik Lundh
|
| 30 |
+
#
|
| 31 |
+
# See the README file for information on usage and redistribution.
|
| 32 |
+
#
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import itertools
|
| 36 |
+
import logging
|
| 37 |
+
import re
|
| 38 |
+
import struct
|
| 39 |
+
import warnings
|
| 40 |
+
import zlib
|
| 41 |
+
from enum import IntEnum
|
| 42 |
+
from typing import IO, NamedTuple, cast
|
| 43 |
+
|
| 44 |
+
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
|
| 45 |
+
from ._binary import i16be as i16
|
| 46 |
+
from ._binary import i32be as i32
|
| 47 |
+
from ._binary import o8
|
| 48 |
+
from ._binary import o16be as o16
|
| 49 |
+
from ._binary import o32be as o32
|
| 50 |
+
from ._deprecate import deprecate
|
| 51 |
+
from ._util import DeferredError
|
| 52 |
+
|
| 53 |
+
TYPE_CHECKING = False
|
| 54 |
+
if TYPE_CHECKING:
|
| 55 |
+
from collections.abc import Callable
|
| 56 |
+
from typing import Any, NoReturn
|
| 57 |
+
|
| 58 |
+
from . import _imaging
|
| 59 |
+
|
| 60 |
+
logger = logging.getLogger(__name__)
|
| 61 |
+
|
| 62 |
+
is_cid = re.compile(rb"\w\w\w\w").match
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
_MAGIC = b"\211PNG\r\n\032\n"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
_MODES = {
|
| 69 |
+
# supported bits/color combinations, and corresponding modes/rawmodes
|
| 70 |
+
# Grayscale
|
| 71 |
+
(1, 0): ("1", "1"),
|
| 72 |
+
(2, 0): ("L", "L;2"),
|
| 73 |
+
(4, 0): ("L", "L;4"),
|
| 74 |
+
(8, 0): ("L", "L"),
|
| 75 |
+
(16, 0): ("I;16", "I;16B"),
|
| 76 |
+
# Truecolour
|
| 77 |
+
(8, 2): ("RGB", "RGB"),
|
| 78 |
+
(16, 2): ("RGB", "RGB;16B"),
|
| 79 |
+
# Indexed-colour
|
| 80 |
+
(1, 3): ("P", "P;1"),
|
| 81 |
+
(2, 3): ("P", "P;2"),
|
| 82 |
+
(4, 3): ("P", "P;4"),
|
| 83 |
+
(8, 3): ("P", "P"),
|
| 84 |
+
# Grayscale with alpha
|
| 85 |
+
(8, 4): ("LA", "LA"),
|
| 86 |
+
(16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
|
| 87 |
+
# Truecolour with alpha
|
| 88 |
+
(8, 6): ("RGBA", "RGBA"),
|
| 89 |
+
(16, 6): ("RGBA", "RGBA;16B"),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
_simple_palette = re.compile(b"^\xff*\x00\xff*$")
|
| 94 |
+
|
| 95 |
+
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
|
| 96 |
+
"""
|
| 97 |
+
Maximum decompressed size for a iTXt or zTXt chunk.
|
| 98 |
+
Eliminates decompression bombs where compressed chunks can expand 1000x.
|
| 99 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 100 |
+
"""
|
| 101 |
+
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
|
| 102 |
+
"""
|
| 103 |
+
Set the maximum total text chunk size.
|
| 104 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# APNG frame disposal modes
|
| 109 |
+
class Disposal(IntEnum):
|
| 110 |
+
OP_NONE = 0
|
| 111 |
+
"""
|
| 112 |
+
No disposal is done on this frame before rendering the next frame.
|
| 113 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 114 |
+
"""
|
| 115 |
+
OP_BACKGROUND = 1
|
| 116 |
+
"""
|
| 117 |
+
This frame’s modified region is cleared to fully transparent black before rendering
|
| 118 |
+
the next frame.
|
| 119 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 120 |
+
"""
|
| 121 |
+
OP_PREVIOUS = 2
|
| 122 |
+
"""
|
| 123 |
+
This frame’s modified region is reverted to the previous frame’s contents before
|
| 124 |
+
rendering the next frame.
|
| 125 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# APNG frame blend modes
|
| 130 |
+
class Blend(IntEnum):
|
| 131 |
+
OP_SOURCE = 0
|
| 132 |
+
"""
|
| 133 |
+
All color components of this frame, including alpha, overwrite the previous output
|
| 134 |
+
image contents.
|
| 135 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 136 |
+
"""
|
| 137 |
+
OP_OVER = 1
|
| 138 |
+
"""
|
| 139 |
+
This frame should be alpha composited with the previous output image contents.
|
| 140 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _safe_zlib_decompress(s: bytes) -> bytes:
|
| 145 |
+
dobj = zlib.decompressobj()
|
| 146 |
+
plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
|
| 147 |
+
if dobj.unconsumed_tail:
|
| 148 |
+
msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"
|
| 149 |
+
raise ValueError(msg)
|
| 150 |
+
return plaintext
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _crc32(data: bytes, seed: int = 0) -> int:
|
| 154 |
+
return zlib.crc32(data, seed) & 0xFFFFFFFF
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# --------------------------------------------------------------------
|
| 158 |
+
# Support classes. Suitable for PNG and related formats like MNG etc.
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class ChunkStream:
|
| 162 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 163 |
+
self.fp: IO[bytes] | None = fp
|
| 164 |
+
self.queue: list[tuple[bytes, int, int]] | None = []
|
| 165 |
+
|
| 166 |
+
def read(self) -> tuple[bytes, int, int]:
|
| 167 |
+
"""Fetch a new chunk. Returns header information."""
|
| 168 |
+
cid = None
|
| 169 |
+
|
| 170 |
+
assert self.fp is not None
|
| 171 |
+
if self.queue:
|
| 172 |
+
cid, pos, length = self.queue.pop()
|
| 173 |
+
self.fp.seek(pos)
|
| 174 |
+
else:
|
| 175 |
+
s = self.fp.read(8)
|
| 176 |
+
cid = s[4:]
|
| 177 |
+
pos = self.fp.tell()
|
| 178 |
+
length = i32(s)
|
| 179 |
+
|
| 180 |
+
if not is_cid(cid):
|
| 181 |
+
if not ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 182 |
+
msg = f"broken PNG file (chunk {repr(cid)})"
|
| 183 |
+
raise SyntaxError(msg)
|
| 184 |
+
|
| 185 |
+
return cid, pos, length
|
| 186 |
+
|
| 187 |
+
def __enter__(self) -> ChunkStream:
|
| 188 |
+
return self
|
| 189 |
+
|
| 190 |
+
def __exit__(self, *args: object) -> None:
|
| 191 |
+
self.close()
|
| 192 |
+
|
| 193 |
+
def close(self) -> None:
|
| 194 |
+
self.queue = self.fp = None
|
| 195 |
+
|
| 196 |
+
def push(self, cid: bytes, pos: int, length: int) -> None:
|
| 197 |
+
assert self.queue is not None
|
| 198 |
+
self.queue.append((cid, pos, length))
|
| 199 |
+
|
| 200 |
+
def call(self, cid: bytes, pos: int, length: int) -> bytes:
|
| 201 |
+
"""Call the appropriate chunk handler"""
|
| 202 |
+
|
| 203 |
+
logger.debug("STREAM %r %s %s", cid, pos, length)
|
| 204 |
+
return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
|
| 205 |
+
|
| 206 |
+
def crc(self, cid: bytes, data: bytes) -> None:
|
| 207 |
+
"""Read and verify checksum"""
|
| 208 |
+
|
| 209 |
+
# Skip CRC checks for ancillary chunks if allowed to load truncated
|
| 210 |
+
# images
|
| 211 |
+
# 5th byte of first char is 1 [specs, section 5.4]
|
| 212 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
|
| 213 |
+
self.crc_skip(cid, data)
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
assert self.fp is not None
|
| 217 |
+
try:
|
| 218 |
+
crc1 = _crc32(data, _crc32(cid))
|
| 219 |
+
crc2 = i32(self.fp.read(4))
|
| 220 |
+
if crc1 != crc2:
|
| 221 |
+
msg = f"broken PNG file (bad header checksum in {repr(cid)})"
|
| 222 |
+
raise SyntaxError(msg)
|
| 223 |
+
except struct.error as e:
|
| 224 |
+
msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
|
| 225 |
+
raise SyntaxError(msg) from e
|
| 226 |
+
|
| 227 |
+
def crc_skip(self, cid: bytes, data: bytes) -> None:
|
| 228 |
+
"""Read checksum"""
|
| 229 |
+
|
| 230 |
+
assert self.fp is not None
|
| 231 |
+
self.fp.read(4)
|
| 232 |
+
|
| 233 |
+
def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
|
| 234 |
+
# Simple approach; just calculate checksum for all remaining
|
| 235 |
+
# blocks. Must be called directly after open.
|
| 236 |
+
|
| 237 |
+
cids = []
|
| 238 |
+
|
| 239 |
+
assert self.fp is not None
|
| 240 |
+
while True:
|
| 241 |
+
try:
|
| 242 |
+
cid, pos, length = self.read()
|
| 243 |
+
except struct.error as e:
|
| 244 |
+
msg = "truncated PNG file"
|
| 245 |
+
raise OSError(msg) from e
|
| 246 |
+
|
| 247 |
+
if cid == endchunk:
|
| 248 |
+
break
|
| 249 |
+
self.crc(cid, ImageFile._safe_read(self.fp, length))
|
| 250 |
+
cids.append(cid)
|
| 251 |
+
|
| 252 |
+
return cids
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class iTXt(str):
|
| 256 |
+
"""
|
| 257 |
+
Subclass of string to allow iTXt chunks to look like strings while
|
| 258 |
+
keeping their extra information
|
| 259 |
+
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
lang: str | bytes | None
|
| 263 |
+
tkey: str | bytes | None
|
| 264 |
+
|
| 265 |
+
@staticmethod
|
| 266 |
+
def __new__(
|
| 267 |
+
cls, text: str, lang: str | None = None, tkey: str | None = None
|
| 268 |
+
) -> iTXt:
|
| 269 |
+
"""
|
| 270 |
+
:param cls: the class to use when creating the instance
|
| 271 |
+
:param text: value for this key
|
| 272 |
+
:param lang: language code
|
| 273 |
+
:param tkey: UTF-8 version of the key name
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
self = str.__new__(cls, text)
|
| 277 |
+
self.lang = lang
|
| 278 |
+
self.tkey = tkey
|
| 279 |
+
return self
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class PngInfo:
|
| 283 |
+
"""
|
| 284 |
+
PNG chunk container (for use with save(pnginfo=))
|
| 285 |
+
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
def __init__(self) -> None:
|
| 289 |
+
self.chunks: list[tuple[bytes, bytes, bool]] = []
|
| 290 |
+
|
| 291 |
+
def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
|
| 292 |
+
"""Appends an arbitrary chunk. Use with caution.
|
| 293 |
+
|
| 294 |
+
:param cid: a byte string, 4 bytes long.
|
| 295 |
+
:param data: a byte string of the encoded data
|
| 296 |
+
:param after_idat: for use with private chunks. Whether the chunk
|
| 297 |
+
should be written after IDAT
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
self.chunks.append((cid, data, after_idat))
|
| 302 |
+
|
| 303 |
+
def add_itxt(
|
| 304 |
+
self,
|
| 305 |
+
key: str | bytes,
|
| 306 |
+
value: str | bytes,
|
| 307 |
+
lang: str | bytes = "",
|
| 308 |
+
tkey: str | bytes = "",
|
| 309 |
+
zip: bool = False,
|
| 310 |
+
) -> None:
|
| 311 |
+
"""Appends an iTXt chunk.
|
| 312 |
+
|
| 313 |
+
:param key: latin-1 encodable text key name
|
| 314 |
+
:param value: value for this key
|
| 315 |
+
:param lang: language code
|
| 316 |
+
:param tkey: UTF-8 version of the key name
|
| 317 |
+
:param zip: compression flag
|
| 318 |
+
|
| 319 |
+
"""
|
| 320 |
+
|
| 321 |
+
if not isinstance(key, bytes):
|
| 322 |
+
key = key.encode("latin-1", "strict")
|
| 323 |
+
if not isinstance(value, bytes):
|
| 324 |
+
value = value.encode("utf-8", "strict")
|
| 325 |
+
if not isinstance(lang, bytes):
|
| 326 |
+
lang = lang.encode("utf-8", "strict")
|
| 327 |
+
if not isinstance(tkey, bytes):
|
| 328 |
+
tkey = tkey.encode("utf-8", "strict")
|
| 329 |
+
|
| 330 |
+
if zip:
|
| 331 |
+
self.add(
|
| 332 |
+
b"iTXt",
|
| 333 |
+
key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
|
| 334 |
+
)
|
| 335 |
+
else:
|
| 336 |
+
self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
|
| 337 |
+
|
| 338 |
+
def add_text(
|
| 339 |
+
self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
|
| 340 |
+
) -> None:
|
| 341 |
+
"""Appends a text chunk.
|
| 342 |
+
|
| 343 |
+
:param key: latin-1 encodable text key name
|
| 344 |
+
:param value: value for this key, text or an
|
| 345 |
+
:py:class:`PIL.PngImagePlugin.iTXt` instance
|
| 346 |
+
:param zip: compression flag
|
| 347 |
+
|
| 348 |
+
"""
|
| 349 |
+
if isinstance(value, iTXt):
|
| 350 |
+
return self.add_itxt(
|
| 351 |
+
key,
|
| 352 |
+
value,
|
| 353 |
+
value.lang if value.lang is not None else b"",
|
| 354 |
+
value.tkey if value.tkey is not None else b"",
|
| 355 |
+
zip=zip,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# The tEXt chunk stores latin-1 text
|
| 359 |
+
if not isinstance(value, bytes):
|
| 360 |
+
try:
|
| 361 |
+
value = value.encode("latin-1", "strict")
|
| 362 |
+
except UnicodeError:
|
| 363 |
+
return self.add_itxt(key, value, zip=zip)
|
| 364 |
+
|
| 365 |
+
if not isinstance(key, bytes):
|
| 366 |
+
key = key.encode("latin-1", "strict")
|
| 367 |
+
|
| 368 |
+
if zip:
|
| 369 |
+
self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
|
| 370 |
+
else:
|
| 371 |
+
self.add(b"tEXt", key + b"\0" + value)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# --------------------------------------------------------------------
|
| 375 |
+
# PNG image stream (IHDR/IEND)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class _RewindState(NamedTuple):
|
| 379 |
+
info: dict[str | tuple[int, int], Any]
|
| 380 |
+
tile: list[ImageFile._Tile]
|
| 381 |
+
seq_num: int | None
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class PngStream(ChunkStream):
|
| 385 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 386 |
+
super().__init__(fp)
|
| 387 |
+
|
| 388 |
+
# local copies of Image attributes
|
| 389 |
+
self.im_info: dict[str | tuple[int, int], Any] = {}
|
| 390 |
+
self.im_text: dict[str, str | iTXt] = {}
|
| 391 |
+
self.im_size = (0, 0)
|
| 392 |
+
self.im_mode = ""
|
| 393 |
+
self.im_tile: list[ImageFile._Tile] = []
|
| 394 |
+
self.im_palette: tuple[str, bytes] | None = None
|
| 395 |
+
self.im_custom_mimetype: str | None = None
|
| 396 |
+
self.im_n_frames: int | None = None
|
| 397 |
+
self._seq_num: int | None = None
|
| 398 |
+
self.rewind_state = _RewindState({}, [], None)
|
| 399 |
+
|
| 400 |
+
self.text_memory = 0
|
| 401 |
+
|
| 402 |
+
def check_text_memory(self, chunklen: int) -> None:
|
| 403 |
+
self.text_memory += chunklen
|
| 404 |
+
if self.text_memory > MAX_TEXT_MEMORY:
|
| 405 |
+
msg = (
|
| 406 |
+
"Too much memory used in text chunks: "
|
| 407 |
+
f"{self.text_memory}>MAX_TEXT_MEMORY"
|
| 408 |
+
)
|
| 409 |
+
raise ValueError(msg)
|
| 410 |
+
|
| 411 |
+
def save_rewind(self) -> None:
|
| 412 |
+
self.rewind_state = _RewindState(
|
| 413 |
+
self.im_info.copy(),
|
| 414 |
+
self.im_tile,
|
| 415 |
+
self._seq_num,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def rewind(self) -> None:
|
| 419 |
+
self.im_info = self.rewind_state.info.copy()
|
| 420 |
+
self.im_tile = self.rewind_state.tile
|
| 421 |
+
self._seq_num = self.rewind_state.seq_num
|
| 422 |
+
|
| 423 |
+
def chunk_iCCP(self, pos: int, length: int) -> bytes:
|
| 424 |
+
# ICC profile
|
| 425 |
+
assert self.fp is not None
|
| 426 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 427 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 428 |
+
# Profile name 1-79 bytes (character string)
|
| 429 |
+
# Null separator 1 byte (null character)
|
| 430 |
+
# Compression method 1 byte (0)
|
| 431 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 432 |
+
i = s.find(b"\0")
|
| 433 |
+
logger.debug("iCCP profile name %r", s[:i])
|
| 434 |
+
comp_method = s[i + 1]
|
| 435 |
+
logger.debug("Compression method %s", comp_method)
|
| 436 |
+
if comp_method != 0:
|
| 437 |
+
msg = f"Unknown compression method {comp_method} in iCCP chunk"
|
| 438 |
+
raise SyntaxError(msg)
|
| 439 |
+
try:
|
| 440 |
+
icc_profile = _safe_zlib_decompress(s[i + 2 :])
|
| 441 |
+
except ValueError:
|
| 442 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 443 |
+
icc_profile = None
|
| 444 |
+
else:
|
| 445 |
+
raise
|
| 446 |
+
except zlib.error:
|
| 447 |
+
icc_profile = None # FIXME
|
| 448 |
+
self.im_info["icc_profile"] = icc_profile
|
| 449 |
+
return s
|
| 450 |
+
|
| 451 |
+
def chunk_IHDR(self, pos: int, length: int) -> bytes:
|
| 452 |
+
# image header
|
| 453 |
+
assert self.fp is not None
|
| 454 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 455 |
+
if length < 13:
|
| 456 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 457 |
+
return s
|
| 458 |
+
msg = "Truncated IHDR chunk"
|
| 459 |
+
raise ValueError(msg)
|
| 460 |
+
self.im_size = i32(s, 0), i32(s, 4)
|
| 461 |
+
try:
|
| 462 |
+
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
|
| 463 |
+
except Exception:
|
| 464 |
+
pass
|
| 465 |
+
if s[12]:
|
| 466 |
+
self.im_info["interlace"] = 1
|
| 467 |
+
if s[11]:
|
| 468 |
+
msg = "unknown filter category"
|
| 469 |
+
raise SyntaxError(msg)
|
| 470 |
+
return s
|
| 471 |
+
|
| 472 |
+
def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
|
| 473 |
+
# image data
|
| 474 |
+
if "bbox" in self.im_info:
|
| 475 |
+
tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]
|
| 476 |
+
else:
|
| 477 |
+
if self.im_n_frames is not None:
|
| 478 |
+
self.im_info["default_image"] = True
|
| 479 |
+
tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
|
| 480 |
+
self.im_tile = tile
|
| 481 |
+
self.im_idat = length
|
| 482 |
+
msg = "image data found"
|
| 483 |
+
raise EOFError(msg)
|
| 484 |
+
|
| 485 |
+
def chunk_IEND(self, pos: int, length: int) -> NoReturn:
|
| 486 |
+
msg = "end of PNG image"
|
| 487 |
+
raise EOFError(msg)
|
| 488 |
+
|
| 489 |
+
def chunk_PLTE(self, pos: int, length: int) -> bytes:
|
| 490 |
+
# palette
|
| 491 |
+
assert self.fp is not None
|
| 492 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 493 |
+
if self.im_mode == "P":
|
| 494 |
+
self.im_palette = "RGB", s
|
| 495 |
+
return s
|
| 496 |
+
|
| 497 |
+
def chunk_tRNS(self, pos: int, length: int) -> bytes:
|
| 498 |
+
# transparency
|
| 499 |
+
assert self.fp is not None
|
| 500 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 501 |
+
if self.im_mode == "P":
|
| 502 |
+
if _simple_palette.match(s):
|
| 503 |
+
# tRNS contains only one full-transparent entry,
|
| 504 |
+
# other entries are full opaque
|
| 505 |
+
i = s.find(b"\0")
|
| 506 |
+
if i >= 0:
|
| 507 |
+
self.im_info["transparency"] = i
|
| 508 |
+
else:
|
| 509 |
+
# otherwise, we have a byte string with one alpha value
|
| 510 |
+
# for each palette entry
|
| 511 |
+
self.im_info["transparency"] = s
|
| 512 |
+
elif self.im_mode in ("1", "L", "I;16"):
|
| 513 |
+
self.im_info["transparency"] = i16(s)
|
| 514 |
+
elif self.im_mode == "RGB":
|
| 515 |
+
self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
|
| 516 |
+
return s
|
| 517 |
+
|
| 518 |
+
def chunk_gAMA(self, pos: int, length: int) -> bytes:
|
| 519 |
+
# gamma setting
|
| 520 |
+
assert self.fp is not None
|
| 521 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 522 |
+
self.im_info["gamma"] = i32(s) / 100000.0
|
| 523 |
+
return s
|
| 524 |
+
|
| 525 |
+
def chunk_cHRM(self, pos: int, length: int) -> bytes:
|
| 526 |
+
# chromaticity, 8 unsigned ints, actual value is scaled by 100,000
|
| 527 |
+
# WP x,y, Red x,y, Green x,y Blue x,y
|
| 528 |
+
|
| 529 |
+
assert self.fp is not None
|
| 530 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 531 |
+
raw_vals = struct.unpack(f">{len(s) // 4}I", s)
|
| 532 |
+
self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
|
| 533 |
+
return s
|
| 534 |
+
|
| 535 |
+
def chunk_sRGB(self, pos: int, length: int) -> bytes:
|
| 536 |
+
# srgb rendering intent, 1 byte
|
| 537 |
+
# 0 perceptual
|
| 538 |
+
# 1 relative colorimetric
|
| 539 |
+
# 2 saturation
|
| 540 |
+
# 3 absolute colorimetric
|
| 541 |
+
|
| 542 |
+
assert self.fp is not None
|
| 543 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 544 |
+
if length < 1:
|
| 545 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 546 |
+
return s
|
| 547 |
+
msg = "Truncated sRGB chunk"
|
| 548 |
+
raise ValueError(msg)
|
| 549 |
+
self.im_info["srgb"] = s[0]
|
| 550 |
+
return s
|
| 551 |
+
|
| 552 |
+
def chunk_pHYs(self, pos: int, length: int) -> bytes:
|
| 553 |
+
# pixels per unit
|
| 554 |
+
assert self.fp is not None
|
| 555 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 556 |
+
if length < 9:
|
| 557 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 558 |
+
return s
|
| 559 |
+
msg = "Truncated pHYs chunk"
|
| 560 |
+
raise ValueError(msg)
|
| 561 |
+
px, py = i32(s, 0), i32(s, 4)
|
| 562 |
+
unit = s[8]
|
| 563 |
+
if unit == 1: # meter
|
| 564 |
+
dpi = px * 0.0254, py * 0.0254
|
| 565 |
+
self.im_info["dpi"] = dpi
|
| 566 |
+
elif unit == 0:
|
| 567 |
+
self.im_info["aspect"] = px, py
|
| 568 |
+
return s
|
| 569 |
+
|
| 570 |
+
def chunk_tEXt(self, pos: int, length: int) -> bytes:
|
| 571 |
+
# text
|
| 572 |
+
assert self.fp is not None
|
| 573 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 574 |
+
try:
|
| 575 |
+
k, v = s.split(b"\0", 1)
|
| 576 |
+
except ValueError:
|
| 577 |
+
# fallback for broken tEXt tags
|
| 578 |
+
k = s
|
| 579 |
+
v = b""
|
| 580 |
+
if k:
|
| 581 |
+
k_str = k.decode("latin-1", "strict")
|
| 582 |
+
v_str = v.decode("latin-1", "replace")
|
| 583 |
+
|
| 584 |
+
self.im_info[k_str] = v if k == b"exif" else v_str
|
| 585 |
+
self.im_text[k_str] = v_str
|
| 586 |
+
self.check_text_memory(len(v_str))
|
| 587 |
+
|
| 588 |
+
return s
|
| 589 |
+
|
| 590 |
+
def chunk_zTXt(self, pos: int, length: int) -> bytes:
|
| 591 |
+
# compressed text
|
| 592 |
+
assert self.fp is not None
|
| 593 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 594 |
+
try:
|
| 595 |
+
k, v = s.split(b"\0", 1)
|
| 596 |
+
except ValueError:
|
| 597 |
+
k = s
|
| 598 |
+
v = b""
|
| 599 |
+
if v:
|
| 600 |
+
comp_method = v[0]
|
| 601 |
+
else:
|
| 602 |
+
comp_method = 0
|
| 603 |
+
if comp_method != 0:
|
| 604 |
+
msg = f"Unknown compression method {comp_method} in zTXt chunk"
|
| 605 |
+
raise SyntaxError(msg)
|
| 606 |
+
try:
|
| 607 |
+
v = _safe_zlib_decompress(v[1:])
|
| 608 |
+
except ValueError:
|
| 609 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 610 |
+
v = b""
|
| 611 |
+
else:
|
| 612 |
+
raise
|
| 613 |
+
except zlib.error:
|
| 614 |
+
v = b""
|
| 615 |
+
|
| 616 |
+
if k:
|
| 617 |
+
k_str = k.decode("latin-1", "strict")
|
| 618 |
+
v_str = v.decode("latin-1", "replace")
|
| 619 |
+
|
| 620 |
+
self.im_info[k_str] = self.im_text[k_str] = v_str
|
| 621 |
+
self.check_text_memory(len(v_str))
|
| 622 |
+
|
| 623 |
+
return s
|
| 624 |
+
|
| 625 |
+
def chunk_iTXt(self, pos: int, length: int) -> bytes:
|
| 626 |
+
# international text
|
| 627 |
+
assert self.fp is not None
|
| 628 |
+
r = s = ImageFile._safe_read(self.fp, length)
|
| 629 |
+
try:
|
| 630 |
+
k, r = r.split(b"\0", 1)
|
| 631 |
+
except ValueError:
|
| 632 |
+
return s
|
| 633 |
+
if len(r) < 2:
|
| 634 |
+
return s
|
| 635 |
+
cf, cm, r = r[0], r[1], r[2:]
|
| 636 |
+
try:
|
| 637 |
+
lang, tk, v = r.split(b"\0", 2)
|
| 638 |
+
except ValueError:
|
| 639 |
+
return s
|
| 640 |
+
if cf != 0:
|
| 641 |
+
if cm == 0:
|
| 642 |
+
try:
|
| 643 |
+
v = _safe_zlib_decompress(v)
|
| 644 |
+
except ValueError:
|
| 645 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 646 |
+
return s
|
| 647 |
+
else:
|
| 648 |
+
raise
|
| 649 |
+
except zlib.error:
|
| 650 |
+
return s
|
| 651 |
+
else:
|
| 652 |
+
return s
|
| 653 |
+
if k == b"XML:com.adobe.xmp":
|
| 654 |
+
self.im_info["xmp"] = v
|
| 655 |
+
try:
|
| 656 |
+
k_str = k.decode("latin-1", "strict")
|
| 657 |
+
lang_str = lang.decode("utf-8", "strict")
|
| 658 |
+
tk_str = tk.decode("utf-8", "strict")
|
| 659 |
+
v_str = v.decode("utf-8", "strict")
|
| 660 |
+
except UnicodeError:
|
| 661 |
+
return s
|
| 662 |
+
|
| 663 |
+
self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)
|
| 664 |
+
self.check_text_memory(len(v_str))
|
| 665 |
+
|
| 666 |
+
return s
|
| 667 |
+
|
| 668 |
+
def chunk_eXIf(self, pos: int, length: int) -> bytes:
|
| 669 |
+
assert self.fp is not None
|
| 670 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 671 |
+
self.im_info["exif"] = b"Exif\x00\x00" + s
|
| 672 |
+
return s
|
| 673 |
+
|
| 674 |
+
# APNG chunks
|
| 675 |
+
def chunk_acTL(self, pos: int, length: int) -> bytes:
|
| 676 |
+
assert self.fp is not None
|
| 677 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 678 |
+
if length < 8:
|
| 679 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 680 |
+
return s
|
| 681 |
+
msg = "APNG contains truncated acTL chunk"
|
| 682 |
+
raise ValueError(msg)
|
| 683 |
+
if self.im_n_frames is not None:
|
| 684 |
+
self.im_n_frames = None
|
| 685 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 686 |
+
return s
|
| 687 |
+
n_frames = i32(s)
|
| 688 |
+
if n_frames == 0 or n_frames > 0x80000000:
|
| 689 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 690 |
+
return s
|
| 691 |
+
self.im_n_frames = n_frames
|
| 692 |
+
self.im_info["loop"] = i32(s, 4)
|
| 693 |
+
self.im_custom_mimetype = "image/apng"
|
| 694 |
+
return s
|
| 695 |
+
|
| 696 |
+
def chunk_fcTL(self, pos: int, length: int) -> bytes:
|
| 697 |
+
assert self.fp is not None
|
| 698 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 699 |
+
if length < 26:
|
| 700 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 701 |
+
return s
|
| 702 |
+
msg = "APNG contains truncated fcTL chunk"
|
| 703 |
+
raise ValueError(msg)
|
| 704 |
+
seq = i32(s)
|
| 705 |
+
if (self._seq_num is None and seq != 0) or (
|
| 706 |
+
self._seq_num is not None and self._seq_num != seq - 1
|
| 707 |
+
):
|
| 708 |
+
msg = "APNG contains frame sequence errors"
|
| 709 |
+
raise SyntaxError(msg)
|
| 710 |
+
self._seq_num = seq
|
| 711 |
+
width, height = i32(s, 4), i32(s, 8)
|
| 712 |
+
px, py = i32(s, 12), i32(s, 16)
|
| 713 |
+
im_w, im_h = self.im_size
|
| 714 |
+
if px + width > im_w or py + height > im_h:
|
| 715 |
+
msg = "APNG contains invalid frames"
|
| 716 |
+
raise SyntaxError(msg)
|
| 717 |
+
self.im_info["bbox"] = (px, py, px + width, py + height)
|
| 718 |
+
delay_num, delay_den = i16(s, 20), i16(s, 22)
|
| 719 |
+
if delay_den == 0:
|
| 720 |
+
delay_den = 100
|
| 721 |
+
self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
|
| 722 |
+
self.im_info["disposal"] = s[24]
|
| 723 |
+
self.im_info["blend"] = s[25]
|
| 724 |
+
return s
|
| 725 |
+
|
| 726 |
+
def chunk_fdAT(self, pos: int, length: int) -> bytes:
|
| 727 |
+
assert self.fp is not None
|
| 728 |
+
if length < 4:
|
| 729 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 730 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 731 |
+
return s
|
| 732 |
+
msg = "APNG contains truncated fDAT chunk"
|
| 733 |
+
raise ValueError(msg)
|
| 734 |
+
s = ImageFile._safe_read(self.fp, 4)
|
| 735 |
+
seq = i32(s)
|
| 736 |
+
if self._seq_num != seq - 1:
|
| 737 |
+
msg = "APNG contains frame sequence errors"
|
| 738 |
+
raise SyntaxError(msg)
|
| 739 |
+
self._seq_num = seq
|
| 740 |
+
return self.chunk_IDAT(pos + 4, length - 4)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
# --------------------------------------------------------------------
|
| 744 |
+
# PNG reader
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _accept(prefix: bytes) -> bool:
|
| 748 |
+
return prefix.startswith(_MAGIC)
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
##
|
| 752 |
+
# Image plugin for PNG images.
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
class PngImageFile(ImageFile.ImageFile):
|
| 756 |
+
format = "PNG"
|
| 757 |
+
format_description = "Portable network graphics"
|
| 758 |
+
|
| 759 |
+
def _open(self) -> None:
|
| 760 |
+
if not _accept(self.fp.read(8)):
|
| 761 |
+
msg = "not a PNG file"
|
| 762 |
+
raise SyntaxError(msg)
|
| 763 |
+
self._fp = self.fp
|
| 764 |
+
self.__frame = 0
|
| 765 |
+
|
| 766 |
+
#
|
| 767 |
+
# Parse headers up to the first IDAT or fDAT chunk
|
| 768 |
+
|
| 769 |
+
self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
|
| 770 |
+
self.png: PngStream | None = PngStream(self.fp)
|
| 771 |
+
|
| 772 |
+
while True:
|
| 773 |
+
#
|
| 774 |
+
# get next chunk
|
| 775 |
+
|
| 776 |
+
cid, pos, length = self.png.read()
|
| 777 |
+
|
| 778 |
+
try:
|
| 779 |
+
s = self.png.call(cid, pos, length)
|
| 780 |
+
except EOFError:
|
| 781 |
+
break
|
| 782 |
+
except AttributeError:
|
| 783 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 784 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 785 |
+
if cid[1:2].islower():
|
| 786 |
+
self.private_chunks.append((cid, s))
|
| 787 |
+
|
| 788 |
+
self.png.crc(cid, s)
|
| 789 |
+
|
| 790 |
+
#
|
| 791 |
+
# Copy relevant attributes from the PngStream. An alternative
|
| 792 |
+
# would be to let the PngStream class modify these attributes
|
| 793 |
+
# directly, but that introduces circular references which are
|
| 794 |
+
# difficult to break if things go wrong in the decoder...
|
| 795 |
+
# (believe me, I've tried ;-)
|
| 796 |
+
|
| 797 |
+
self._mode = self.png.im_mode
|
| 798 |
+
self._size = self.png.im_size
|
| 799 |
+
self.info = self.png.im_info
|
| 800 |
+
self._text: dict[str, str | iTXt] | None = None
|
| 801 |
+
self.tile = self.png.im_tile
|
| 802 |
+
self.custom_mimetype = self.png.im_custom_mimetype
|
| 803 |
+
self.n_frames = self.png.im_n_frames or 1
|
| 804 |
+
self.default_image = self.info.get("default_image", False)
|
| 805 |
+
|
| 806 |
+
if self.png.im_palette:
|
| 807 |
+
rawmode, data = self.png.im_palette
|
| 808 |
+
self.palette = ImagePalette.raw(rawmode, data)
|
| 809 |
+
|
| 810 |
+
if cid == b"fdAT":
|
| 811 |
+
self.__prepare_idat = length - 4
|
| 812 |
+
else:
|
| 813 |
+
self.__prepare_idat = length # used by load_prepare()
|
| 814 |
+
|
| 815 |
+
if self.png.im_n_frames is not None:
|
| 816 |
+
self._close_exclusive_fp_after_loading = False
|
| 817 |
+
self.png.save_rewind()
|
| 818 |
+
self.__rewind_idat = self.__prepare_idat
|
| 819 |
+
self.__rewind = self._fp.tell()
|
| 820 |
+
if self.default_image:
|
| 821 |
+
# IDAT chunk contains default image and not first animation frame
|
| 822 |
+
self.n_frames += 1
|
| 823 |
+
self._seek(0)
|
| 824 |
+
self.is_animated = self.n_frames > 1
|
| 825 |
+
|
| 826 |
+
@property
|
| 827 |
+
def text(self) -> dict[str, str | iTXt]:
|
| 828 |
+
# experimental
|
| 829 |
+
if self._text is None:
|
| 830 |
+
# iTxt, tEXt and zTXt chunks may appear at the end of the file
|
| 831 |
+
# So load the file to ensure that they are read
|
| 832 |
+
if self.is_animated:
|
| 833 |
+
frame = self.__frame
|
| 834 |
+
# for APNG, seek to the final frame before loading
|
| 835 |
+
self.seek(self.n_frames - 1)
|
| 836 |
+
self.load()
|
| 837 |
+
if self.is_animated:
|
| 838 |
+
self.seek(frame)
|
| 839 |
+
assert self._text is not None
|
| 840 |
+
return self._text
|
| 841 |
+
|
| 842 |
+
def verify(self) -> None:
|
| 843 |
+
"""Verify PNG file"""
|
| 844 |
+
|
| 845 |
+
if self.fp is None:
|
| 846 |
+
msg = "verify must be called directly after open"
|
| 847 |
+
raise RuntimeError(msg)
|
| 848 |
+
|
| 849 |
+
# back up to beginning of IDAT block
|
| 850 |
+
self.fp.seek(self.tile[0][2] - 8)
|
| 851 |
+
|
| 852 |
+
assert self.png is not None
|
| 853 |
+
self.png.verify()
|
| 854 |
+
self.png.close()
|
| 855 |
+
|
| 856 |
+
if self._exclusive_fp:
|
| 857 |
+
self.fp.close()
|
| 858 |
+
self.fp = None
|
| 859 |
+
|
| 860 |
+
def seek(self, frame: int) -> None:
|
| 861 |
+
if not self._seek_check(frame):
|
| 862 |
+
return
|
| 863 |
+
if frame < self.__frame:
|
| 864 |
+
self._seek(0, True)
|
| 865 |
+
|
| 866 |
+
last_frame = self.__frame
|
| 867 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 868 |
+
try:
|
| 869 |
+
self._seek(f)
|
| 870 |
+
except EOFError as e:
|
| 871 |
+
self.seek(last_frame)
|
| 872 |
+
msg = "no more images in APNG file"
|
| 873 |
+
raise EOFError(msg) from e
|
| 874 |
+
|
| 875 |
+
def _seek(self, frame: int, rewind: bool = False) -> None:
|
| 876 |
+
assert self.png is not None
|
| 877 |
+
if isinstance(self._fp, DeferredError):
|
| 878 |
+
raise self._fp.ex
|
| 879 |
+
|
| 880 |
+
self.dispose: _imaging.ImagingCore | None
|
| 881 |
+
dispose_extent = None
|
| 882 |
+
if frame == 0:
|
| 883 |
+
if rewind:
|
| 884 |
+
self._fp.seek(self.__rewind)
|
| 885 |
+
self.png.rewind()
|
| 886 |
+
self.__prepare_idat = self.__rewind_idat
|
| 887 |
+
self._im = None
|
| 888 |
+
self.info = self.png.im_info
|
| 889 |
+
self.tile = self.png.im_tile
|
| 890 |
+
self.fp = self._fp
|
| 891 |
+
self._prev_im = None
|
| 892 |
+
self.dispose = None
|
| 893 |
+
self.default_image = self.info.get("default_image", False)
|
| 894 |
+
self.dispose_op = self.info.get("disposal")
|
| 895 |
+
self.blend_op = self.info.get("blend")
|
| 896 |
+
dispose_extent = self.info.get("bbox")
|
| 897 |
+
self.__frame = 0
|
| 898 |
+
else:
|
| 899 |
+
if frame != self.__frame + 1:
|
| 900 |
+
msg = f"cannot seek to frame {frame}"
|
| 901 |
+
raise ValueError(msg)
|
| 902 |
+
|
| 903 |
+
# ensure previous frame was loaded
|
| 904 |
+
self.load()
|
| 905 |
+
|
| 906 |
+
if self.dispose:
|
| 907 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
| 908 |
+
self._prev_im = self.im.copy()
|
| 909 |
+
|
| 910 |
+
self.fp = self._fp
|
| 911 |
+
|
| 912 |
+
# advance to the next frame
|
| 913 |
+
if self.__prepare_idat:
|
| 914 |
+
ImageFile._safe_read(self.fp, self.__prepare_idat)
|
| 915 |
+
self.__prepare_idat = 0
|
| 916 |
+
frame_start = False
|
| 917 |
+
while True:
|
| 918 |
+
self.fp.read(4) # CRC
|
| 919 |
+
|
| 920 |
+
try:
|
| 921 |
+
cid, pos, length = self.png.read()
|
| 922 |
+
except (struct.error, SyntaxError):
|
| 923 |
+
break
|
| 924 |
+
|
| 925 |
+
if cid == b"IEND":
|
| 926 |
+
msg = "No more images in APNG file"
|
| 927 |
+
raise EOFError(msg)
|
| 928 |
+
if cid == b"fcTL":
|
| 929 |
+
if frame_start:
|
| 930 |
+
# there must be at least one fdAT chunk between fcTL chunks
|
| 931 |
+
msg = "APNG missing frame data"
|
| 932 |
+
raise SyntaxError(msg)
|
| 933 |
+
frame_start = True
|
| 934 |
+
|
| 935 |
+
try:
|
| 936 |
+
self.png.call(cid, pos, length)
|
| 937 |
+
except UnicodeDecodeError:
|
| 938 |
+
break
|
| 939 |
+
except EOFError:
|
| 940 |
+
if cid == b"fdAT":
|
| 941 |
+
length -= 4
|
| 942 |
+
if frame_start:
|
| 943 |
+
self.__prepare_idat = length
|
| 944 |
+
break
|
| 945 |
+
ImageFile._safe_read(self.fp, length)
|
| 946 |
+
except AttributeError:
|
| 947 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 948 |
+
ImageFile._safe_read(self.fp, length)
|
| 949 |
+
|
| 950 |
+
self.__frame = frame
|
| 951 |
+
self.tile = self.png.im_tile
|
| 952 |
+
self.dispose_op = self.info.get("disposal")
|
| 953 |
+
self.blend_op = self.info.get("blend")
|
| 954 |
+
dispose_extent = self.info.get("bbox")
|
| 955 |
+
|
| 956 |
+
if not self.tile:
|
| 957 |
+
msg = "image not found in APNG frame"
|
| 958 |
+
raise EOFError(msg)
|
| 959 |
+
if dispose_extent:
|
| 960 |
+
self.dispose_extent: tuple[float, float, float, float] = dispose_extent
|
| 961 |
+
|
| 962 |
+
# setup frame disposal (actual disposal done when needed in the next _seek())
|
| 963 |
+
if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
|
| 964 |
+
self.dispose_op = Disposal.OP_BACKGROUND
|
| 965 |
+
|
| 966 |
+
self.dispose = None
|
| 967 |
+
if self.dispose_op == Disposal.OP_PREVIOUS:
|
| 968 |
+
if self._prev_im:
|
| 969 |
+
self.dispose = self._prev_im.copy()
|
| 970 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 971 |
+
elif self.dispose_op == Disposal.OP_BACKGROUND:
|
| 972 |
+
self.dispose = Image.core.fill(self.mode, self.size)
|
| 973 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 974 |
+
|
| 975 |
+
def tell(self) -> int:
|
| 976 |
+
return self.__frame
|
| 977 |
+
|
| 978 |
+
def load_prepare(self) -> None:
|
| 979 |
+
"""internal: prepare to read PNG file"""
|
| 980 |
+
|
| 981 |
+
if self.info.get("interlace"):
|
| 982 |
+
self.decoderconfig = self.decoderconfig + (1,)
|
| 983 |
+
|
| 984 |
+
self.__idat = self.__prepare_idat # used by load_read()
|
| 985 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 986 |
+
|
| 987 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 988 |
+
"""internal: read more image data"""
|
| 989 |
+
|
| 990 |
+
assert self.png is not None
|
| 991 |
+
while self.__idat == 0:
|
| 992 |
+
# end of chunk, skip forward to next one
|
| 993 |
+
|
| 994 |
+
self.fp.read(4) # CRC
|
| 995 |
+
|
| 996 |
+
cid, pos, length = self.png.read()
|
| 997 |
+
|
| 998 |
+
if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
|
| 999 |
+
self.png.push(cid, pos, length)
|
| 1000 |
+
return b""
|
| 1001 |
+
|
| 1002 |
+
if cid == b"fdAT":
|
| 1003 |
+
try:
|
| 1004 |
+
self.png.call(cid, pos, length)
|
| 1005 |
+
except EOFError:
|
| 1006 |
+
pass
|
| 1007 |
+
self.__idat = length - 4 # sequence_num has already been read
|
| 1008 |
+
else:
|
| 1009 |
+
self.__idat = length # empty chunks are allowed
|
| 1010 |
+
|
| 1011 |
+
# read more data from this chunk
|
| 1012 |
+
if read_bytes <= 0:
|
| 1013 |
+
read_bytes = self.__idat
|
| 1014 |
+
else:
|
| 1015 |
+
read_bytes = min(read_bytes, self.__idat)
|
| 1016 |
+
|
| 1017 |
+
self.__idat = self.__idat - read_bytes
|
| 1018 |
+
|
| 1019 |
+
return self.fp.read(read_bytes)
|
| 1020 |
+
|
| 1021 |
+
def load_end(self) -> None:
|
| 1022 |
+
"""internal: finished reading image data"""
|
| 1023 |
+
assert self.png is not None
|
| 1024 |
+
if self.__idat != 0:
|
| 1025 |
+
self.fp.read(self.__idat)
|
| 1026 |
+
while True:
|
| 1027 |
+
self.fp.read(4) # CRC
|
| 1028 |
+
|
| 1029 |
+
try:
|
| 1030 |
+
cid, pos, length = self.png.read()
|
| 1031 |
+
except (struct.error, SyntaxError):
|
| 1032 |
+
break
|
| 1033 |
+
|
| 1034 |
+
if cid == b"IEND":
|
| 1035 |
+
break
|
| 1036 |
+
elif cid == b"fcTL" and self.is_animated:
|
| 1037 |
+
# start of the next frame, stop reading
|
| 1038 |
+
self.__prepare_idat = 0
|
| 1039 |
+
self.png.push(cid, pos, length)
|
| 1040 |
+
break
|
| 1041 |
+
|
| 1042 |
+
try:
|
| 1043 |
+
self.png.call(cid, pos, length)
|
| 1044 |
+
except UnicodeDecodeError:
|
| 1045 |
+
break
|
| 1046 |
+
except EOFError:
|
| 1047 |
+
if cid == b"fdAT":
|
| 1048 |
+
length -= 4
|
| 1049 |
+
try:
|
| 1050 |
+
ImageFile._safe_read(self.fp, length)
|
| 1051 |
+
except OSError as e:
|
| 1052 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 1053 |
+
break
|
| 1054 |
+
else:
|
| 1055 |
+
raise e
|
| 1056 |
+
except AttributeError:
|
| 1057 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 1058 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 1059 |
+
if cid[1:2].islower():
|
| 1060 |
+
self.private_chunks.append((cid, s, True))
|
| 1061 |
+
self._text = self.png.im_text
|
| 1062 |
+
if not self.is_animated:
|
| 1063 |
+
self.png.close()
|
| 1064 |
+
self.png = None
|
| 1065 |
+
else:
|
| 1066 |
+
if self._prev_im and self.blend_op == Blend.OP_OVER:
|
| 1067 |
+
updated = self._crop(self.im, self.dispose_extent)
|
| 1068 |
+
if self.im.mode == "RGB" and "transparency" in self.info:
|
| 1069 |
+
mask = updated.convert_transparent(
|
| 1070 |
+
"RGBA", self.info["transparency"]
|
| 1071 |
+
)
|
| 1072 |
+
else:
|
| 1073 |
+
if self.im.mode == "P" and "transparency" in self.info:
|
| 1074 |
+
t = self.info["transparency"]
|
| 1075 |
+
if isinstance(t, bytes):
|
| 1076 |
+
updated.putpalettealphas(t)
|
| 1077 |
+
elif isinstance(t, int):
|
| 1078 |
+
updated.putpalettealpha(t)
|
| 1079 |
+
mask = updated.convert("RGBA")
|
| 1080 |
+
self._prev_im.paste(updated, self.dispose_extent, mask)
|
| 1081 |
+
self.im = self._prev_im
|
| 1082 |
+
|
| 1083 |
+
def _getexif(self) -> dict[int, Any] | None:
|
| 1084 |
+
if "exif" not in self.info:
|
| 1085 |
+
self.load()
|
| 1086 |
+
if "exif" not in self.info and "Raw profile type exif" not in self.info:
|
| 1087 |
+
return None
|
| 1088 |
+
return self.getexif()._get_merged_dict()
|
| 1089 |
+
|
| 1090 |
+
def getexif(self) -> Image.Exif:
|
| 1091 |
+
if "exif" not in self.info:
|
| 1092 |
+
self.load()
|
| 1093 |
+
|
| 1094 |
+
return super().getexif()
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
# --------------------------------------------------------------------
|
| 1098 |
+
# PNG writer
|
| 1099 |
+
|
| 1100 |
+
_OUTMODES = {
|
| 1101 |
+
# supported PIL modes, and corresponding rawmode, bit depth and color type
|
| 1102 |
+
"1": ("1", b"\x01", b"\x00"),
|
| 1103 |
+
"L;1": ("L;1", b"\x01", b"\x00"),
|
| 1104 |
+
"L;2": ("L;2", b"\x02", b"\x00"),
|
| 1105 |
+
"L;4": ("L;4", b"\x04", b"\x00"),
|
| 1106 |
+
"L": ("L", b"\x08", b"\x00"),
|
| 1107 |
+
"LA": ("LA", b"\x08", b"\x04"),
|
| 1108 |
+
"I": ("I;16B", b"\x10", b"\x00"),
|
| 1109 |
+
"I;16": ("I;16B", b"\x10", b"\x00"),
|
| 1110 |
+
"I;16B": ("I;16B", b"\x10", b"\x00"),
|
| 1111 |
+
"P;1": ("P;1", b"\x01", b"\x03"),
|
| 1112 |
+
"P;2": ("P;2", b"\x02", b"\x03"),
|
| 1113 |
+
"P;4": ("P;4", b"\x04", b"\x03"),
|
| 1114 |
+
"P": ("P", b"\x08", b"\x03"),
|
| 1115 |
+
"RGB": ("RGB", b"\x08", b"\x02"),
|
| 1116 |
+
"RGBA": ("RGBA", b"\x08", b"\x06"),
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
|
| 1120 |
+
def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
|
| 1121 |
+
"""Write a PNG chunk (including CRC field)"""
|
| 1122 |
+
|
| 1123 |
+
byte_data = b"".join(data)
|
| 1124 |
+
|
| 1125 |
+
fp.write(o32(len(byte_data)) + cid)
|
| 1126 |
+
fp.write(byte_data)
|
| 1127 |
+
crc = _crc32(byte_data, _crc32(cid))
|
| 1128 |
+
fp.write(o32(crc))
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
class _idat:
|
| 1132 |
+
# wrap output from the encoder in IDAT chunks
|
| 1133 |
+
|
| 1134 |
+
def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:
|
| 1135 |
+
self.fp = fp
|
| 1136 |
+
self.chunk = chunk
|
| 1137 |
+
|
| 1138 |
+
def write(self, data: bytes) -> None:
|
| 1139 |
+
self.chunk(self.fp, b"IDAT", data)
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
class _fdat:
|
| 1143 |
+
# wrap encoder output in fdAT chunks
|
| 1144 |
+
|
| 1145 |
+
def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:
|
| 1146 |
+
self.fp = fp
|
| 1147 |
+
self.chunk = chunk
|
| 1148 |
+
self.seq_num = seq_num
|
| 1149 |
+
|
| 1150 |
+
def write(self, data: bytes) -> None:
|
| 1151 |
+
self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
|
| 1152 |
+
self.seq_num += 1
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
class _Frame(NamedTuple):
|
| 1156 |
+
im: Image.Image
|
| 1157 |
+
bbox: tuple[int, int, int, int] | None
|
| 1158 |
+
encoderinfo: dict[str, Any]
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
def _write_multiple_frames(
|
| 1162 |
+
im: Image.Image,
|
| 1163 |
+
fp: IO[bytes],
|
| 1164 |
+
chunk: Callable[..., None],
|
| 1165 |
+
mode: str,
|
| 1166 |
+
rawmode: str,
|
| 1167 |
+
default_image: Image.Image | None,
|
| 1168 |
+
append_images: list[Image.Image],
|
| 1169 |
+
) -> Image.Image | None:
|
| 1170 |
+
duration = im.encoderinfo.get("duration")
|
| 1171 |
+
loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
|
| 1172 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
|
| 1173 |
+
blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
|
| 1174 |
+
|
| 1175 |
+
if default_image:
|
| 1176 |
+
chain = itertools.chain(append_images)
|
| 1177 |
+
else:
|
| 1178 |
+
chain = itertools.chain([im], append_images)
|
| 1179 |
+
|
| 1180 |
+
im_frames: list[_Frame] = []
|
| 1181 |
+
frame_count = 0
|
| 1182 |
+
for im_seq in chain:
|
| 1183 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1184 |
+
if im_frame.mode == mode:
|
| 1185 |
+
im_frame = im_frame.copy()
|
| 1186 |
+
else:
|
| 1187 |
+
im_frame = im_frame.convert(mode)
|
| 1188 |
+
encoderinfo = im.encoderinfo.copy()
|
| 1189 |
+
if isinstance(duration, (list, tuple)):
|
| 1190 |
+
encoderinfo["duration"] = duration[frame_count]
|
| 1191 |
+
elif duration is None and "duration" in im_frame.info:
|
| 1192 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
| 1193 |
+
if isinstance(disposal, (list, tuple)):
|
| 1194 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
| 1195 |
+
if isinstance(blend, (list, tuple)):
|
| 1196 |
+
encoderinfo["blend"] = blend[frame_count]
|
| 1197 |
+
frame_count += 1
|
| 1198 |
+
|
| 1199 |
+
if im_frames:
|
| 1200 |
+
previous = im_frames[-1]
|
| 1201 |
+
prev_disposal = previous.encoderinfo.get("disposal")
|
| 1202 |
+
prev_blend = previous.encoderinfo.get("blend")
|
| 1203 |
+
if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
|
| 1204 |
+
prev_disposal = Disposal.OP_BACKGROUND
|
| 1205 |
+
|
| 1206 |
+
if prev_disposal == Disposal.OP_BACKGROUND:
|
| 1207 |
+
base_im = previous.im.copy()
|
| 1208 |
+
dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
|
| 1209 |
+
bbox = previous.bbox
|
| 1210 |
+
if bbox:
|
| 1211 |
+
dispose = dispose.crop(bbox)
|
| 1212 |
+
else:
|
| 1213 |
+
bbox = (0, 0) + im.size
|
| 1214 |
+
base_im.paste(dispose, bbox)
|
| 1215 |
+
elif prev_disposal == Disposal.OP_PREVIOUS:
|
| 1216 |
+
base_im = im_frames[-2].im
|
| 1217 |
+
else:
|
| 1218 |
+
base_im = previous.im
|
| 1219 |
+
delta = ImageChops.subtract_modulo(
|
| 1220 |
+
im_frame.convert("RGBA"), base_im.convert("RGBA")
|
| 1221 |
+
)
|
| 1222 |
+
bbox = delta.getbbox(alpha_only=False)
|
| 1223 |
+
if (
|
| 1224 |
+
not bbox
|
| 1225 |
+
and prev_disposal == encoderinfo.get("disposal")
|
| 1226 |
+
and prev_blend == encoderinfo.get("blend")
|
| 1227 |
+
and "duration" in encoderinfo
|
| 1228 |
+
):
|
| 1229 |
+
previous.encoderinfo["duration"] += encoderinfo["duration"]
|
| 1230 |
+
continue
|
| 1231 |
+
else:
|
| 1232 |
+
bbox = None
|
| 1233 |
+
im_frames.append(_Frame(im_frame, bbox, encoderinfo))
|
| 1234 |
+
|
| 1235 |
+
if len(im_frames) == 1 and not default_image:
|
| 1236 |
+
return im_frames[0].im
|
| 1237 |
+
|
| 1238 |
+
# animation control
|
| 1239 |
+
chunk(
|
| 1240 |
+
fp,
|
| 1241 |
+
b"acTL",
|
| 1242 |
+
o32(len(im_frames)), # 0: num_frames
|
| 1243 |
+
o32(loop), # 4: num_plays
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
# default image IDAT (if it exists)
|
| 1247 |
+
if default_image:
|
| 1248 |
+
if im.mode != mode:
|
| 1249 |
+
im = im.convert(mode)
|
| 1250 |
+
ImageFile._save(
|
| 1251 |
+
im,
|
| 1252 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1253 |
+
[ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
|
| 1254 |
+
)
|
| 1255 |
+
|
| 1256 |
+
seq_num = 0
|
| 1257 |
+
for frame, frame_data in enumerate(im_frames):
|
| 1258 |
+
im_frame = frame_data.im
|
| 1259 |
+
if not frame_data.bbox:
|
| 1260 |
+
bbox = (0, 0) + im_frame.size
|
| 1261 |
+
else:
|
| 1262 |
+
bbox = frame_data.bbox
|
| 1263 |
+
im_frame = im_frame.crop(bbox)
|
| 1264 |
+
size = im_frame.size
|
| 1265 |
+
encoderinfo = frame_data.encoderinfo
|
| 1266 |
+
frame_duration = int(round(encoderinfo.get("duration", 0)))
|
| 1267 |
+
frame_disposal = encoderinfo.get("disposal", disposal)
|
| 1268 |
+
frame_blend = encoderinfo.get("blend", blend)
|
| 1269 |
+
# frame control
|
| 1270 |
+
chunk(
|
| 1271 |
+
fp,
|
| 1272 |
+
b"fcTL",
|
| 1273 |
+
o32(seq_num), # sequence_number
|
| 1274 |
+
o32(size[0]), # width
|
| 1275 |
+
o32(size[1]), # height
|
| 1276 |
+
o32(bbox[0]), # x_offset
|
| 1277 |
+
o32(bbox[1]), # y_offset
|
| 1278 |
+
o16(frame_duration), # delay_numerator
|
| 1279 |
+
o16(1000), # delay_denominator
|
| 1280 |
+
o8(frame_disposal), # dispose_op
|
| 1281 |
+
o8(frame_blend), # blend_op
|
| 1282 |
+
)
|
| 1283 |
+
seq_num += 1
|
| 1284 |
+
# frame data
|
| 1285 |
+
if frame == 0 and not default_image:
|
| 1286 |
+
# first frame must be in IDAT chunks for backwards compatibility
|
| 1287 |
+
ImageFile._save(
|
| 1288 |
+
im_frame,
|
| 1289 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1290 |
+
[ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1291 |
+
)
|
| 1292 |
+
else:
|
| 1293 |
+
fdat_chunks = _fdat(fp, chunk, seq_num)
|
| 1294 |
+
ImageFile._save(
|
| 1295 |
+
im_frame,
|
| 1296 |
+
cast(IO[bytes], fdat_chunks),
|
| 1297 |
+
[ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1298 |
+
)
|
| 1299 |
+
seq_num = fdat_chunks.seq_num
|
| 1300 |
+
return None
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 1304 |
+
_save(im, fp, filename, save_all=True)
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
def _save(
|
| 1308 |
+
im: Image.Image,
|
| 1309 |
+
fp: IO[bytes],
|
| 1310 |
+
filename: str | bytes,
|
| 1311 |
+
chunk: Callable[..., None] = putchunk,
|
| 1312 |
+
save_all: bool = False,
|
| 1313 |
+
) -> None:
|
| 1314 |
+
# save an image to disk (called by the save method)
|
| 1315 |
+
|
| 1316 |
+
if save_all:
|
| 1317 |
+
default_image = im.encoderinfo.get(
|
| 1318 |
+
"default_image", im.info.get("default_image")
|
| 1319 |
+
)
|
| 1320 |
+
modes = set()
|
| 1321 |
+
sizes = set()
|
| 1322 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 1323 |
+
for im_seq in itertools.chain([im], append_images):
|
| 1324 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1325 |
+
modes.add(im_frame.mode)
|
| 1326 |
+
sizes.add(im_frame.size)
|
| 1327 |
+
for mode in ("RGBA", "RGB", "P"):
|
| 1328 |
+
if mode in modes:
|
| 1329 |
+
break
|
| 1330 |
+
else:
|
| 1331 |
+
mode = modes.pop()
|
| 1332 |
+
size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
|
| 1333 |
+
else:
|
| 1334 |
+
size = im.size
|
| 1335 |
+
mode = im.mode
|
| 1336 |
+
|
| 1337 |
+
outmode = mode
|
| 1338 |
+
if mode == "P":
|
| 1339 |
+
#
|
| 1340 |
+
# attempt to minimize storage requirements for palette images
|
| 1341 |
+
if "bits" in im.encoderinfo:
|
| 1342 |
+
# number of bits specified by user
|
| 1343 |
+
colors = min(1 << im.encoderinfo["bits"], 256)
|
| 1344 |
+
else:
|
| 1345 |
+
# check palette contents
|
| 1346 |
+
if im.palette:
|
| 1347 |
+
colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
|
| 1348 |
+
else:
|
| 1349 |
+
colors = 256
|
| 1350 |
+
|
| 1351 |
+
if colors <= 16:
|
| 1352 |
+
if colors <= 2:
|
| 1353 |
+
bits = 1
|
| 1354 |
+
elif colors <= 4:
|
| 1355 |
+
bits = 2
|
| 1356 |
+
else:
|
| 1357 |
+
bits = 4
|
| 1358 |
+
outmode += f";{bits}"
|
| 1359 |
+
|
| 1360 |
+
# encoder options
|
| 1361 |
+
im.encoderconfig = (
|
| 1362 |
+
im.encoderinfo.get("optimize", False),
|
| 1363 |
+
im.encoderinfo.get("compress_level", -1),
|
| 1364 |
+
im.encoderinfo.get("compress_type", -1),
|
| 1365 |
+
im.encoderinfo.get("dictionary", b""),
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
# get the corresponding PNG mode
|
| 1369 |
+
try:
|
| 1370 |
+
rawmode, bit_depth, color_type = _OUTMODES[outmode]
|
| 1371 |
+
except KeyError as e:
|
| 1372 |
+
msg = f"cannot write mode {mode} as PNG"
|
| 1373 |
+
raise OSError(msg) from e
|
| 1374 |
+
if outmode == "I":
|
| 1375 |
+
deprecate("Saving I mode images as PNG", 13, stacklevel=4)
|
| 1376 |
+
|
| 1377 |
+
#
|
| 1378 |
+
# write minimal PNG file
|
| 1379 |
+
|
| 1380 |
+
fp.write(_MAGIC)
|
| 1381 |
+
|
| 1382 |
+
chunk(
|
| 1383 |
+
fp,
|
| 1384 |
+
b"IHDR",
|
| 1385 |
+
o32(size[0]), # 0: size
|
| 1386 |
+
o32(size[1]),
|
| 1387 |
+
bit_depth,
|
| 1388 |
+
color_type,
|
| 1389 |
+
b"\0", # 10: compression
|
| 1390 |
+
b"\0", # 11: filter category
|
| 1391 |
+
b"\0", # 12: interlace flag
|
| 1392 |
+
)
|
| 1393 |
+
|
| 1394 |
+
chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
|
| 1395 |
+
|
| 1396 |
+
icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1397 |
+
if icc:
|
| 1398 |
+
# ICC profile
|
| 1399 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 1400 |
+
# Profile name 1-79 bytes (character string)
|
| 1401 |
+
# Null separator 1 byte (null character)
|
| 1402 |
+
# Compression method 1 byte (0)
|
| 1403 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 1404 |
+
name = b"ICC Profile"
|
| 1405 |
+
data = name + b"\0\0" + zlib.compress(icc)
|
| 1406 |
+
chunk(fp, b"iCCP", data)
|
| 1407 |
+
|
| 1408 |
+
# You must either have sRGB or iCCP.
|
| 1409 |
+
# Disallow sRGB chunks when an iCCP-chunk has been emitted.
|
| 1410 |
+
chunks.remove(b"sRGB")
|
| 1411 |
+
|
| 1412 |
+
info = im.encoderinfo.get("pnginfo")
|
| 1413 |
+
if info:
|
| 1414 |
+
chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
|
| 1415 |
+
for info_chunk in info.chunks:
|
| 1416 |
+
cid, data = info_chunk[:2]
|
| 1417 |
+
if cid in chunks:
|
| 1418 |
+
chunks.remove(cid)
|
| 1419 |
+
chunk(fp, cid, data)
|
| 1420 |
+
elif cid in chunks_multiple_allowed:
|
| 1421 |
+
chunk(fp, cid, data)
|
| 1422 |
+
elif cid[1:2].islower():
|
| 1423 |
+
# Private chunk
|
| 1424 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1425 |
+
if not after_idat:
|
| 1426 |
+
chunk(fp, cid, data)
|
| 1427 |
+
|
| 1428 |
+
if im.mode == "P":
|
| 1429 |
+
palette_byte_number = colors * 3
|
| 1430 |
+
palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
|
| 1431 |
+
while len(palette_bytes) < palette_byte_number:
|
| 1432 |
+
palette_bytes += b"\0"
|
| 1433 |
+
chunk(fp, b"PLTE", palette_bytes)
|
| 1434 |
+
|
| 1435 |
+
transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
|
| 1436 |
+
|
| 1437 |
+
if transparency or transparency == 0:
|
| 1438 |
+
if im.mode == "P":
|
| 1439 |
+
# limit to actual palette size
|
| 1440 |
+
alpha_bytes = colors
|
| 1441 |
+
if isinstance(transparency, bytes):
|
| 1442 |
+
chunk(fp, b"tRNS", transparency[:alpha_bytes])
|
| 1443 |
+
else:
|
| 1444 |
+
transparency = max(0, min(255, transparency))
|
| 1445 |
+
alpha = b"\xff" * transparency + b"\0"
|
| 1446 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1447 |
+
elif im.mode in ("1", "L", "I", "I;16"):
|
| 1448 |
+
transparency = max(0, min(65535, transparency))
|
| 1449 |
+
chunk(fp, b"tRNS", o16(transparency))
|
| 1450 |
+
elif im.mode == "RGB":
|
| 1451 |
+
red, green, blue = transparency
|
| 1452 |
+
chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
|
| 1453 |
+
else:
|
| 1454 |
+
if "transparency" in im.encoderinfo:
|
| 1455 |
+
# don't bother with transparency if it's an RGBA
|
| 1456 |
+
# and it's in the info dict. It's probably just stale.
|
| 1457 |
+
msg = "cannot use transparency for this mode"
|
| 1458 |
+
raise OSError(msg)
|
| 1459 |
+
else:
|
| 1460 |
+
if im.mode == "P" and im.im.getpalettemode() == "RGBA":
|
| 1461 |
+
alpha = im.im.getpalette("RGBA", "A")
|
| 1462 |
+
alpha_bytes = colors
|
| 1463 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1464 |
+
|
| 1465 |
+
dpi = im.encoderinfo.get("dpi")
|
| 1466 |
+
if dpi:
|
| 1467 |
+
chunk(
|
| 1468 |
+
fp,
|
| 1469 |
+
b"pHYs",
|
| 1470 |
+
o32(int(dpi[0] / 0.0254 + 0.5)),
|
| 1471 |
+
o32(int(dpi[1] / 0.0254 + 0.5)),
|
| 1472 |
+
b"\x01",
|
| 1473 |
+
)
|
| 1474 |
+
|
| 1475 |
+
if info:
|
| 1476 |
+
chunks = [b"bKGD", b"hIST"]
|
| 1477 |
+
for info_chunk in info.chunks:
|
| 1478 |
+
cid, data = info_chunk[:2]
|
| 1479 |
+
if cid in chunks:
|
| 1480 |
+
chunks.remove(cid)
|
| 1481 |
+
chunk(fp, cid, data)
|
| 1482 |
+
|
| 1483 |
+
exif = im.encoderinfo.get("exif")
|
| 1484 |
+
if exif:
|
| 1485 |
+
if isinstance(exif, Image.Exif):
|
| 1486 |
+
exif = exif.tobytes(8)
|
| 1487 |
+
if exif.startswith(b"Exif\x00\x00"):
|
| 1488 |
+
exif = exif[6:]
|
| 1489 |
+
chunk(fp, b"eXIf", exif)
|
| 1490 |
+
|
| 1491 |
+
single_im: Image.Image | None = im
|
| 1492 |
+
if save_all:
|
| 1493 |
+
single_im = _write_multiple_frames(
|
| 1494 |
+
im, fp, chunk, mode, rawmode, default_image, append_images
|
| 1495 |
+
)
|
| 1496 |
+
if single_im:
|
| 1497 |
+
ImageFile._save(
|
| 1498 |
+
single_im,
|
| 1499 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1500 |
+
[ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],
|
| 1501 |
+
)
|
| 1502 |
+
|
| 1503 |
+
if info:
|
| 1504 |
+
for info_chunk in info.chunks:
|
| 1505 |
+
cid, data = info_chunk[:2]
|
| 1506 |
+
if cid[1:2].islower():
|
| 1507 |
+
# Private chunk
|
| 1508 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1509 |
+
if after_idat:
|
| 1510 |
+
chunk(fp, cid, data)
|
| 1511 |
+
|
| 1512 |
+
chunk(fp, b"IEND", b"")
|
| 1513 |
+
|
| 1514 |
+
if hasattr(fp, "flush"):
|
| 1515 |
+
fp.flush()
|
| 1516 |
+
|
| 1517 |
+
|
| 1518 |
+
# --------------------------------------------------------------------
|
| 1519 |
+
# PNG chunk converter
|
| 1520 |
+
|
| 1521 |
+
|
| 1522 |
+
def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:
|
| 1523 |
+
"""Return a list of PNG chunks representing this image."""
|
| 1524 |
+
from io import BytesIO
|
| 1525 |
+
|
| 1526 |
+
chunks = []
|
| 1527 |
+
|
| 1528 |
+
def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
|
| 1529 |
+
byte_data = b"".join(data)
|
| 1530 |
+
crc = o32(_crc32(byte_data, _crc32(cid)))
|
| 1531 |
+
chunks.append((cid, byte_data, crc))
|
| 1532 |
+
|
| 1533 |
+
fp = BytesIO()
|
| 1534 |
+
|
| 1535 |
+
try:
|
| 1536 |
+
im.encoderinfo = params
|
| 1537 |
+
_save(im, fp, "", append)
|
| 1538 |
+
finally:
|
| 1539 |
+
del im.encoderinfo
|
| 1540 |
+
|
| 1541 |
+
return chunks
|
| 1542 |
+
|
| 1543 |
+
|
| 1544 |
+
# --------------------------------------------------------------------
|
| 1545 |
+
# Registry
|
| 1546 |
+
|
| 1547 |
+
Image.register_open(PngImageFile.format, PngImageFile, _accept)
|
| 1548 |
+
Image.register_save(PngImageFile.format, _save)
|
| 1549 |
+
Image.register_save_all(PngImageFile.format, _save_all)
|
| 1550 |
+
|
| 1551 |
+
Image.register_extensions(PngImageFile.format, [".png", ".apng"])
|
| 1552 |
+
|
| 1553 |
+
Image.register_mime(PngImageFile.format, "image/png")
|
.venv/lib/python3.12/site-packages/PIL/PpmImagePlugin.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PPM support for PIL
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-03-24 fl Created
|
| 9 |
+
# 98-03-06 fl Write RGBA images (as RGB, that is)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
| 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 |
+
import math
|
| 19 |
+
from typing import IO
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile
|
| 22 |
+
from ._binary import i16be as i16
|
| 23 |
+
from ._binary import o8
|
| 24 |
+
from ._binary import o32le as o32
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# --------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d"
|
| 30 |
+
|
| 31 |
+
MODES = {
|
| 32 |
+
# standard
|
| 33 |
+
b"P1": "1",
|
| 34 |
+
b"P2": "L",
|
| 35 |
+
b"P3": "RGB",
|
| 36 |
+
b"P4": "1",
|
| 37 |
+
b"P5": "L",
|
| 38 |
+
b"P6": "RGB",
|
| 39 |
+
# extensions
|
| 40 |
+
b"P0CMYK": "CMYK",
|
| 41 |
+
b"Pf": "F",
|
| 42 |
+
# PIL extensions (for test purposes only)
|
| 43 |
+
b"PyP": "P",
|
| 44 |
+
b"PyRGBA": "RGBA",
|
| 45 |
+
b"PyCMYK": "CMYK",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _accept(prefix: bytes) -> bool:
|
| 50 |
+
return len(prefix) >= 2 and prefix.startswith(b"P") and prefix[1] in b"0123456fy"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
##
|
| 54 |
+
# Image plugin for PBM, PGM, and PPM images.
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PpmImageFile(ImageFile.ImageFile):
|
| 58 |
+
format = "PPM"
|
| 59 |
+
format_description = "Pbmplus image"
|
| 60 |
+
|
| 61 |
+
def _read_magic(self) -> bytes:
|
| 62 |
+
assert self.fp is not None
|
| 63 |
+
|
| 64 |
+
magic = b""
|
| 65 |
+
# read until whitespace or longest available magic number
|
| 66 |
+
for _ in range(6):
|
| 67 |
+
c = self.fp.read(1)
|
| 68 |
+
if not c or c in b_whitespace:
|
| 69 |
+
break
|
| 70 |
+
magic += c
|
| 71 |
+
return magic
|
| 72 |
+
|
| 73 |
+
def _read_token(self) -> bytes:
|
| 74 |
+
assert self.fp is not None
|
| 75 |
+
|
| 76 |
+
token = b""
|
| 77 |
+
while len(token) <= 10: # read until next whitespace or limit of 10 characters
|
| 78 |
+
c = self.fp.read(1)
|
| 79 |
+
if not c:
|
| 80 |
+
break
|
| 81 |
+
elif c in b_whitespace: # token ended
|
| 82 |
+
if not token:
|
| 83 |
+
# skip whitespace at start
|
| 84 |
+
continue
|
| 85 |
+
break
|
| 86 |
+
elif c == b"#":
|
| 87 |
+
# ignores rest of the line; stops at CR, LF or EOF
|
| 88 |
+
while self.fp.read(1) not in b"\r\n":
|
| 89 |
+
pass
|
| 90 |
+
continue
|
| 91 |
+
token += c
|
| 92 |
+
if not token:
|
| 93 |
+
# Token was not even 1 byte
|
| 94 |
+
msg = "Reached EOF while reading header"
|
| 95 |
+
raise ValueError(msg)
|
| 96 |
+
elif len(token) > 10:
|
| 97 |
+
msg_too_long = b"Token too long in file header: %s" % token
|
| 98 |
+
raise ValueError(msg_too_long)
|
| 99 |
+
return token
|
| 100 |
+
|
| 101 |
+
def _open(self) -> None:
|
| 102 |
+
assert self.fp is not None
|
| 103 |
+
|
| 104 |
+
magic_number = self._read_magic()
|
| 105 |
+
try:
|
| 106 |
+
mode = MODES[magic_number]
|
| 107 |
+
except KeyError:
|
| 108 |
+
msg = "not a PPM file"
|
| 109 |
+
raise SyntaxError(msg)
|
| 110 |
+
self._mode = mode
|
| 111 |
+
|
| 112 |
+
if magic_number in (b"P1", b"P4"):
|
| 113 |
+
self.custom_mimetype = "image/x-portable-bitmap"
|
| 114 |
+
elif magic_number in (b"P2", b"P5"):
|
| 115 |
+
self.custom_mimetype = "image/x-portable-graymap"
|
| 116 |
+
elif magic_number in (b"P3", b"P6"):
|
| 117 |
+
self.custom_mimetype = "image/x-portable-pixmap"
|
| 118 |
+
|
| 119 |
+
self._size = int(self._read_token()), int(self._read_token())
|
| 120 |
+
|
| 121 |
+
decoder_name = "raw"
|
| 122 |
+
if magic_number in (b"P1", b"P2", b"P3"):
|
| 123 |
+
decoder_name = "ppm_plain"
|
| 124 |
+
|
| 125 |
+
args: str | tuple[str | int, ...]
|
| 126 |
+
if mode == "1":
|
| 127 |
+
args = "1;I"
|
| 128 |
+
elif mode == "F":
|
| 129 |
+
scale = float(self._read_token())
|
| 130 |
+
if scale == 0.0 or not math.isfinite(scale):
|
| 131 |
+
msg = "scale must be finite and non-zero"
|
| 132 |
+
raise ValueError(msg)
|
| 133 |
+
self.info["scale"] = abs(scale)
|
| 134 |
+
|
| 135 |
+
rawmode = "F;32F" if scale < 0 else "F;32BF"
|
| 136 |
+
args = (rawmode, 0, -1)
|
| 137 |
+
else:
|
| 138 |
+
maxval = int(self._read_token())
|
| 139 |
+
if not 0 < maxval < 65536:
|
| 140 |
+
msg = "maxval must be greater than 0 and less than 65536"
|
| 141 |
+
raise ValueError(msg)
|
| 142 |
+
if maxval > 255 and mode == "L":
|
| 143 |
+
self._mode = "I"
|
| 144 |
+
|
| 145 |
+
rawmode = mode
|
| 146 |
+
if decoder_name != "ppm_plain":
|
| 147 |
+
# If maxval matches a bit depth, use the raw decoder directly
|
| 148 |
+
if maxval == 65535 and mode == "L":
|
| 149 |
+
rawmode = "I;16B"
|
| 150 |
+
elif maxval != 255:
|
| 151 |
+
decoder_name = "ppm"
|
| 152 |
+
|
| 153 |
+
args = rawmode if decoder_name == "raw" else (rawmode, maxval)
|
| 154 |
+
self.tile = [
|
| 155 |
+
ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args)
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
#
|
| 160 |
+
# --------------------------------------------------------------------
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class PpmPlainDecoder(ImageFile.PyDecoder):
|
| 164 |
+
_pulls_fd = True
|
| 165 |
+
_comment_spans: bool
|
| 166 |
+
|
| 167 |
+
def _read_block(self) -> bytes:
|
| 168 |
+
assert self.fd is not None
|
| 169 |
+
|
| 170 |
+
return self.fd.read(ImageFile.SAFEBLOCK)
|
| 171 |
+
|
| 172 |
+
def _find_comment_end(self, block: bytes, start: int = 0) -> int:
|
| 173 |
+
a = block.find(b"\n", start)
|
| 174 |
+
b = block.find(b"\r", start)
|
| 175 |
+
return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1)
|
| 176 |
+
|
| 177 |
+
def _ignore_comments(self, block: bytes) -> bytes:
|
| 178 |
+
if self._comment_spans:
|
| 179 |
+
# Finish current comment
|
| 180 |
+
while block:
|
| 181 |
+
comment_end = self._find_comment_end(block)
|
| 182 |
+
if comment_end != -1:
|
| 183 |
+
# Comment ends in this block
|
| 184 |
+
# Delete tail of comment
|
| 185 |
+
block = block[comment_end + 1 :]
|
| 186 |
+
break
|
| 187 |
+
else:
|
| 188 |
+
# Comment spans whole block
|
| 189 |
+
# So read the next block, looking for the end
|
| 190 |
+
block = self._read_block()
|
| 191 |
+
|
| 192 |
+
# Search for any further comments
|
| 193 |
+
self._comment_spans = False
|
| 194 |
+
while True:
|
| 195 |
+
comment_start = block.find(b"#")
|
| 196 |
+
if comment_start == -1:
|
| 197 |
+
# No comment found
|
| 198 |
+
break
|
| 199 |
+
comment_end = self._find_comment_end(block, comment_start)
|
| 200 |
+
if comment_end != -1:
|
| 201 |
+
# Comment ends in this block
|
| 202 |
+
# Delete comment
|
| 203 |
+
block = block[:comment_start] + block[comment_end + 1 :]
|
| 204 |
+
else:
|
| 205 |
+
# Comment continues to next block(s)
|
| 206 |
+
block = block[:comment_start]
|
| 207 |
+
self._comment_spans = True
|
| 208 |
+
break
|
| 209 |
+
return block
|
| 210 |
+
|
| 211 |
+
def _decode_bitonal(self) -> bytearray:
|
| 212 |
+
"""
|
| 213 |
+
This is a separate method because in the plain PBM format, all data tokens are
|
| 214 |
+
exactly one byte, so the inter-token whitespace is optional.
|
| 215 |
+
"""
|
| 216 |
+
data = bytearray()
|
| 217 |
+
total_bytes = self.state.xsize * self.state.ysize
|
| 218 |
+
|
| 219 |
+
while len(data) != total_bytes:
|
| 220 |
+
block = self._read_block() # read next block
|
| 221 |
+
if not block:
|
| 222 |
+
# eof
|
| 223 |
+
break
|
| 224 |
+
|
| 225 |
+
block = self._ignore_comments(block)
|
| 226 |
+
|
| 227 |
+
tokens = b"".join(block.split())
|
| 228 |
+
for token in tokens:
|
| 229 |
+
if token not in (48, 49):
|
| 230 |
+
msg = b"Invalid token for this mode: %s" % bytes([token])
|
| 231 |
+
raise ValueError(msg)
|
| 232 |
+
data = (data + tokens)[:total_bytes]
|
| 233 |
+
invert = bytes.maketrans(b"01", b"\xff\x00")
|
| 234 |
+
return data.translate(invert)
|
| 235 |
+
|
| 236 |
+
def _decode_blocks(self, maxval: int) -> bytearray:
|
| 237 |
+
data = bytearray()
|
| 238 |
+
max_len = 10
|
| 239 |
+
out_byte_count = 4 if self.mode == "I" else 1
|
| 240 |
+
out_max = 65535 if self.mode == "I" else 255
|
| 241 |
+
bands = Image.getmodebands(self.mode)
|
| 242 |
+
total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count
|
| 243 |
+
|
| 244 |
+
half_token = b""
|
| 245 |
+
while len(data) != total_bytes:
|
| 246 |
+
block = self._read_block() # read next block
|
| 247 |
+
if not block:
|
| 248 |
+
if half_token:
|
| 249 |
+
block = bytearray(b" ") # flush half_token
|
| 250 |
+
else:
|
| 251 |
+
# eof
|
| 252 |
+
break
|
| 253 |
+
|
| 254 |
+
block = self._ignore_comments(block)
|
| 255 |
+
|
| 256 |
+
if half_token:
|
| 257 |
+
block = half_token + block # stitch half_token to new block
|
| 258 |
+
half_token = b""
|
| 259 |
+
|
| 260 |
+
tokens = block.split()
|
| 261 |
+
|
| 262 |
+
if block and not block[-1:].isspace(): # block might split token
|
| 263 |
+
half_token = tokens.pop() # save half token for later
|
| 264 |
+
if len(half_token) > max_len: # prevent buildup of half_token
|
| 265 |
+
msg = (
|
| 266 |
+
b"Token too long found in data: %s" % half_token[: max_len + 1]
|
| 267 |
+
)
|
| 268 |
+
raise ValueError(msg)
|
| 269 |
+
|
| 270 |
+
for token in tokens:
|
| 271 |
+
if len(token) > max_len:
|
| 272 |
+
msg = b"Token too long found in data: %s" % token[: max_len + 1]
|
| 273 |
+
raise ValueError(msg)
|
| 274 |
+
value = int(token)
|
| 275 |
+
if value < 0:
|
| 276 |
+
msg_str = f"Channel value is negative: {value}"
|
| 277 |
+
raise ValueError(msg_str)
|
| 278 |
+
if value > maxval:
|
| 279 |
+
msg_str = f"Channel value too large for this mode: {value}"
|
| 280 |
+
raise ValueError(msg_str)
|
| 281 |
+
value = round(value / maxval * out_max)
|
| 282 |
+
data += o32(value) if self.mode == "I" else o8(value)
|
| 283 |
+
if len(data) == total_bytes: # finished!
|
| 284 |
+
break
|
| 285 |
+
return data
|
| 286 |
+
|
| 287 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 288 |
+
self._comment_spans = False
|
| 289 |
+
if self.mode == "1":
|
| 290 |
+
data = self._decode_bitonal()
|
| 291 |
+
rawmode = "1;8"
|
| 292 |
+
else:
|
| 293 |
+
maxval = self.args[-1]
|
| 294 |
+
data = self._decode_blocks(maxval)
|
| 295 |
+
rawmode = "I;32" if self.mode == "I" else self.mode
|
| 296 |
+
self.set_as_raw(bytes(data), rawmode)
|
| 297 |
+
return -1, 0
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class PpmDecoder(ImageFile.PyDecoder):
|
| 301 |
+
_pulls_fd = True
|
| 302 |
+
|
| 303 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 304 |
+
assert self.fd is not None
|
| 305 |
+
|
| 306 |
+
data = bytearray()
|
| 307 |
+
maxval = self.args[-1]
|
| 308 |
+
in_byte_count = 1 if maxval < 256 else 2
|
| 309 |
+
out_byte_count = 4 if self.mode == "I" else 1
|
| 310 |
+
out_max = 65535 if self.mode == "I" else 255
|
| 311 |
+
bands = Image.getmodebands(self.mode)
|
| 312 |
+
dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count
|
| 313 |
+
while len(data) < dest_length:
|
| 314 |
+
pixels = self.fd.read(in_byte_count * bands)
|
| 315 |
+
if len(pixels) < in_byte_count * bands:
|
| 316 |
+
# eof
|
| 317 |
+
break
|
| 318 |
+
for b in range(bands):
|
| 319 |
+
value = (
|
| 320 |
+
pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count)
|
| 321 |
+
)
|
| 322 |
+
value = min(out_max, round(value / maxval * out_max))
|
| 323 |
+
data += o32(value) if self.mode == "I" else o8(value)
|
| 324 |
+
rawmode = "I;32" if self.mode == "I" else self.mode
|
| 325 |
+
self.set_as_raw(bytes(data), rawmode)
|
| 326 |
+
return -1, 0
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
#
|
| 330 |
+
# --------------------------------------------------------------------
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 334 |
+
if im.mode == "1":
|
| 335 |
+
rawmode, head = "1;I", b"P4"
|
| 336 |
+
elif im.mode == "L":
|
| 337 |
+
rawmode, head = "L", b"P5"
|
| 338 |
+
elif im.mode in ("I", "I;16"):
|
| 339 |
+
rawmode, head = "I;16B", b"P5"
|
| 340 |
+
elif im.mode in ("RGB", "RGBA"):
|
| 341 |
+
rawmode, head = "RGB", b"P6"
|
| 342 |
+
elif im.mode == "F":
|
| 343 |
+
rawmode, head = "F;32F", b"Pf"
|
| 344 |
+
else:
|
| 345 |
+
msg = f"cannot write mode {im.mode} as PPM"
|
| 346 |
+
raise OSError(msg)
|
| 347 |
+
fp.write(head + b"\n%d %d\n" % im.size)
|
| 348 |
+
if head == b"P6":
|
| 349 |
+
fp.write(b"255\n")
|
| 350 |
+
elif head == b"P5":
|
| 351 |
+
if rawmode == "L":
|
| 352 |
+
fp.write(b"255\n")
|
| 353 |
+
else:
|
| 354 |
+
fp.write(b"65535\n")
|
| 355 |
+
elif head == b"Pf":
|
| 356 |
+
fp.write(b"-1.0\n")
|
| 357 |
+
row_order = -1 if im.mode == "F" else 1
|
| 358 |
+
ImageFile._save(
|
| 359 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))]
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
#
|
| 364 |
+
# --------------------------------------------------------------------
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
Image.register_open(PpmImageFile.format, PpmImageFile, _accept)
|
| 368 |
+
Image.register_save(PpmImageFile.format, _save)
|
| 369 |
+
|
| 370 |
+
Image.register_decoder("ppm", PpmDecoder)
|
| 371 |
+
Image.register_decoder("ppm_plain", PpmPlainDecoder)
|
| 372 |
+
|
| 373 |
+
Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"])
|
| 374 |
+
|
| 375 |
+
Image.register_mime(PpmImageFile.format, "image/x-portable-anymap")
|
.venv/lib/python3.12/site-packages/PIL/XVThumbImagePlugin.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# XV Thumbnail file handler by Charles E. "Gene" Cash
|
| 6 |
+
# (gcash@magicnet.net)
|
| 7 |
+
#
|
| 8 |
+
# see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV,
|
| 9 |
+
# available from ftp://ftp.cis.upenn.edu/pub/xv/
|
| 10 |
+
#
|
| 11 |
+
# history:
|
| 12 |
+
# 98-08-15 cec created (b/w only)
|
| 13 |
+
# 98-12-09 cec added color palette
|
| 14 |
+
# 98-12-28 fl added to PIL (with only a few very minor modifications)
|
| 15 |
+
#
|
| 16 |
+
# To do:
|
| 17 |
+
# FIXME: make save work (this requires quantization support)
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile, ImagePalette
|
| 22 |
+
from ._binary import o8
|
| 23 |
+
|
| 24 |
+
_MAGIC = b"P7 332"
|
| 25 |
+
|
| 26 |
+
# standard color palette for thumbnails (RGB332)
|
| 27 |
+
PALETTE = b""
|
| 28 |
+
for r in range(8):
|
| 29 |
+
for g in range(8):
|
| 30 |
+
for b in range(4):
|
| 31 |
+
PALETTE = PALETTE + (
|
| 32 |
+
o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _accept(prefix: bytes) -> bool:
|
| 37 |
+
return prefix.startswith(_MAGIC)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
##
|
| 41 |
+
# Image plugin for XV thumbnail images.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class XVThumbImageFile(ImageFile.ImageFile):
|
| 45 |
+
format = "XVThumb"
|
| 46 |
+
format_description = "XV thumbnail image"
|
| 47 |
+
|
| 48 |
+
def _open(self) -> None:
|
| 49 |
+
# check magic
|
| 50 |
+
assert self.fp is not None
|
| 51 |
+
|
| 52 |
+
if not _accept(self.fp.read(6)):
|
| 53 |
+
msg = "not an XV thumbnail file"
|
| 54 |
+
raise SyntaxError(msg)
|
| 55 |
+
|
| 56 |
+
# Skip to beginning of next line
|
| 57 |
+
self.fp.readline()
|
| 58 |
+
|
| 59 |
+
# skip info comments
|
| 60 |
+
while True:
|
| 61 |
+
s = self.fp.readline()
|
| 62 |
+
if not s:
|
| 63 |
+
msg = "Unexpected EOF reading XV thumbnail file"
|
| 64 |
+
raise SyntaxError(msg)
|
| 65 |
+
if s[0] != 35: # ie. when not a comment: '#'
|
| 66 |
+
break
|
| 67 |
+
|
| 68 |
+
# parse header line (already read)
|
| 69 |
+
s = s.strip().split()
|
| 70 |
+
|
| 71 |
+
self._mode = "P"
|
| 72 |
+
self._size = int(s[0]), int(s[1])
|
| 73 |
+
|
| 74 |
+
self.palette = ImagePalette.raw("RGB", PALETTE)
|
| 75 |
+
|
| 76 |
+
self.tile = [
|
| 77 |
+
ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode)
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# --------------------------------------------------------------------
|
| 82 |
+
|
| 83 |
+
Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept)
|
.venv/lib/python3.12/site-packages/PIL/XpmImagePlugin.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# XPM File handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-12-29 fl Created
|
| 9 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997-2001.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996-2001.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
from . import Image, ImageFile, ImagePalette
|
| 21 |
+
from ._binary import o8
|
| 22 |
+
|
| 23 |
+
# XPM header
|
| 24 |
+
xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _accept(prefix: bytes) -> bool:
|
| 28 |
+
return prefix.startswith(b"/* XPM */")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
##
|
| 32 |
+
# Image plugin for X11 pixel maps.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class XpmImageFile(ImageFile.ImageFile):
|
| 36 |
+
format = "XPM"
|
| 37 |
+
format_description = "X11 Pixel Map"
|
| 38 |
+
|
| 39 |
+
def _open(self) -> None:
|
| 40 |
+
assert self.fp is not None
|
| 41 |
+
if not _accept(self.fp.read(9)):
|
| 42 |
+
msg = "not an XPM file"
|
| 43 |
+
raise SyntaxError(msg)
|
| 44 |
+
|
| 45 |
+
# skip forward to next string
|
| 46 |
+
while True:
|
| 47 |
+
line = self.fp.readline()
|
| 48 |
+
if not line:
|
| 49 |
+
msg = "broken XPM file"
|
| 50 |
+
raise SyntaxError(msg)
|
| 51 |
+
m = xpm_head.match(line)
|
| 52 |
+
if m:
|
| 53 |
+
break
|
| 54 |
+
|
| 55 |
+
self._size = int(m.group(1)), int(m.group(2))
|
| 56 |
+
|
| 57 |
+
palette_length = int(m.group(3))
|
| 58 |
+
bpp = int(m.group(4))
|
| 59 |
+
|
| 60 |
+
#
|
| 61 |
+
# load palette description
|
| 62 |
+
|
| 63 |
+
palette = {}
|
| 64 |
+
|
| 65 |
+
for _ in range(palette_length):
|
| 66 |
+
line = self.fp.readline().rstrip()
|
| 67 |
+
|
| 68 |
+
c = line[1 : bpp + 1]
|
| 69 |
+
s = line[bpp + 1 : -2].split()
|
| 70 |
+
|
| 71 |
+
for i in range(0, len(s), 2):
|
| 72 |
+
if s[i] == b"c":
|
| 73 |
+
# process colour key
|
| 74 |
+
rgb = s[i + 1]
|
| 75 |
+
if rgb == b"None":
|
| 76 |
+
self.info["transparency"] = c
|
| 77 |
+
elif rgb.startswith(b"#"):
|
| 78 |
+
rgb_int = int(rgb[1:], 16)
|
| 79 |
+
palette[c] = (
|
| 80 |
+
o8((rgb_int >> 16) & 255)
|
| 81 |
+
+ o8((rgb_int >> 8) & 255)
|
| 82 |
+
+ o8(rgb_int & 255)
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
# unknown colour
|
| 86 |
+
msg = "cannot read this XPM file"
|
| 87 |
+
raise ValueError(msg)
|
| 88 |
+
break
|
| 89 |
+
|
| 90 |
+
else:
|
| 91 |
+
# missing colour key
|
| 92 |
+
msg = "cannot read this XPM file"
|
| 93 |
+
raise ValueError(msg)
|
| 94 |
+
|
| 95 |
+
args: tuple[int, dict[bytes, bytes] | tuple[bytes, ...]]
|
| 96 |
+
if palette_length > 256:
|
| 97 |
+
self._mode = "RGB"
|
| 98 |
+
args = (bpp, palette)
|
| 99 |
+
else:
|
| 100 |
+
self._mode = "P"
|
| 101 |
+
self.palette = ImagePalette.raw("RGB", b"".join(palette.values()))
|
| 102 |
+
args = (bpp, tuple(palette.keys()))
|
| 103 |
+
|
| 104 |
+
self.tile = [ImageFile._Tile("xpm", (0, 0) + self.size, self.fp.tell(), args)]
|
| 105 |
+
|
| 106 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 107 |
+
#
|
| 108 |
+
# load all image data in one chunk
|
| 109 |
+
|
| 110 |
+
xsize, ysize = self.size
|
| 111 |
+
|
| 112 |
+
assert self.fp is not None
|
| 113 |
+
s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]
|
| 114 |
+
|
| 115 |
+
return b"".join(s)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class XpmDecoder(ImageFile.PyDecoder):
|
| 119 |
+
_pulls_fd = True
|
| 120 |
+
|
| 121 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 122 |
+
assert self.fd is not None
|
| 123 |
+
|
| 124 |
+
data = bytearray()
|
| 125 |
+
bpp, palette = self.args
|
| 126 |
+
dest_length = self.state.xsize * self.state.ysize
|
| 127 |
+
if self.mode == "RGB":
|
| 128 |
+
dest_length *= 3
|
| 129 |
+
pixel_header = False
|
| 130 |
+
while len(data) < dest_length:
|
| 131 |
+
line = self.fd.readline()
|
| 132 |
+
if not line:
|
| 133 |
+
break
|
| 134 |
+
if line.rstrip() == b"/* pixels */" and not pixel_header:
|
| 135 |
+
pixel_header = True
|
| 136 |
+
continue
|
| 137 |
+
line = b'"'.join(line.split(b'"')[1:-1])
|
| 138 |
+
for i in range(0, len(line), bpp):
|
| 139 |
+
key = line[i : i + bpp]
|
| 140 |
+
if self.mode == "RGB":
|
| 141 |
+
data += palette[key]
|
| 142 |
+
else:
|
| 143 |
+
data += o8(palette.index(key))
|
| 144 |
+
self.set_as_raw(bytes(data))
|
| 145 |
+
return -1, 0
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
#
|
| 149 |
+
# Registry
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
Image.register_open(XpmImageFile.format, XpmImageFile, _accept)
|
| 153 |
+
Image.register_decoder("xpm", XpmDecoder)
|
| 154 |
+
|
| 155 |
+
Image.register_extension(XpmImageFile.format, ".xpm")
|
| 156 |
+
|
| 157 |
+
Image.register_mime(XpmImageFile.format, "image/xpm")
|
.venv/lib/python3.12/site-packages/PIL/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pillow (Fork of the Python Imaging Library)
|
| 2 |
+
|
| 3 |
+
Pillow is the friendly PIL fork by Jeffrey A. Clark and contributors.
|
| 4 |
+
https://github.com/python-pillow/Pillow/
|
| 5 |
+
|
| 6 |
+
Pillow is forked from PIL 1.1.7.
|
| 7 |
+
|
| 8 |
+
PIL is the Python Imaging Library by Fredrik Lundh and contributors.
|
| 9 |
+
Copyright (c) 1999 by Secret Labs AB.
|
| 10 |
+
|
| 11 |
+
Use PIL.__version__ for this Pillow version.
|
| 12 |
+
|
| 13 |
+
;-)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from . import _version
|
| 19 |
+
|
| 20 |
+
# VERSION was removed in Pillow 6.0.0.
|
| 21 |
+
# PILLOW_VERSION was removed in Pillow 9.0.0.
|
| 22 |
+
# Use __version__ instead.
|
| 23 |
+
__version__ = _version.__version__
|
| 24 |
+
del _version
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_plugins = [
|
| 28 |
+
"AvifImagePlugin",
|
| 29 |
+
"BlpImagePlugin",
|
| 30 |
+
"BmpImagePlugin",
|
| 31 |
+
"BufrStubImagePlugin",
|
| 32 |
+
"CurImagePlugin",
|
| 33 |
+
"DcxImagePlugin",
|
| 34 |
+
"DdsImagePlugin",
|
| 35 |
+
"EpsImagePlugin",
|
| 36 |
+
"FitsImagePlugin",
|
| 37 |
+
"FliImagePlugin",
|
| 38 |
+
"FpxImagePlugin",
|
| 39 |
+
"FtexImagePlugin",
|
| 40 |
+
"GbrImagePlugin",
|
| 41 |
+
"GifImagePlugin",
|
| 42 |
+
"GribStubImagePlugin",
|
| 43 |
+
"Hdf5StubImagePlugin",
|
| 44 |
+
"IcnsImagePlugin",
|
| 45 |
+
"IcoImagePlugin",
|
| 46 |
+
"ImImagePlugin",
|
| 47 |
+
"ImtImagePlugin",
|
| 48 |
+
"IptcImagePlugin",
|
| 49 |
+
"JpegImagePlugin",
|
| 50 |
+
"Jpeg2KImagePlugin",
|
| 51 |
+
"McIdasImagePlugin",
|
| 52 |
+
"MicImagePlugin",
|
| 53 |
+
"MpegImagePlugin",
|
| 54 |
+
"MpoImagePlugin",
|
| 55 |
+
"MspImagePlugin",
|
| 56 |
+
"PalmImagePlugin",
|
| 57 |
+
"PcdImagePlugin",
|
| 58 |
+
"PcxImagePlugin",
|
| 59 |
+
"PdfImagePlugin",
|
| 60 |
+
"PixarImagePlugin",
|
| 61 |
+
"PngImagePlugin",
|
| 62 |
+
"PpmImagePlugin",
|
| 63 |
+
"PsdImagePlugin",
|
| 64 |
+
"QoiImagePlugin",
|
| 65 |
+
"SgiImagePlugin",
|
| 66 |
+
"SpiderImagePlugin",
|
| 67 |
+
"SunImagePlugin",
|
| 68 |
+
"TgaImagePlugin",
|
| 69 |
+
"TiffImagePlugin",
|
| 70 |
+
"WebPImagePlugin",
|
| 71 |
+
"WmfImagePlugin",
|
| 72 |
+
"XbmImagePlugin",
|
| 73 |
+
"XpmImagePlugin",
|
| 74 |
+
"XVThumbImagePlugin",
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class UnidentifiedImageError(OSError):
|
| 79 |
+
"""
|
| 80 |
+
Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.
|
| 81 |
+
|
| 82 |
+
If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES`
|
| 83 |
+
to true may allow the image to be opened after all. The setting will ignore missing
|
| 84 |
+
data and checksum failures.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
pass
|
.venv/lib/python3.12/site-packages/__pycache__/isympy.cpython-312.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/__pycache__/pylab.cpython-312.pyc
ADDED
|
Binary file (302 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/__pycache__/six.cpython-312.pyc
ADDED
|
Binary file (41.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/easydict-1.13.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: filelock
|
| 3 |
+
Version: 3.20.0
|
| 4 |
+
Summary: A platform independent file lock.
|
| 5 |
+
Project-URL: Documentation, https://py-filelock.readthedocs.io
|
| 6 |
+
Project-URL: Homepage, https://github.com/tox-dev/py-filelock
|
| 7 |
+
Project-URL: Source, https://github.com/tox-dev/py-filelock
|
| 8 |
+
Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues
|
| 9 |
+
Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>
|
| 10 |
+
License-Expression: Unlicense
|
| 11 |
+
License-File: LICENSE
|
| 12 |
+
Keywords: application,cache,directory,log,user
|
| 13 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 14 |
+
Classifier: Intended Audience :: Developers
|
| 15 |
+
Classifier: License :: OSI Approved :: The Unlicense (Unlicense)
|
| 16 |
+
Classifier: Operating System :: OS Independent
|
| 17 |
+
Classifier: Programming Language :: Python
|
| 18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 24 |
+
Classifier: Topic :: Internet
|
| 25 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 26 |
+
Classifier: Topic :: System
|
| 27 |
+
Requires-Python: >=3.10
|
| 28 |
+
Description-Content-Type: text/markdown
|
| 29 |
+
|
| 30 |
+
# filelock
|
| 31 |
+
|
| 32 |
+
[](https://pypi.org/project/filelock/)
|
| 33 |
+
[](https://pypi.org/project/filelock/)
|
| 35 |
+
[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
|
| 37 |
+
[](https://github.com/psf/black)
|
| 39 |
+
[](https://pepy.tech/project/filelock)
|
| 40 |
+
[](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
|
| 41 |
+
|
| 42 |
+
For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
|
.venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
filelock-3.20.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
filelock-3.20.0.dist-info/METADATA,sha256=gIghqdcbGNywxw52pN02_a9OxFqzhjA8v-9GsDWtNog,2110
|
| 3 |
+
filelock-3.20.0.dist-info/RECORD,,
|
| 4 |
+
filelock-3.20.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
| 5 |
+
filelock-3.20.0.dist-info/licenses/LICENSE,sha256=iNm062BXnBkew5HKBMFhMFctfu3EqG2qWL8oxuFMm80,1210
|
| 6 |
+
filelock/__init__.py,sha256=_t_-OAGXo_qyPa9lNQ1YnzVYEvSW3I0onPqzpomsVVg,1769
|
| 7 |
+
filelock/__pycache__/__init__.cpython-312.pyc,,
|
| 8 |
+
filelock/__pycache__/_api.cpython-312.pyc,,
|
| 9 |
+
filelock/__pycache__/_error.cpython-312.pyc,,
|
| 10 |
+
filelock/__pycache__/_soft.cpython-312.pyc,,
|
| 11 |
+
filelock/__pycache__/_unix.cpython-312.pyc,,
|
| 12 |
+
filelock/__pycache__/_util.cpython-312.pyc,,
|
| 13 |
+
filelock/__pycache__/_windows.cpython-312.pyc,,
|
| 14 |
+
filelock/__pycache__/asyncio.cpython-312.pyc,,
|
| 15 |
+
filelock/__pycache__/version.cpython-312.pyc,,
|
| 16 |
+
filelock/_api.py,sha256=2aATBeJ3-jtMj5OSm7EE539iNaTBsf13KXtcBMoi8oM,14545
|
| 17 |
+
filelock/_error.py,sha256=-5jMcjTu60YAvAO1UbqDD1GIEjVkwr8xCFwDBtMeYDg,787
|
| 18 |
+
filelock/_soft.py,sha256=haqtc_TB_KJbYv2a8iuEAclKuM4fMG1vTcp28sK919c,1711
|
| 19 |
+
filelock/_unix.py,sha256=eGOs4gDgZ-5fGnJUz-OkJDeZkAMzgvYcD8hVD6XH7e4,2351
|
| 20 |
+
filelock/_util.py,sha256=QHBoNFIYfbAThhotH3Q8E2acFc84wpG49-T-uu017ZE,1715
|
| 21 |
+
filelock/_windows.py,sha256=8k4XIBl_zZVfGC2gz0kEr8DZBvpNa8wdU9qeM1YrBb8,2179
|
| 22 |
+
filelock/asyncio.py,sha256=dSLe6XZSECFOgsVpcQUSh5Y5zAHxHGPu_tfpPX9I45k,12514
|
| 23 |
+
filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 24 |
+
filelock/version.py,sha256=AW5MeEjK4TaQWWJrGb_AlBw8PlmFoIcn7GodG_AVSOM,706
|
.venv/lib/python3.12/site-packages/filelock-3.20.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.27.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.venv/lib/python3.12/site-packages/filelock/__init__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A platform independent file lock that supports the with-statement.
|
| 3 |
+
|
| 4 |
+
.. autodata:: filelock.__version__
|
| 5 |
+
:no-value:
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import warnings
|
| 13 |
+
from typing import TYPE_CHECKING
|
| 14 |
+
|
| 15 |
+
from ._api import AcquireReturnProxy, BaseFileLock
|
| 16 |
+
from ._error import Timeout
|
| 17 |
+
from ._soft import SoftFileLock
|
| 18 |
+
from ._unix import UnixFileLock, has_fcntl
|
| 19 |
+
from ._windows import WindowsFileLock
|
| 20 |
+
from .asyncio import (
|
| 21 |
+
AsyncAcquireReturnProxy,
|
| 22 |
+
AsyncSoftFileLock,
|
| 23 |
+
AsyncUnixFileLock,
|
| 24 |
+
AsyncWindowsFileLock,
|
| 25 |
+
BaseAsyncFileLock,
|
| 26 |
+
)
|
| 27 |
+
from .version import version
|
| 28 |
+
|
| 29 |
+
#: version of the project as a string
|
| 30 |
+
__version__: str = version
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if sys.platform == "win32": # pragma: win32 cover
|
| 34 |
+
_FileLock: type[BaseFileLock] = WindowsFileLock
|
| 35 |
+
_AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLock
|
| 36 |
+
else: # pragma: win32 no cover # noqa: PLR5501
|
| 37 |
+
if has_fcntl:
|
| 38 |
+
_FileLock: type[BaseFileLock] = UnixFileLock
|
| 39 |
+
_AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock
|
| 40 |
+
else:
|
| 41 |
+
_FileLock = SoftFileLock
|
| 42 |
+
_AsyncFileLock = AsyncSoftFileLock
|
| 43 |
+
if warnings is not None:
|
| 44 |
+
warnings.warn("only soft file lock is available", stacklevel=2)
|
| 45 |
+
|
| 46 |
+
if TYPE_CHECKING:
|
| 47 |
+
FileLock = SoftFileLock
|
| 48 |
+
AsyncFileLock = AsyncSoftFileLock
|
| 49 |
+
else:
|
| 50 |
+
#: Alias for the lock, which should be used for the current platform.
|
| 51 |
+
FileLock = _FileLock
|
| 52 |
+
AsyncFileLock = _AsyncFileLock
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
__all__ = [
|
| 56 |
+
"AcquireReturnProxy",
|
| 57 |
+
"AsyncAcquireReturnProxy",
|
| 58 |
+
"AsyncFileLock",
|
| 59 |
+
"AsyncSoftFileLock",
|
| 60 |
+
"AsyncUnixFileLock",
|
| 61 |
+
"AsyncWindowsFileLock",
|
| 62 |
+
"BaseAsyncFileLock",
|
| 63 |
+
"BaseFileLock",
|
| 64 |
+
"FileLock",
|
| 65 |
+
"SoftFileLock",
|
| 66 |
+
"Timeout",
|
| 67 |
+
"UnixFileLock",
|
| 68 |
+
"WindowsFileLock",
|
| 69 |
+
"__version__",
|
| 70 |
+
]
|
.venv/lib/python3.12/site-packages/filelock/_error.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Timeout(TimeoutError): # noqa: N818
|
| 7 |
+
"""Raised when the lock could not be acquired in *timeout* seconds."""
|
| 8 |
+
|
| 9 |
+
def __init__(self, lock_file: str) -> None:
|
| 10 |
+
super().__init__()
|
| 11 |
+
self._lock_file = lock_file
|
| 12 |
+
|
| 13 |
+
def __reduce__(self) -> str | tuple[Any, ...]:
|
| 14 |
+
return self.__class__, (self._lock_file,) # Properly pickle the exception
|
| 15 |
+
|
| 16 |
+
def __str__(self) -> str:
|
| 17 |
+
return f"The file lock '{self._lock_file}' could not be acquired."
|
| 18 |
+
|
| 19 |
+
def __repr__(self) -> str:
|
| 20 |
+
return f"{self.__class__.__name__}({self.lock_file!r})"
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def lock_file(self) -> str:
|
| 24 |
+
""":return: The path of the file lock."""
|
| 25 |
+
return self._lock_file
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
"Timeout",
|
| 30 |
+
]
|