auto-sync 2026-07-02T13:37:00Z workspace (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +4 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageOps.py +746 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImagePalette.py +287 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImagePath.py +20 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageQt.py +219 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageSequence.py +88 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageShow.py +362 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageStat.py +167 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageText.py +320 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageTk.py +266 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageTransform.py +136 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageWin.py +247 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py +103 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/IptcImagePlugin.py +233 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py +448 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/JpegImagePlugin.py +895 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/JpegPresets.py +242 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py +78 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MicImagePlugin.py +103 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py +84 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py +204 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py +200 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PSDraw.py +237 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PaletteFile.py +54 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py +217 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PcdImagePlugin.py +68 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PcfFontFile.py +258 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py +228 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PdfImagePlugin.py +311 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PdfParser.py +1075 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py +72 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py +1564 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py +375 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py +334 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py +235 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/SgiImagePlugin.py +231 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/SpiderImagePlugin.py +332 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/SunImagePlugin.py +145 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TarIO.py +61 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py +264 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py +2338 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TiffTags.py +566 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WalImageFile.py +128 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py +317 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py +188 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/XVThumbImagePlugin.py +83 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/XbmImagePlugin.py +98 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/XpmImagePlugin.py +157 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/__init__.py +87 -0
- workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/__main__.py +7 -0
.gitattributes
CHANGED
|
@@ -134,3 +134,7 @@ outputs/audit_venv/lib/python3.11/site-packages/torch/lib/libtorch_python.so fil
|
|
| 134 |
outputs/audit_venv/lib/python3.11/site-packages/yaml/_yaml.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 135 |
outputs/external_vla_export_maniskill_full_no_images/train.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 136 |
workspace/latex/main.pdf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
outputs/audit_venv/lib/python3.11/site-packages/yaml/_yaml.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 135 |
outputs/external_vla_export_maniskill_full_no_images/train.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 136 |
workspace/latex/main.pdf filter=lfs diff=lfs merge=lfs -text
|
| 137 |
+
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 138 |
+
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 139 |
+
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 140 |
+
workspace/outputs/audit_venv/lib/python3.11/site-packages/contourpy/_contourpy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageOps.py
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# standard image operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2001-10-20 fl Created
|
| 9 |
+
# 2001-10-23 fl Added autocontrast operator
|
| 10 |
+
# 2001-12-18 fl Added Kevin's fit operator
|
| 11 |
+
# 2004-03-14 fl Fixed potential division by zero in equalize
|
| 12 |
+
# 2005-05-05 fl Fixed equalize for low number of values
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) 2001-2004 by Secret Labs AB
|
| 15 |
+
# Copyright (c) 2001-2004 by Fredrik Lundh
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import functools
|
| 22 |
+
import operator
|
| 23 |
+
import re
|
| 24 |
+
from collections.abc import Sequence
|
| 25 |
+
from typing import Literal, Protocol, cast, overload
|
| 26 |
+
|
| 27 |
+
from . import ExifTags, Image, ImagePalette
|
| 28 |
+
|
| 29 |
+
#
|
| 30 |
+
# helpers
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
|
| 34 |
+
if isinstance(border, tuple):
|
| 35 |
+
if len(border) == 2:
|
| 36 |
+
left, top = right, bottom = border
|
| 37 |
+
elif len(border) == 4:
|
| 38 |
+
left, top, right, bottom = border
|
| 39 |
+
else:
|
| 40 |
+
left = top = right = bottom = border
|
| 41 |
+
return left, top, right, bottom
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
|
| 45 |
+
if isinstance(color, str):
|
| 46 |
+
from . import ImageColor
|
| 47 |
+
|
| 48 |
+
color = ImageColor.getcolor(color, mode)
|
| 49 |
+
return color
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
|
| 53 |
+
if image.mode == "P":
|
| 54 |
+
# FIXME: apply to lookup table, not image data
|
| 55 |
+
msg = "mode P support coming soon"
|
| 56 |
+
raise NotImplementedError(msg)
|
| 57 |
+
elif image.mode in ("L", "RGB"):
|
| 58 |
+
if image.mode == "RGB" and len(lut) == 256:
|
| 59 |
+
lut = lut + lut + lut
|
| 60 |
+
return image.point(lut)
|
| 61 |
+
else:
|
| 62 |
+
msg = f"not supported for mode {image.mode}"
|
| 63 |
+
raise OSError(msg)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
#
|
| 67 |
+
# actions
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def autocontrast(
|
| 71 |
+
image: Image.Image,
|
| 72 |
+
cutoff: float | tuple[float, float] = 0,
|
| 73 |
+
ignore: int | Sequence[int] | None = None,
|
| 74 |
+
mask: Image.Image | None = None,
|
| 75 |
+
preserve_tone: bool = False,
|
| 76 |
+
) -> Image.Image:
|
| 77 |
+
"""
|
| 78 |
+
Maximize (normalize) image contrast. This function calculates a
|
| 79 |
+
histogram of the input image (or mask region), removes ``cutoff`` percent of the
|
| 80 |
+
lightest and darkest pixels from the histogram, and remaps the image
|
| 81 |
+
so that the darkest pixel becomes black (0), and the lightest
|
| 82 |
+
becomes white (255).
|
| 83 |
+
|
| 84 |
+
:param image: The image to process.
|
| 85 |
+
:param cutoff: The percent to cut off from the histogram on the low and
|
| 86 |
+
high ends. Either a tuple of (low, high), or a single
|
| 87 |
+
number for both.
|
| 88 |
+
:param ignore: The background pixel value (use None for no background).
|
| 89 |
+
:param mask: Histogram used in contrast operation is computed using pixels
|
| 90 |
+
within the mask. If no mask is given the entire image is used
|
| 91 |
+
for histogram computation.
|
| 92 |
+
:param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
|
| 93 |
+
|
| 94 |
+
.. versionadded:: 8.2.0
|
| 95 |
+
|
| 96 |
+
:return: An image.
|
| 97 |
+
"""
|
| 98 |
+
if preserve_tone:
|
| 99 |
+
histogram = image.convert("L").histogram(mask)
|
| 100 |
+
else:
|
| 101 |
+
histogram = image.histogram(mask)
|
| 102 |
+
|
| 103 |
+
lut = []
|
| 104 |
+
for layer in range(0, len(histogram), 256):
|
| 105 |
+
h = histogram[layer : layer + 256]
|
| 106 |
+
if ignore is not None:
|
| 107 |
+
# get rid of outliers
|
| 108 |
+
if isinstance(ignore, int):
|
| 109 |
+
h[ignore] = 0
|
| 110 |
+
else:
|
| 111 |
+
for ix in ignore:
|
| 112 |
+
h[ix] = 0
|
| 113 |
+
if cutoff:
|
| 114 |
+
# cut off pixels from both ends of the histogram
|
| 115 |
+
if not isinstance(cutoff, tuple):
|
| 116 |
+
cutoff = (cutoff, cutoff)
|
| 117 |
+
# get number of pixels
|
| 118 |
+
n = 0
|
| 119 |
+
for ix in range(256):
|
| 120 |
+
n = n + h[ix]
|
| 121 |
+
# remove cutoff% pixels from the low end
|
| 122 |
+
cut = int(n * cutoff[0] // 100)
|
| 123 |
+
for lo in range(256):
|
| 124 |
+
if cut > h[lo]:
|
| 125 |
+
cut = cut - h[lo]
|
| 126 |
+
h[lo] = 0
|
| 127 |
+
else:
|
| 128 |
+
h[lo] -= cut
|
| 129 |
+
cut = 0
|
| 130 |
+
if cut <= 0:
|
| 131 |
+
break
|
| 132 |
+
# remove cutoff% samples from the high end
|
| 133 |
+
cut = int(n * cutoff[1] // 100)
|
| 134 |
+
for hi in range(255, -1, -1):
|
| 135 |
+
if cut > h[hi]:
|
| 136 |
+
cut = cut - h[hi]
|
| 137 |
+
h[hi] = 0
|
| 138 |
+
else:
|
| 139 |
+
h[hi] -= cut
|
| 140 |
+
cut = 0
|
| 141 |
+
if cut <= 0:
|
| 142 |
+
break
|
| 143 |
+
# find lowest/highest samples after preprocessing
|
| 144 |
+
for lo in range(256):
|
| 145 |
+
if h[lo]:
|
| 146 |
+
break
|
| 147 |
+
for hi in range(255, -1, -1):
|
| 148 |
+
if h[hi]:
|
| 149 |
+
break
|
| 150 |
+
if hi <= lo:
|
| 151 |
+
# don't bother
|
| 152 |
+
lut.extend(list(range(256)))
|
| 153 |
+
else:
|
| 154 |
+
scale = 255.0 / (hi - lo)
|
| 155 |
+
offset = -lo * scale
|
| 156 |
+
for ix in range(256):
|
| 157 |
+
ix = int(ix * scale + offset)
|
| 158 |
+
if ix < 0:
|
| 159 |
+
ix = 0
|
| 160 |
+
elif ix > 255:
|
| 161 |
+
ix = 255
|
| 162 |
+
lut.append(ix)
|
| 163 |
+
return _lut(image, lut)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def colorize(
|
| 167 |
+
image: Image.Image,
|
| 168 |
+
black: str | tuple[int, ...],
|
| 169 |
+
white: str | tuple[int, ...],
|
| 170 |
+
mid: str | int | tuple[int, ...] | None = None,
|
| 171 |
+
blackpoint: int = 0,
|
| 172 |
+
whitepoint: int = 255,
|
| 173 |
+
midpoint: int = 127,
|
| 174 |
+
) -> Image.Image:
|
| 175 |
+
"""
|
| 176 |
+
Colorize grayscale image.
|
| 177 |
+
This function calculates a color wedge which maps all black pixels in
|
| 178 |
+
the source image to the first color and all white pixels to the
|
| 179 |
+
second color. If ``mid`` is specified, it uses three-color mapping.
|
| 180 |
+
The ``black`` and ``white`` arguments should be RGB tuples or color names;
|
| 181 |
+
optionally you can use three-color mapping by also specifying ``mid``.
|
| 182 |
+
Mapping positions for any of the colors can be specified
|
| 183 |
+
(e.g. ``blackpoint``), where these parameters are the integer
|
| 184 |
+
value corresponding to where the corresponding color should be mapped.
|
| 185 |
+
These parameters must have logical order, such that
|
| 186 |
+
``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
|
| 187 |
+
|
| 188 |
+
:param image: The image to colorize.
|
| 189 |
+
:param black: The color to use for black input pixels.
|
| 190 |
+
:param white: The color to use for white input pixels.
|
| 191 |
+
:param mid: The color to use for midtone input pixels.
|
| 192 |
+
:param blackpoint: an int value [0, 255] for the black mapping.
|
| 193 |
+
:param whitepoint: an int value [0, 255] for the white mapping.
|
| 194 |
+
:param midpoint: an int value [0, 255] for the midtone mapping.
|
| 195 |
+
:return: An image.
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
# Initial asserts
|
| 199 |
+
assert image.mode == "L"
|
| 200 |
+
if mid is None:
|
| 201 |
+
assert 0 <= blackpoint <= whitepoint <= 255
|
| 202 |
+
else:
|
| 203 |
+
assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
|
| 204 |
+
|
| 205 |
+
# Define colors from arguments
|
| 206 |
+
rgb_black = cast(Sequence[int], _color(black, "RGB"))
|
| 207 |
+
rgb_white = cast(Sequence[int], _color(white, "RGB"))
|
| 208 |
+
rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
|
| 209 |
+
|
| 210 |
+
# Empty lists for the mapping
|
| 211 |
+
red = []
|
| 212 |
+
green = []
|
| 213 |
+
blue = []
|
| 214 |
+
|
| 215 |
+
# Create the low-end values
|
| 216 |
+
for i in range(blackpoint):
|
| 217 |
+
red.append(rgb_black[0])
|
| 218 |
+
green.append(rgb_black[1])
|
| 219 |
+
blue.append(rgb_black[2])
|
| 220 |
+
|
| 221 |
+
# Create the mapping (2-color)
|
| 222 |
+
if rgb_mid is None:
|
| 223 |
+
range_map = range(whitepoint - blackpoint)
|
| 224 |
+
|
| 225 |
+
for i in range_map:
|
| 226 |
+
red.append(
|
| 227 |
+
rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
|
| 228 |
+
)
|
| 229 |
+
green.append(
|
| 230 |
+
rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
|
| 231 |
+
)
|
| 232 |
+
blue.append(
|
| 233 |
+
rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Create the mapping (3-color)
|
| 237 |
+
else:
|
| 238 |
+
range_map1 = range(midpoint - blackpoint)
|
| 239 |
+
range_map2 = range(whitepoint - midpoint)
|
| 240 |
+
|
| 241 |
+
for i in range_map1:
|
| 242 |
+
red.append(
|
| 243 |
+
rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
|
| 244 |
+
)
|
| 245 |
+
green.append(
|
| 246 |
+
rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
|
| 247 |
+
)
|
| 248 |
+
blue.append(
|
| 249 |
+
rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
|
| 250 |
+
)
|
| 251 |
+
for i in range_map2:
|
| 252 |
+
red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
|
| 253 |
+
green.append(
|
| 254 |
+
rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
|
| 255 |
+
)
|
| 256 |
+
blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
|
| 257 |
+
|
| 258 |
+
# Create the high-end values
|
| 259 |
+
for i in range(256 - whitepoint):
|
| 260 |
+
red.append(rgb_white[0])
|
| 261 |
+
green.append(rgb_white[1])
|
| 262 |
+
blue.append(rgb_white[2])
|
| 263 |
+
|
| 264 |
+
# Return converted image
|
| 265 |
+
image = image.convert("RGB")
|
| 266 |
+
return _lut(image, red + green + blue)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def contain(
|
| 270 |
+
image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
|
| 271 |
+
) -> Image.Image:
|
| 272 |
+
"""
|
| 273 |
+
Returns a resized version of the image, set to the maximum width and height
|
| 274 |
+
within the requested size, while maintaining the original aspect ratio.
|
| 275 |
+
|
| 276 |
+
:param image: The image to resize.
|
| 277 |
+
:param size: The requested output size in pixels, given as a
|
| 278 |
+
(width, height) tuple.
|
| 279 |
+
:param method: Resampling method to use. Default is
|
| 280 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
| 281 |
+
See :ref:`concept-filters`.
|
| 282 |
+
:return: An image.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
im_ratio = image.width / image.height
|
| 286 |
+
dest_ratio = size[0] / size[1]
|
| 287 |
+
|
| 288 |
+
if im_ratio != dest_ratio:
|
| 289 |
+
if im_ratio > dest_ratio:
|
| 290 |
+
new_height = round(image.height / image.width * size[0])
|
| 291 |
+
if new_height != size[1]:
|
| 292 |
+
size = (size[0], new_height)
|
| 293 |
+
else:
|
| 294 |
+
new_width = round(image.width / image.height * size[1])
|
| 295 |
+
if new_width != size[0]:
|
| 296 |
+
size = (new_width, size[1])
|
| 297 |
+
return image.resize(size, resample=method)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def cover(
|
| 301 |
+
image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
|
| 302 |
+
) -> Image.Image:
|
| 303 |
+
"""
|
| 304 |
+
Returns a resized version of the image, so that the requested size is
|
| 305 |
+
covered, while maintaining the original aspect ratio.
|
| 306 |
+
|
| 307 |
+
:param image: The image to resize.
|
| 308 |
+
:param size: The requested output size in pixels, given as a
|
| 309 |
+
(width, height) tuple.
|
| 310 |
+
:param method: Resampling method to use. Default is
|
| 311 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
| 312 |
+
See :ref:`concept-filters`.
|
| 313 |
+
:return: An image.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
im_ratio = image.width / image.height
|
| 317 |
+
dest_ratio = size[0] / size[1]
|
| 318 |
+
|
| 319 |
+
if im_ratio != dest_ratio:
|
| 320 |
+
if im_ratio < dest_ratio:
|
| 321 |
+
new_height = round(image.height / image.width * size[0])
|
| 322 |
+
if new_height != size[1]:
|
| 323 |
+
size = (size[0], new_height)
|
| 324 |
+
else:
|
| 325 |
+
new_width = round(image.width / image.height * size[1])
|
| 326 |
+
if new_width != size[0]:
|
| 327 |
+
size = (new_width, size[1])
|
| 328 |
+
return image.resize(size, resample=method)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def pad(
|
| 332 |
+
image: Image.Image,
|
| 333 |
+
size: tuple[int, int],
|
| 334 |
+
method: int = Image.Resampling.BICUBIC,
|
| 335 |
+
color: str | int | tuple[int, ...] | None = None,
|
| 336 |
+
centering: tuple[float, float] = (0.5, 0.5),
|
| 337 |
+
) -> Image.Image:
|
| 338 |
+
"""
|
| 339 |
+
Returns a resized and padded version of the image, expanded to fill the
|
| 340 |
+
requested aspect ratio and size.
|
| 341 |
+
|
| 342 |
+
:param image: The image to resize and crop.
|
| 343 |
+
:param size: The requested output size in pixels, given as a
|
| 344 |
+
(width, height) tuple.
|
| 345 |
+
:param method: Resampling method to use. Default is
|
| 346 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
| 347 |
+
See :ref:`concept-filters`.
|
| 348 |
+
:param color: The background color of the padded image.
|
| 349 |
+
:param centering: Control the position of the original image within the
|
| 350 |
+
padded version.
|
| 351 |
+
|
| 352 |
+
(0.5, 0.5) will keep the image centered
|
| 353 |
+
(0, 0) will keep the image aligned to the top left
|
| 354 |
+
(1, 1) will keep the image aligned to the bottom
|
| 355 |
+
right
|
| 356 |
+
:return: An image.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
resized = contain(image, size, method)
|
| 360 |
+
if resized.size == size:
|
| 361 |
+
out = resized
|
| 362 |
+
else:
|
| 363 |
+
out = Image.new(image.mode, size, color)
|
| 364 |
+
if resized.palette:
|
| 365 |
+
palette = resized.getpalette()
|
| 366 |
+
if palette is not None:
|
| 367 |
+
out.putpalette(palette)
|
| 368 |
+
if resized.width != size[0]:
|
| 369 |
+
x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
|
| 370 |
+
out.paste(resized, (x, 0))
|
| 371 |
+
else:
|
| 372 |
+
y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
|
| 373 |
+
out.paste(resized, (0, y))
|
| 374 |
+
return out
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def crop(image: Image.Image, border: int = 0) -> Image.Image:
|
| 378 |
+
"""
|
| 379 |
+
Remove border from image. The same amount of pixels are removed
|
| 380 |
+
from all four sides. This function works on all image modes.
|
| 381 |
+
|
| 382 |
+
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
|
| 383 |
+
|
| 384 |
+
:param image: The image to crop.
|
| 385 |
+
:param border: The number of pixels to remove.
|
| 386 |
+
:return: An image.
|
| 387 |
+
"""
|
| 388 |
+
left, top, right, bottom = _border(border)
|
| 389 |
+
return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def scale(
|
| 393 |
+
image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
|
| 394 |
+
) -> Image.Image:
|
| 395 |
+
"""
|
| 396 |
+
Returns a rescaled image by a specific factor given in parameter.
|
| 397 |
+
A factor greater than 1 expands the image, between 0 and 1 contracts the
|
| 398 |
+
image.
|
| 399 |
+
|
| 400 |
+
:param image: The image to rescale.
|
| 401 |
+
:param factor: The expansion factor, as a float.
|
| 402 |
+
:param resample: Resampling method to use. Default is
|
| 403 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
| 404 |
+
See :ref:`concept-filters`.
|
| 405 |
+
:returns: An :py:class:`~PIL.Image.Image` object.
|
| 406 |
+
"""
|
| 407 |
+
if factor == 1:
|
| 408 |
+
return image.copy()
|
| 409 |
+
elif factor <= 0:
|
| 410 |
+
msg = "the factor must be greater than 0"
|
| 411 |
+
raise ValueError(msg)
|
| 412 |
+
else:
|
| 413 |
+
size = (round(factor * image.width), round(factor * image.height))
|
| 414 |
+
return image.resize(size, resample)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class SupportsGetMesh(Protocol):
|
| 418 |
+
"""
|
| 419 |
+
An object that supports the ``getmesh`` method, taking an image as an
|
| 420 |
+
argument, and returning a list of tuples. Each tuple contains two tuples,
|
| 421 |
+
the source box as a tuple of 4 integers, and a tuple of 8 integers for the
|
| 422 |
+
final quadrilateral, in order of top left, bottom left, bottom right, top
|
| 423 |
+
right.
|
| 424 |
+
"""
|
| 425 |
+
|
| 426 |
+
def getmesh(
|
| 427 |
+
self, image: Image.Image
|
| 428 |
+
) -> list[
|
| 429 |
+
tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
|
| 430 |
+
]: ...
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def deform(
|
| 434 |
+
image: Image.Image,
|
| 435 |
+
deformer: SupportsGetMesh,
|
| 436 |
+
resample: int = Image.Resampling.BILINEAR,
|
| 437 |
+
) -> Image.Image:
|
| 438 |
+
"""
|
| 439 |
+
Deform the image.
|
| 440 |
+
|
| 441 |
+
:param image: The image to deform.
|
| 442 |
+
:param deformer: A deformer object. Any object that implements a
|
| 443 |
+
``getmesh`` method can be used.
|
| 444 |
+
:param resample: An optional resampling filter. Same values possible as
|
| 445 |
+
in the PIL.Image.transform function.
|
| 446 |
+
:return: An image.
|
| 447 |
+
"""
|
| 448 |
+
return image.transform(
|
| 449 |
+
image.size, Image.Transform.MESH, deformer.getmesh(image), resample
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
|
| 454 |
+
"""
|
| 455 |
+
Equalize the image histogram. This function applies a non-linear
|
| 456 |
+
mapping to the input image, in order to create a uniform
|
| 457 |
+
distribution of grayscale values in the output image.
|
| 458 |
+
|
| 459 |
+
:param image: The image to equalize.
|
| 460 |
+
:param mask: An optional mask. If given, only the pixels selected by
|
| 461 |
+
the mask are included in the analysis.
|
| 462 |
+
:return: An image.
|
| 463 |
+
"""
|
| 464 |
+
if image.mode == "P":
|
| 465 |
+
image = image.convert("RGB")
|
| 466 |
+
h = image.histogram(mask)
|
| 467 |
+
lut = []
|
| 468 |
+
for b in range(0, len(h), 256):
|
| 469 |
+
histo = [_f for _f in h[b : b + 256] if _f]
|
| 470 |
+
if len(histo) <= 1:
|
| 471 |
+
lut.extend(list(range(256)))
|
| 472 |
+
else:
|
| 473 |
+
step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
|
| 474 |
+
if not step:
|
| 475 |
+
lut.extend(list(range(256)))
|
| 476 |
+
else:
|
| 477 |
+
n = step // 2
|
| 478 |
+
for i in range(256):
|
| 479 |
+
lut.append(n // step)
|
| 480 |
+
n = n + h[i + b]
|
| 481 |
+
return _lut(image, lut)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def expand(
|
| 485 |
+
image: Image.Image,
|
| 486 |
+
border: int | tuple[int, ...] = 0,
|
| 487 |
+
fill: str | int | tuple[int, ...] = 0,
|
| 488 |
+
) -> Image.Image:
|
| 489 |
+
"""
|
| 490 |
+
Add border to the image
|
| 491 |
+
|
| 492 |
+
:param image: The image to expand.
|
| 493 |
+
:param border: Border width, in pixels.
|
| 494 |
+
:param fill: Pixel fill value (a color value). Default is 0 (black).
|
| 495 |
+
:return: An image.
|
| 496 |
+
"""
|
| 497 |
+
left, top, right, bottom = _border(border)
|
| 498 |
+
width = left + image.size[0] + right
|
| 499 |
+
height = top + image.size[1] + bottom
|
| 500 |
+
color = _color(fill, image.mode)
|
| 501 |
+
if image.palette:
|
| 502 |
+
mode = image.palette.mode
|
| 503 |
+
palette = ImagePalette.ImagePalette(mode, image.getpalette(mode))
|
| 504 |
+
if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
|
| 505 |
+
color = palette.getcolor(color)
|
| 506 |
+
else:
|
| 507 |
+
palette = None
|
| 508 |
+
out = Image.new(image.mode, (width, height), color)
|
| 509 |
+
if palette:
|
| 510 |
+
out.putpalette(palette.palette, mode)
|
| 511 |
+
out.paste(image, (left, top))
|
| 512 |
+
return out
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def fit(
|
| 516 |
+
image: Image.Image,
|
| 517 |
+
size: tuple[int, int],
|
| 518 |
+
method: int = Image.Resampling.BICUBIC,
|
| 519 |
+
bleed: float = 0.0,
|
| 520 |
+
centering: tuple[float, float] = (0.5, 0.5),
|
| 521 |
+
) -> Image.Image:
|
| 522 |
+
"""
|
| 523 |
+
Returns a resized and cropped version of the image, cropped to the
|
| 524 |
+
requested aspect ratio and size.
|
| 525 |
+
|
| 526 |
+
This function was contributed by Kevin Cazabon.
|
| 527 |
+
|
| 528 |
+
:param image: The image to resize and crop.
|
| 529 |
+
:param size: The requested output size in pixels, given as a
|
| 530 |
+
(width, height) tuple.
|
| 531 |
+
:param method: Resampling method to use. Default is
|
| 532 |
+
:py:attr:`~PIL.Image.Resampling.BICUBIC`.
|
| 533 |
+
See :ref:`concept-filters`.
|
| 534 |
+
:param bleed: Remove a border around the outside of the image from all
|
| 535 |
+
four edges. The value is a decimal percentage (use 0.01 for
|
| 536 |
+
one percent). The default value is 0 (no border).
|
| 537 |
+
Cannot be greater than or equal to 0.5.
|
| 538 |
+
:param centering: Control the cropping position. Use (0.5, 0.5) for
|
| 539 |
+
center cropping (e.g. if cropping the width, take 50% off
|
| 540 |
+
of the left side, and therefore 50% off the right side).
|
| 541 |
+
(0.0, 0.0) will crop from the top left corner (i.e. if
|
| 542 |
+
cropping the width, take all of the crop off of the right
|
| 543 |
+
side, and if cropping the height, take all of it off the
|
| 544 |
+
bottom). (1.0, 0.0) will crop from the bottom left
|
| 545 |
+
corner, etc. (i.e. if cropping the width, take all of the
|
| 546 |
+
crop off the left side, and if cropping the height take
|
| 547 |
+
none from the top, and therefore all off the bottom).
|
| 548 |
+
:return: An image.
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
# by Kevin Cazabon, Feb 17/2000
|
| 552 |
+
# kevin@cazabon.com
|
| 553 |
+
# https://www.cazabon.com
|
| 554 |
+
|
| 555 |
+
centering_x, centering_y = centering
|
| 556 |
+
|
| 557 |
+
if not 0.0 <= centering_x <= 1.0:
|
| 558 |
+
centering_x = 0.5
|
| 559 |
+
if not 0.0 <= centering_y <= 1.0:
|
| 560 |
+
centering_y = 0.5
|
| 561 |
+
|
| 562 |
+
if not 0.0 <= bleed < 0.5:
|
| 563 |
+
bleed = 0.0
|
| 564 |
+
|
| 565 |
+
# calculate the area to use for resizing and cropping, subtracting
|
| 566 |
+
# the 'bleed' around the edges
|
| 567 |
+
|
| 568 |
+
# number of pixels to trim off on Top and Bottom, Left and Right
|
| 569 |
+
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
|
| 570 |
+
|
| 571 |
+
live_size = (
|
| 572 |
+
image.size[0] - bleed_pixels[0] * 2,
|
| 573 |
+
image.size[1] - bleed_pixels[1] * 2,
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
# calculate the aspect ratio of the live_size
|
| 577 |
+
live_size_ratio = live_size[0] / live_size[1]
|
| 578 |
+
|
| 579 |
+
# calculate the aspect ratio of the output image
|
| 580 |
+
output_ratio = size[0] / size[1]
|
| 581 |
+
|
| 582 |
+
# figure out if the sides or top/bottom will be cropped off
|
| 583 |
+
if live_size_ratio == output_ratio:
|
| 584 |
+
# live_size is already the needed ratio
|
| 585 |
+
crop_width = live_size[0]
|
| 586 |
+
crop_height = live_size[1]
|
| 587 |
+
elif live_size_ratio >= output_ratio:
|
| 588 |
+
# live_size is wider than what's needed, crop the sides
|
| 589 |
+
crop_width = output_ratio * live_size[1]
|
| 590 |
+
crop_height = live_size[1]
|
| 591 |
+
else:
|
| 592 |
+
# live_size is taller than what's needed, crop the top and bottom
|
| 593 |
+
crop_width = live_size[0]
|
| 594 |
+
crop_height = live_size[0] / output_ratio
|
| 595 |
+
|
| 596 |
+
# make the crop
|
| 597 |
+
crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
|
| 598 |
+
crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
|
| 599 |
+
|
| 600 |
+
crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
|
| 601 |
+
|
| 602 |
+
# resize the image and return it
|
| 603 |
+
return image.resize(size, method, box=crop)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def flip(image: Image.Image) -> Image.Image:
|
| 607 |
+
"""
|
| 608 |
+
Flip the image vertically (top to bottom).
|
| 609 |
+
|
| 610 |
+
:param image: The image to flip.
|
| 611 |
+
:return: An image.
|
| 612 |
+
"""
|
| 613 |
+
return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def grayscale(image: Image.Image) -> Image.Image:
|
| 617 |
+
"""
|
| 618 |
+
Convert the image to grayscale.
|
| 619 |
+
|
| 620 |
+
:param image: The image to convert.
|
| 621 |
+
:return: An image.
|
| 622 |
+
"""
|
| 623 |
+
return image.convert("L")
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def invert(image: Image.Image) -> Image.Image:
|
| 627 |
+
"""
|
| 628 |
+
Invert (negate) the image.
|
| 629 |
+
|
| 630 |
+
:param image: The image to invert.
|
| 631 |
+
:return: An image.
|
| 632 |
+
"""
|
| 633 |
+
lut = list(range(255, -1, -1))
|
| 634 |
+
return image.point(lut) if image.mode == "1" else _lut(image, lut)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def mirror(image: Image.Image) -> Image.Image:
|
| 638 |
+
"""
|
| 639 |
+
Flip image horizontally (left to right).
|
| 640 |
+
|
| 641 |
+
:param image: The image to mirror.
|
| 642 |
+
:return: An image.
|
| 643 |
+
"""
|
| 644 |
+
return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def posterize(image: Image.Image, bits: int) -> Image.Image:
|
| 648 |
+
"""
|
| 649 |
+
Reduce the number of bits for each color channel.
|
| 650 |
+
|
| 651 |
+
:param image: The image to posterize.
|
| 652 |
+
:param bits: The number of bits to keep for each channel (1-8).
|
| 653 |
+
:return: An image.
|
| 654 |
+
"""
|
| 655 |
+
mask = ~(2 ** (8 - bits) - 1)
|
| 656 |
+
lut = [i & mask for i in range(256)]
|
| 657 |
+
return _lut(image, lut)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
|
| 661 |
+
"""
|
| 662 |
+
Invert all pixel values above a threshold.
|
| 663 |
+
|
| 664 |
+
:param image: The image to solarize.
|
| 665 |
+
:param threshold: All pixels above this grayscale level are inverted.
|
| 666 |
+
:return: An image.
|
| 667 |
+
"""
|
| 668 |
+
lut = []
|
| 669 |
+
for i in range(256):
|
| 670 |
+
if i < threshold:
|
| 671 |
+
lut.append(i)
|
| 672 |
+
else:
|
| 673 |
+
lut.append(255 - i)
|
| 674 |
+
return _lut(image, lut)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@overload
|
| 678 |
+
def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
@overload
|
| 682 |
+
def exif_transpose(
|
| 683 |
+
image: Image.Image, *, in_place: Literal[False] = False
|
| 684 |
+
) -> Image.Image: ...
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
|
| 688 |
+
"""
|
| 689 |
+
If an image has an EXIF Orientation tag, other than 1, transpose the image
|
| 690 |
+
accordingly, and remove the orientation data.
|
| 691 |
+
|
| 692 |
+
:param image: The image to transpose.
|
| 693 |
+
:param in_place: Boolean. Keyword-only argument.
|
| 694 |
+
If ``True``, the original image is modified in-place, and ``None`` is returned.
|
| 695 |
+
If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
|
| 696 |
+
with the transposition applied. If there is no transposition, a copy of the
|
| 697 |
+
image will be returned.
|
| 698 |
+
"""
|
| 699 |
+
image.load()
|
| 700 |
+
image_exif = image.getexif()
|
| 701 |
+
orientation = image_exif.get(ExifTags.Base.Orientation, 1)
|
| 702 |
+
method = {
|
| 703 |
+
2: Image.Transpose.FLIP_LEFT_RIGHT,
|
| 704 |
+
3: Image.Transpose.ROTATE_180,
|
| 705 |
+
4: Image.Transpose.FLIP_TOP_BOTTOM,
|
| 706 |
+
5: Image.Transpose.TRANSPOSE,
|
| 707 |
+
6: Image.Transpose.ROTATE_270,
|
| 708 |
+
7: Image.Transpose.TRANSVERSE,
|
| 709 |
+
8: Image.Transpose.ROTATE_90,
|
| 710 |
+
}.get(orientation)
|
| 711 |
+
if method is not None:
|
| 712 |
+
if in_place:
|
| 713 |
+
image.im = image.im.transpose(method)
|
| 714 |
+
image._size = image.im.size
|
| 715 |
+
else:
|
| 716 |
+
transposed_image = image.transpose(method)
|
| 717 |
+
exif_image = image if in_place else transposed_image
|
| 718 |
+
|
| 719 |
+
exif = exif_image.getexif()
|
| 720 |
+
if ExifTags.Base.Orientation in exif:
|
| 721 |
+
del exif[ExifTags.Base.Orientation]
|
| 722 |
+
if "exif" in exif_image.info:
|
| 723 |
+
exif_image.info["exif"] = exif.tobytes()
|
| 724 |
+
elif "Raw profile type exif" in exif_image.info:
|
| 725 |
+
exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
|
| 726 |
+
for key in ("XML:com.adobe.xmp", "xmp"):
|
| 727 |
+
if key in exif_image.info:
|
| 728 |
+
for pattern in (
|
| 729 |
+
r'tiff:Orientation="([0-9])"',
|
| 730 |
+
r"<tiff:Orientation>([0-9])</tiff:Orientation>",
|
| 731 |
+
):
|
| 732 |
+
value = exif_image.info[key]
|
| 733 |
+
if isinstance(value, str):
|
| 734 |
+
value = re.sub(pattern, "", value)
|
| 735 |
+
elif isinstance(value, tuple):
|
| 736 |
+
value = tuple(
|
| 737 |
+
re.sub(pattern.encode(), b"", v) for v in value
|
| 738 |
+
)
|
| 739 |
+
else:
|
| 740 |
+
value = re.sub(pattern.encode(), b"", value)
|
| 741 |
+
exif_image.info[key] = value
|
| 742 |
+
if not in_place:
|
| 743 |
+
return transposed_image
|
| 744 |
+
elif not in_place:
|
| 745 |
+
return image.copy()
|
| 746 |
+
return None
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImagePalette.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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) // len(self.mode)
|
| 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 |
+
mode_len = len(self.mode)
|
| 172 |
+
if index * mode_len < len(self.palette):
|
| 173 |
+
self._palette = (
|
| 174 |
+
self._palette[: index * mode_len]
|
| 175 |
+
+ bytes(color)
|
| 176 |
+
+ self._palette[index * mode_len + mode_len :]
|
| 177 |
+
)
|
| 178 |
+
else:
|
| 179 |
+
self._palette += bytes(color)
|
| 180 |
+
self.dirty = 1
|
| 181 |
+
return index
|
| 182 |
+
else:
|
| 183 |
+
msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
|
| 184 |
+
raise ValueError(msg)
|
| 185 |
+
|
| 186 |
+
def save(self, fp: str | IO[str]) -> None:
|
| 187 |
+
"""Save palette to text file.
|
| 188 |
+
|
| 189 |
+
.. warning:: This method is experimental.
|
| 190 |
+
"""
|
| 191 |
+
if self.rawmode:
|
| 192 |
+
msg = "palette contains raw palette data"
|
| 193 |
+
raise ValueError(msg)
|
| 194 |
+
if isinstance(fp, str):
|
| 195 |
+
fp = open(fp, "w")
|
| 196 |
+
fp.write("# Palette\n")
|
| 197 |
+
fp.write(f"# Mode: {self.mode}\n")
|
| 198 |
+
for i in range(256):
|
| 199 |
+
fp.write(f"{i}")
|
| 200 |
+
for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
|
| 201 |
+
try:
|
| 202 |
+
fp.write(f" {self.palette[j]}")
|
| 203 |
+
except IndexError:
|
| 204 |
+
fp.write(" 0")
|
| 205 |
+
fp.write("\n")
|
| 206 |
+
fp.close()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# --------------------------------------------------------------------
|
| 210 |
+
# Internal
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
|
| 214 |
+
palette = ImagePalette()
|
| 215 |
+
palette.rawmode = rawmode
|
| 216 |
+
palette.palette = data
|
| 217 |
+
palette.dirty = 1
|
| 218 |
+
return palette
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# --------------------------------------------------------------------
|
| 222 |
+
# Factories
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def make_linear_lut(black: int, white: float) -> list[int]:
|
| 226 |
+
if black == 0:
|
| 227 |
+
return [int(white * i // 255) for i in range(256)]
|
| 228 |
+
|
| 229 |
+
msg = "unavailable when black is non-zero"
|
| 230 |
+
raise NotImplementedError(msg) # FIXME
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def make_gamma_lut(exp: float) -> list[int]:
|
| 234 |
+
return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def negative(mode: str = "RGB") -> ImagePalette:
|
| 238 |
+
palette = list(range(256 * len(mode)))
|
| 239 |
+
palette.reverse()
|
| 240 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def random(mode: str = "RGB") -> ImagePalette:
|
| 244 |
+
from random import randint
|
| 245 |
+
|
| 246 |
+
palette = [randint(0, 255) for _ in range(256 * len(mode))]
|
| 247 |
+
return ImagePalette(mode, palette)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def sepia(white: str = "#fff0c0") -> ImagePalette:
|
| 251 |
+
bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
|
| 252 |
+
return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def wedge(mode: str = "RGB") -> ImagePalette:
|
| 256 |
+
palette = list(range(256 * len(mode)))
|
| 257 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def load(filename: str) -> tuple[bytes, str]:
|
| 261 |
+
# FIXME: supports GIMP gradients only
|
| 262 |
+
|
| 263 |
+
with open(filename, "rb") as fp:
|
| 264 |
+
paletteHandlers: list[
|
| 265 |
+
type[
|
| 266 |
+
GimpPaletteFile.GimpPaletteFile
|
| 267 |
+
| GimpGradientFile.GimpGradientFile
|
| 268 |
+
| PaletteFile.PaletteFile
|
| 269 |
+
]
|
| 270 |
+
] = [
|
| 271 |
+
GimpPaletteFile.GimpPaletteFile,
|
| 272 |
+
GimpGradientFile.GimpGradientFile,
|
| 273 |
+
PaletteFile.PaletteFile,
|
| 274 |
+
]
|
| 275 |
+
for paletteHandler in paletteHandlers:
|
| 276 |
+
try:
|
| 277 |
+
fp.seek(0)
|
| 278 |
+
lut = paletteHandler(fp).getpalette()
|
| 279 |
+
if lut:
|
| 280 |
+
break
|
| 281 |
+
except (SyntaxError, ValueError):
|
| 282 |
+
pass
|
| 283 |
+
else:
|
| 284 |
+
msg = "cannot load palette"
|
| 285 |
+
raise OSError(msg)
|
| 286 |
+
|
| 287 |
+
return lut # data, rawmode
|
workspace/outputs/audit_venv/lib/python3.11/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
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageQt.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
# 2006-06-03 fl: created
|
| 9 |
+
# 2006-06-04 fl: inherit from QImage instead of wrapping it
|
| 10 |
+
# 2006-06-05 fl: removed toimage helper; move string support to ImageQt
|
| 11 |
+
# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 2006 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 2006 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import sys
|
| 21 |
+
from io import BytesIO
|
| 22 |
+
|
| 23 |
+
from . import Image
|
| 24 |
+
from ._util import is_path
|
| 25 |
+
|
| 26 |
+
TYPE_CHECKING = False
|
| 27 |
+
if TYPE_CHECKING:
|
| 28 |
+
from collections.abc import Callable
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
from . import ImageFile
|
| 32 |
+
|
| 33 |
+
QBuffer: type
|
| 34 |
+
|
| 35 |
+
qt_version: str | None
|
| 36 |
+
qt_versions = [
|
| 37 |
+
["6", "PyQt6"],
|
| 38 |
+
["side6", "PySide6"],
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
# If a version has already been imported, attempt it first
|
| 42 |
+
qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
|
| 43 |
+
for version, qt_module in qt_versions:
|
| 44 |
+
try:
|
| 45 |
+
qRgba: Callable[[int, int, int, int], int]
|
| 46 |
+
if qt_module == "PyQt6":
|
| 47 |
+
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
|
| 48 |
+
from PyQt6.QtGui import QImage, QPixmap, qRgba
|
| 49 |
+
elif qt_module == "PySide6":
|
| 50 |
+
from PySide6.QtCore import ( # type: ignore[assignment]
|
| 51 |
+
QBuffer,
|
| 52 |
+
QByteArray,
|
| 53 |
+
QIODevice,
|
| 54 |
+
)
|
| 55 |
+
from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment]
|
| 56 |
+
except (ImportError, RuntimeError):
|
| 57 |
+
continue
|
| 58 |
+
qt_is_installed = True
|
| 59 |
+
qt_version = version
|
| 60 |
+
break
|
| 61 |
+
else:
|
| 62 |
+
qt_is_installed = False
|
| 63 |
+
qt_version = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def rgb(r: int, g: int, b: int, a: int = 255) -> int:
|
| 67 |
+
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
|
| 68 |
+
# use qRgb to pack the colors, and then turn the resulting long
|
| 69 |
+
# into a negative integer with the same bitpattern.
|
| 70 |
+
return qRgba(r, g, b, a) & 0xFFFFFFFF
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:
|
| 74 |
+
"""
|
| 75 |
+
:param im: QImage or PIL ImageQt object
|
| 76 |
+
"""
|
| 77 |
+
buffer = QBuffer()
|
| 78 |
+
qt_openmode: object
|
| 79 |
+
if qt_version == "6":
|
| 80 |
+
try:
|
| 81 |
+
qt_openmode = getattr(QIODevice, "OpenModeFlag")
|
| 82 |
+
except AttributeError:
|
| 83 |
+
qt_openmode = getattr(QIODevice, "OpenMode")
|
| 84 |
+
else:
|
| 85 |
+
qt_openmode = QIODevice
|
| 86 |
+
buffer.open(getattr(qt_openmode, "ReadWrite"))
|
| 87 |
+
# preserve alpha channel with png
|
| 88 |
+
# otherwise ppm is more friendly with Image.open
|
| 89 |
+
if im.hasAlphaChannel():
|
| 90 |
+
im.save(buffer, "png")
|
| 91 |
+
else:
|
| 92 |
+
im.save(buffer, "ppm")
|
| 93 |
+
|
| 94 |
+
b = BytesIO()
|
| 95 |
+
b.write(buffer.data())
|
| 96 |
+
buffer.close()
|
| 97 |
+
b.seek(0)
|
| 98 |
+
|
| 99 |
+
return Image.open(b)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:
|
| 103 |
+
return fromqimage(im)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def align8to32(bytes: bytes, width: int, mode: str) -> bytes:
|
| 107 |
+
"""
|
| 108 |
+
converts each scanline of data from 8 bit to 32 bit aligned
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
|
| 112 |
+
|
| 113 |
+
# calculate bytes per line and the extra padding if needed
|
| 114 |
+
bits_per_line = bits_per_pixel * width
|
| 115 |
+
full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
|
| 116 |
+
bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
|
| 117 |
+
|
| 118 |
+
extra_padding = -bytes_per_line % 4
|
| 119 |
+
|
| 120 |
+
# already 32 bit aligned by luck
|
| 121 |
+
if not extra_padding:
|
| 122 |
+
return bytes
|
| 123 |
+
|
| 124 |
+
new_data = [
|
| 125 |
+
bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
|
| 126 |
+
for i in range(len(bytes) // bytes_per_line)
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
return b"".join(new_data)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:
|
| 133 |
+
data = None
|
| 134 |
+
colortable = None
|
| 135 |
+
exclusive_fp = False
|
| 136 |
+
|
| 137 |
+
# handle filename, if given instead of image name
|
| 138 |
+
if hasattr(im, "toUtf8"):
|
| 139 |
+
# FIXME - is this really the best way to do this?
|
| 140 |
+
im = str(im.toUtf8(), "utf-8")
|
| 141 |
+
if is_path(im):
|
| 142 |
+
im = Image.open(im)
|
| 143 |
+
exclusive_fp = True
|
| 144 |
+
assert isinstance(im, Image.Image)
|
| 145 |
+
|
| 146 |
+
qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage
|
| 147 |
+
if im.mode == "1":
|
| 148 |
+
format = getattr(qt_format, "Format_Mono")
|
| 149 |
+
elif im.mode == "L":
|
| 150 |
+
format = getattr(qt_format, "Format_Indexed8")
|
| 151 |
+
colortable = [rgb(i, i, i) for i in range(256)]
|
| 152 |
+
elif im.mode == "P":
|
| 153 |
+
format = getattr(qt_format, "Format_Indexed8")
|
| 154 |
+
palette = im.getpalette()
|
| 155 |
+
assert palette is not None
|
| 156 |
+
colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
|
| 157 |
+
elif im.mode == "RGB":
|
| 158 |
+
# Populate the 4th channel with 255
|
| 159 |
+
im = im.convert("RGBA")
|
| 160 |
+
|
| 161 |
+
data = im.tobytes("raw", "BGRA")
|
| 162 |
+
format = getattr(qt_format, "Format_RGB32")
|
| 163 |
+
elif im.mode == "RGBA":
|
| 164 |
+
data = im.tobytes("raw", "BGRA")
|
| 165 |
+
format = getattr(qt_format, "Format_ARGB32")
|
| 166 |
+
elif im.mode == "I;16":
|
| 167 |
+
im = im.point(lambda i: i * 256)
|
| 168 |
+
|
| 169 |
+
format = getattr(qt_format, "Format_Grayscale16")
|
| 170 |
+
else:
|
| 171 |
+
if exclusive_fp:
|
| 172 |
+
im.close()
|
| 173 |
+
msg = f"unsupported image mode {repr(im.mode)}"
|
| 174 |
+
raise ValueError(msg)
|
| 175 |
+
|
| 176 |
+
size = im.size
|
| 177 |
+
__data = data or align8to32(im.tobytes(), size[0], im.mode)
|
| 178 |
+
if exclusive_fp:
|
| 179 |
+
im.close()
|
| 180 |
+
return {"data": __data, "size": size, "format": format, "colortable": colortable}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if qt_is_installed:
|
| 184 |
+
|
| 185 |
+
class ImageQt(QImage):
|
| 186 |
+
def __init__(self, im: Image.Image | str | QByteArray) -> None:
|
| 187 |
+
"""
|
| 188 |
+
An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
|
| 189 |
+
class.
|
| 190 |
+
|
| 191 |
+
:param im: A PIL Image object, or a file name (given either as
|
| 192 |
+
Python string or a PyQt string object).
|
| 193 |
+
"""
|
| 194 |
+
im_data = _toqclass_helper(im)
|
| 195 |
+
# must keep a reference, or Qt will crash!
|
| 196 |
+
# All QImage constructors that take data operate on an existing
|
| 197 |
+
# buffer, so this buffer has to hang on for the life of the image.
|
| 198 |
+
# Fixes https://github.com/python-pillow/Pillow/issues/1370
|
| 199 |
+
self.__data = im_data["data"]
|
| 200 |
+
super().__init__(
|
| 201 |
+
self.__data,
|
| 202 |
+
im_data["size"][0],
|
| 203 |
+
im_data["size"][1],
|
| 204 |
+
im_data["format"],
|
| 205 |
+
)
|
| 206 |
+
if im_data["colortable"]:
|
| 207 |
+
self.setColorTable(im_data["colortable"])
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def toqimage(im: Image.Image | str | QByteArray) -> ImageQt:
|
| 211 |
+
return ImageQt(im)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:
|
| 215 |
+
qimage = toqimage(im)
|
| 216 |
+
pixmap = getattr(QPixmap, "fromImage")(qimage)
|
| 217 |
+
if qt_version == "6":
|
| 218 |
+
pixmap.detach()
|
| 219 |
+
return pixmap
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageSequence.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# sequence support classes
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1997-02-20 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 11 |
+
# Copyright (c) 1997 by Fredrik Lundh.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
##
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from . import Image
|
| 20 |
+
|
| 21 |
+
TYPE_CHECKING = False
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from collections.abc import Callable
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Iterator:
|
| 27 |
+
"""
|
| 28 |
+
This class implements an iterator object that can be used to loop
|
| 29 |
+
over an image sequence.
|
| 30 |
+
|
| 31 |
+
You can use the ``[]`` operator to access elements by index. This operator
|
| 32 |
+
will raise an :py:exc:`IndexError` if you try to access a nonexistent
|
| 33 |
+
frame.
|
| 34 |
+
|
| 35 |
+
:param im: An image object.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, im: Image.Image) -> None:
|
| 39 |
+
if not hasattr(im, "seek"):
|
| 40 |
+
msg = "im must have seek method"
|
| 41 |
+
raise AttributeError(msg)
|
| 42 |
+
self.im = im
|
| 43 |
+
self.position = getattr(self.im, "_min_frame", 0)
|
| 44 |
+
|
| 45 |
+
def __getitem__(self, ix: int) -> Image.Image:
|
| 46 |
+
try:
|
| 47 |
+
self.im.seek(ix)
|
| 48 |
+
return self.im
|
| 49 |
+
except EOFError as e:
|
| 50 |
+
msg = "end of sequence"
|
| 51 |
+
raise IndexError(msg) from e
|
| 52 |
+
|
| 53 |
+
def __iter__(self) -> Iterator:
|
| 54 |
+
return self
|
| 55 |
+
|
| 56 |
+
def __next__(self) -> Image.Image:
|
| 57 |
+
try:
|
| 58 |
+
self.im.seek(self.position)
|
| 59 |
+
self.position += 1
|
| 60 |
+
return self.im
|
| 61 |
+
except EOFError as e:
|
| 62 |
+
msg = "end of sequence"
|
| 63 |
+
raise StopIteration(msg) from e
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def all_frames(
|
| 67 |
+
im: Image.Image | list[Image.Image],
|
| 68 |
+
func: Callable[[Image.Image], Image.Image] | None = None,
|
| 69 |
+
) -> list[Image.Image]:
|
| 70 |
+
"""
|
| 71 |
+
Applies a given function to all frames in an image or a list of images.
|
| 72 |
+
The frames are returned as a list of separate images.
|
| 73 |
+
|
| 74 |
+
:param im: An image, or a list of images.
|
| 75 |
+
:param func: The function to apply to all of the image frames.
|
| 76 |
+
:returns: A list of images.
|
| 77 |
+
"""
|
| 78 |
+
if not isinstance(im, list):
|
| 79 |
+
im = [im]
|
| 80 |
+
|
| 81 |
+
ims = []
|
| 82 |
+
for imSequence in im:
|
| 83 |
+
current = imSequence.tell()
|
| 84 |
+
|
| 85 |
+
ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
|
| 86 |
+
|
| 87 |
+
imSequence.seek(current)
|
| 88 |
+
return [func(im) for im in ims] if func else ims
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageShow.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# im.show() drivers
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2008-04-06 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 2008.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import abc
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
from shlex import quote
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
|
| 26 |
+
_viewers = []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def register(viewer: type[Viewer] | Viewer, order: int = 1) -> None:
|
| 30 |
+
"""
|
| 31 |
+
The :py:func:`register` function is used to register additional viewers::
|
| 32 |
+
|
| 33 |
+
from PIL import ImageShow
|
| 34 |
+
ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
|
| 35 |
+
ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
|
| 36 |
+
ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
|
| 37 |
+
|
| 38 |
+
:param viewer: The viewer to be registered.
|
| 39 |
+
:param order:
|
| 40 |
+
Zero or a negative integer to prepend this viewer to the list,
|
| 41 |
+
a positive integer to append it.
|
| 42 |
+
"""
|
| 43 |
+
if isinstance(viewer, type) and issubclass(viewer, Viewer):
|
| 44 |
+
viewer = viewer()
|
| 45 |
+
if order > 0:
|
| 46 |
+
_viewers.append(viewer)
|
| 47 |
+
else:
|
| 48 |
+
_viewers.insert(0, viewer)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
|
| 52 |
+
r"""
|
| 53 |
+
Display a given image.
|
| 54 |
+
|
| 55 |
+
:param image: An image object.
|
| 56 |
+
:param title: Optional title. Not all viewers can display the title.
|
| 57 |
+
:param \**options: Additional viewer options.
|
| 58 |
+
:returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
|
| 59 |
+
"""
|
| 60 |
+
for viewer in _viewers:
|
| 61 |
+
if viewer.show(image, title=title, **options):
|
| 62 |
+
return True
|
| 63 |
+
return False
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Viewer:
|
| 67 |
+
"""Base class for viewers."""
|
| 68 |
+
|
| 69 |
+
# main api
|
| 70 |
+
|
| 71 |
+
def show(self, image: Image.Image, **options: Any) -> int:
|
| 72 |
+
"""
|
| 73 |
+
The main function for displaying an image.
|
| 74 |
+
Converts the given image to the target format and displays it.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
if not (
|
| 78 |
+
image.mode in ("1", "RGBA")
|
| 79 |
+
or (self.format == "PNG" and image.mode in ("I;16", "LA"))
|
| 80 |
+
):
|
| 81 |
+
base = Image.getmodebase(image.mode)
|
| 82 |
+
if image.mode != base:
|
| 83 |
+
image = image.convert(base)
|
| 84 |
+
|
| 85 |
+
return self.show_image(image, **options)
|
| 86 |
+
|
| 87 |
+
# hook methods
|
| 88 |
+
|
| 89 |
+
format: str | None = None
|
| 90 |
+
"""The format to convert the image into."""
|
| 91 |
+
options: dict[str, Any] = {}
|
| 92 |
+
"""Additional options used to convert the image."""
|
| 93 |
+
|
| 94 |
+
def get_format(self, image: Image.Image) -> str | None:
|
| 95 |
+
"""Return format name, or ``None`` to save as PGM/PPM."""
|
| 96 |
+
return self.format
|
| 97 |
+
|
| 98 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 99 |
+
"""
|
| 100 |
+
Returns the command used to display the file.
|
| 101 |
+
Not implemented in the base class.
|
| 102 |
+
"""
|
| 103 |
+
msg = "unavailable in base viewer"
|
| 104 |
+
raise NotImplementedError(msg)
|
| 105 |
+
|
| 106 |
+
def save_image(self, image: Image.Image) -> str:
|
| 107 |
+
"""Save to temporary file and return filename."""
|
| 108 |
+
return image._dump(format=self.get_format(image), **self.options)
|
| 109 |
+
|
| 110 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
| 111 |
+
"""Display the given image."""
|
| 112 |
+
return self.show_file(self.save_image(image), **options)
|
| 113 |
+
|
| 114 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 115 |
+
"""
|
| 116 |
+
Display given file.
|
| 117 |
+
"""
|
| 118 |
+
if not os.path.exists(path):
|
| 119 |
+
raise FileNotFoundError
|
| 120 |
+
os.system(self.get_command(path, **options)) # nosec
|
| 121 |
+
return 1
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# --------------------------------------------------------------------
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class WindowsViewer(Viewer):
|
| 128 |
+
"""The default viewer on Windows is the default system application for PNG files."""
|
| 129 |
+
|
| 130 |
+
format = "PNG"
|
| 131 |
+
options = {"compress_level": 1, "save_all": True}
|
| 132 |
+
|
| 133 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 134 |
+
return (
|
| 135 |
+
f'start "Pillow" /WAIT "{file}" '
|
| 136 |
+
"&& ping -n 4 127.0.0.1 >NUL "
|
| 137 |
+
f'&& del /f "{file}"'
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 141 |
+
"""
|
| 142 |
+
Display given file.
|
| 143 |
+
"""
|
| 144 |
+
if not os.path.exists(path):
|
| 145 |
+
raise FileNotFoundError
|
| 146 |
+
subprocess.Popen(
|
| 147 |
+
self.get_command(path, **options),
|
| 148 |
+
shell=True,
|
| 149 |
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
|
| 150 |
+
) # nosec
|
| 151 |
+
return 1
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if sys.platform == "win32":
|
| 155 |
+
register(WindowsViewer)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class MacViewer(Viewer):
|
| 159 |
+
"""The default viewer on macOS using ``Preview.app``."""
|
| 160 |
+
|
| 161 |
+
format = "PNG"
|
| 162 |
+
options = {"compress_level": 1, "save_all": True}
|
| 163 |
+
|
| 164 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 165 |
+
# on darwin open returns immediately resulting in the temp
|
| 166 |
+
# file removal while app is opening
|
| 167 |
+
command = "open -a Preview.app"
|
| 168 |
+
command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
|
| 169 |
+
return command
|
| 170 |
+
|
| 171 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 172 |
+
"""
|
| 173 |
+
Display given file.
|
| 174 |
+
"""
|
| 175 |
+
if not os.path.exists(path):
|
| 176 |
+
raise FileNotFoundError
|
| 177 |
+
subprocess.call(["open", "-a", "Preview.app", path])
|
| 178 |
+
|
| 179 |
+
pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
|
| 180 |
+
executable = (not pyinstaller and sys.executable) or shutil.which("python3")
|
| 181 |
+
if executable:
|
| 182 |
+
subprocess.Popen(
|
| 183 |
+
[
|
| 184 |
+
executable,
|
| 185 |
+
"-c",
|
| 186 |
+
"import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
|
| 187 |
+
path,
|
| 188 |
+
]
|
| 189 |
+
)
|
| 190 |
+
return 1
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if sys.platform == "darwin":
|
| 194 |
+
register(MacViewer)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class UnixViewer(abc.ABC, Viewer):
|
| 198 |
+
format = "PNG"
|
| 199 |
+
options = {"compress_level": 1, "save_all": True}
|
| 200 |
+
|
| 201 |
+
@abc.abstractmethod
|
| 202 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 206 |
+
command = self.get_command_ex(file, **options)[0]
|
| 207 |
+
return f"{command} {quote(file)}"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class XDGViewer(UnixViewer):
|
| 211 |
+
"""
|
| 212 |
+
The freedesktop.org ``xdg-open`` command.
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 216 |
+
command = executable = "xdg-open"
|
| 217 |
+
return command, executable
|
| 218 |
+
|
| 219 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 220 |
+
"""
|
| 221 |
+
Display given file.
|
| 222 |
+
"""
|
| 223 |
+
if not os.path.exists(path):
|
| 224 |
+
raise FileNotFoundError
|
| 225 |
+
subprocess.Popen(["xdg-open", path])
|
| 226 |
+
return 1
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class DisplayViewer(UnixViewer):
|
| 230 |
+
"""
|
| 231 |
+
The ImageMagick ``display`` command.
|
| 232 |
+
This viewer supports the ``title`` parameter.
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
def get_command_ex(
|
| 236 |
+
self, file: str, title: str | None = None, **options: Any
|
| 237 |
+
) -> tuple[str, str]:
|
| 238 |
+
command = executable = "display"
|
| 239 |
+
if title:
|
| 240 |
+
command += f" -title {quote(title)}"
|
| 241 |
+
return command, executable
|
| 242 |
+
|
| 243 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 244 |
+
"""
|
| 245 |
+
Display given file.
|
| 246 |
+
"""
|
| 247 |
+
if not os.path.exists(path):
|
| 248 |
+
raise FileNotFoundError
|
| 249 |
+
args = ["display"]
|
| 250 |
+
title = options.get("title")
|
| 251 |
+
if title:
|
| 252 |
+
args += ["-title", title]
|
| 253 |
+
args.append(path)
|
| 254 |
+
|
| 255 |
+
subprocess.Popen(args)
|
| 256 |
+
return 1
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class GmDisplayViewer(UnixViewer):
|
| 260 |
+
"""The GraphicsMagick ``gm display`` command."""
|
| 261 |
+
|
| 262 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 263 |
+
executable = "gm"
|
| 264 |
+
command = "gm display"
|
| 265 |
+
return command, executable
|
| 266 |
+
|
| 267 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 268 |
+
"""
|
| 269 |
+
Display given file.
|
| 270 |
+
"""
|
| 271 |
+
if not os.path.exists(path):
|
| 272 |
+
raise FileNotFoundError
|
| 273 |
+
subprocess.Popen(["gm", "display", path])
|
| 274 |
+
return 1
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class EogViewer(UnixViewer):
|
| 278 |
+
"""The GNOME Image Viewer ``eog`` command."""
|
| 279 |
+
|
| 280 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 281 |
+
executable = "eog"
|
| 282 |
+
command = "eog -n"
|
| 283 |
+
return command, executable
|
| 284 |
+
|
| 285 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 286 |
+
"""
|
| 287 |
+
Display given file.
|
| 288 |
+
"""
|
| 289 |
+
if not os.path.exists(path):
|
| 290 |
+
raise FileNotFoundError
|
| 291 |
+
subprocess.Popen(["eog", "-n", path])
|
| 292 |
+
return 1
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class XVViewer(UnixViewer):
|
| 296 |
+
"""
|
| 297 |
+
The X Viewer ``xv`` command.
|
| 298 |
+
This viewer supports the ``title`` parameter.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def get_command_ex(
|
| 302 |
+
self, file: str, title: str | None = None, **options: Any
|
| 303 |
+
) -> tuple[str, str]:
|
| 304 |
+
# note: xv is pretty outdated. most modern systems have
|
| 305 |
+
# imagemagick's display command instead.
|
| 306 |
+
command = executable = "xv"
|
| 307 |
+
if title:
|
| 308 |
+
command += f" -name {quote(title)}"
|
| 309 |
+
return command, executable
|
| 310 |
+
|
| 311 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 312 |
+
"""
|
| 313 |
+
Display given file.
|
| 314 |
+
"""
|
| 315 |
+
if not os.path.exists(path):
|
| 316 |
+
raise FileNotFoundError
|
| 317 |
+
args = ["xv"]
|
| 318 |
+
title = options.get("title")
|
| 319 |
+
if title:
|
| 320 |
+
args += ["-name", title]
|
| 321 |
+
args.append(path)
|
| 322 |
+
|
| 323 |
+
subprocess.Popen(args)
|
| 324 |
+
return 1
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if sys.platform not in ("win32", "darwin"): # unixoids
|
| 328 |
+
if shutil.which("xdg-open"):
|
| 329 |
+
register(XDGViewer)
|
| 330 |
+
if shutil.which("display"):
|
| 331 |
+
register(DisplayViewer)
|
| 332 |
+
if shutil.which("gm"):
|
| 333 |
+
register(GmDisplayViewer)
|
| 334 |
+
if shutil.which("eog"):
|
| 335 |
+
register(EogViewer)
|
| 336 |
+
if shutil.which("xv"):
|
| 337 |
+
register(XVViewer)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class IPythonViewer(Viewer):
|
| 341 |
+
"""The viewer for IPython frontends."""
|
| 342 |
+
|
| 343 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
| 344 |
+
ipython_display(image)
|
| 345 |
+
return 1
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
try:
|
| 349 |
+
from IPython.display import display as ipython_display
|
| 350 |
+
except ImportError:
|
| 351 |
+
pass
|
| 352 |
+
else:
|
| 353 |
+
register(IPythonViewer)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
if __name__ == "__main__":
|
| 357 |
+
if len(sys.argv) < 2:
|
| 358 |
+
print("Syntax: python3 ImageShow.py imagefile [title]")
|
| 359 |
+
sys.exit()
|
| 360 |
+
|
| 361 |
+
with Image.open(sys.argv[1]) as im:
|
| 362 |
+
print(show(im, *sys.argv[2:]))
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageStat.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 5 |
+
# global image statistics
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-05 fl Created
|
| 9 |
+
# 1997-05-21 fl Added mask; added rms, var, stddev attributes
|
| 10 |
+
# 1997-08-05 fl Added median
|
| 11 |
+
# 1998-07-05 hk Fixed integer overflow error
|
| 12 |
+
#
|
| 13 |
+
# Notes:
|
| 14 |
+
# This class shows how to implement delayed evaluation of attributes.
|
| 15 |
+
# To get a certain value, simply access the corresponding attribute.
|
| 16 |
+
# The __getattr__ dispatcher takes care of the rest.
|
| 17 |
+
#
|
| 18 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 19 |
+
# Copyright (c) Fredrik Lundh 1996-97.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import math
|
| 26 |
+
from functools import cached_property
|
| 27 |
+
|
| 28 |
+
from . import Image
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Stat:
|
| 32 |
+
def __init__(
|
| 33 |
+
self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
|
| 34 |
+
) -> None:
|
| 35 |
+
"""
|
| 36 |
+
Calculate statistics for the given image. If a mask is included,
|
| 37 |
+
only the regions covered by that mask are included in the
|
| 38 |
+
statistics. You can also pass in a previously calculated histogram.
|
| 39 |
+
|
| 40 |
+
:param image: A PIL image, or a precalculated histogram.
|
| 41 |
+
|
| 42 |
+
.. note::
|
| 43 |
+
|
| 44 |
+
For a PIL image, calculations rely on the
|
| 45 |
+
:py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
|
| 46 |
+
grouped into 256 bins, even if the image has more than 8 bits per
|
| 47 |
+
channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
|
| 48 |
+
``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
|
| 49 |
+
of more than 255.
|
| 50 |
+
|
| 51 |
+
:param mask: An optional mask.
|
| 52 |
+
"""
|
| 53 |
+
if isinstance(image_or_list, Image.Image):
|
| 54 |
+
self.h = image_or_list.histogram(mask)
|
| 55 |
+
elif isinstance(image_or_list, list):
|
| 56 |
+
self.h = image_or_list
|
| 57 |
+
else:
|
| 58 |
+
msg = "first argument must be image or list" # type: ignore[unreachable]
|
| 59 |
+
raise TypeError(msg)
|
| 60 |
+
self.bands = list(range(len(self.h) // 256))
|
| 61 |
+
|
| 62 |
+
@cached_property
|
| 63 |
+
def extrema(self) -> list[tuple[int, int]]:
|
| 64 |
+
"""
|
| 65 |
+
Min/max values for each band in the image.
|
| 66 |
+
|
| 67 |
+
.. note::
|
| 68 |
+
This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
|
| 69 |
+
simply returns the low and high bins used. This is correct for
|
| 70 |
+
images with 8 bits per channel, but fails for other modes such as
|
| 71 |
+
``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
|
| 72 |
+
return per-band extrema for the image. This is more correct and
|
| 73 |
+
efficient because, for non-8-bit modes, the histogram method uses
|
| 74 |
+
:py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def minmax(histogram: list[int]) -> tuple[int, int]:
|
| 78 |
+
res_min, res_max = 255, 0
|
| 79 |
+
for i in range(256):
|
| 80 |
+
if histogram[i]:
|
| 81 |
+
res_min = i
|
| 82 |
+
break
|
| 83 |
+
for i in range(255, -1, -1):
|
| 84 |
+
if histogram[i]:
|
| 85 |
+
res_max = i
|
| 86 |
+
break
|
| 87 |
+
return res_min, res_max
|
| 88 |
+
|
| 89 |
+
return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
|
| 90 |
+
|
| 91 |
+
@cached_property
|
| 92 |
+
def count(self) -> list[int]:
|
| 93 |
+
"""Total number of pixels for each band in the image."""
|
| 94 |
+
return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
|
| 95 |
+
|
| 96 |
+
@cached_property
|
| 97 |
+
def sum(self) -> list[float]:
|
| 98 |
+
"""Sum of all pixels for each band in the image."""
|
| 99 |
+
|
| 100 |
+
v = []
|
| 101 |
+
for i in range(0, len(self.h), 256):
|
| 102 |
+
layer_sum = 0.0
|
| 103 |
+
for j in range(256):
|
| 104 |
+
layer_sum += j * self.h[i + j]
|
| 105 |
+
v.append(layer_sum)
|
| 106 |
+
return v
|
| 107 |
+
|
| 108 |
+
@cached_property
|
| 109 |
+
def sum2(self) -> list[float]:
|
| 110 |
+
"""Squared sum of all pixels for each band in the image."""
|
| 111 |
+
|
| 112 |
+
v = []
|
| 113 |
+
for i in range(0, len(self.h), 256):
|
| 114 |
+
sum2 = 0.0
|
| 115 |
+
for j in range(256):
|
| 116 |
+
sum2 += (j**2) * float(self.h[i + j])
|
| 117 |
+
v.append(sum2)
|
| 118 |
+
return v
|
| 119 |
+
|
| 120 |
+
@cached_property
|
| 121 |
+
def mean(self) -> list[float]:
|
| 122 |
+
"""Average (arithmetic mean) pixel level for each band in the image."""
|
| 123 |
+
return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands]
|
| 124 |
+
|
| 125 |
+
@cached_property
|
| 126 |
+
def median(self) -> list[int]:
|
| 127 |
+
"""Median pixel level for each band in the image."""
|
| 128 |
+
|
| 129 |
+
v = []
|
| 130 |
+
for i in self.bands:
|
| 131 |
+
s = 0
|
| 132 |
+
half = self.count[i] // 2
|
| 133 |
+
b = i * 256
|
| 134 |
+
for j in range(256):
|
| 135 |
+
s = s + self.h[b + j]
|
| 136 |
+
if s > half:
|
| 137 |
+
break
|
| 138 |
+
v.append(j)
|
| 139 |
+
return v
|
| 140 |
+
|
| 141 |
+
@cached_property
|
| 142 |
+
def rms(self) -> list[float]:
|
| 143 |
+
"""RMS (root-mean-square) for each band in the image."""
|
| 144 |
+
return [
|
| 145 |
+
math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0
|
| 146 |
+
for i in self.bands
|
| 147 |
+
]
|
| 148 |
+
|
| 149 |
+
@cached_property
|
| 150 |
+
def var(self) -> list[float]:
|
| 151 |
+
"""Variance for each band in the image."""
|
| 152 |
+
return [
|
| 153 |
+
(
|
| 154 |
+
(self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
|
| 155 |
+
if self.count[i]
|
| 156 |
+
else 0
|
| 157 |
+
)
|
| 158 |
+
for i in self.bands
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
@cached_property
|
| 162 |
+
def stddev(self) -> list[float]:
|
| 163 |
+
"""Standard deviation for each band in the image."""
|
| 164 |
+
return [math.sqrt(self.var[i]) for i in self.bands]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
Global = Stat # compatibility
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageText.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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) -> float:
|
| 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 |
+
if isinstance(self.text, str):
|
| 134 |
+
multiline = "\n" in self.text
|
| 135 |
+
else:
|
| 136 |
+
multiline = b"\n" in self.text
|
| 137 |
+
if multiline:
|
| 138 |
+
msg = "can't measure length of multiline text"
|
| 139 |
+
raise ValueError(msg)
|
| 140 |
+
return self.font.getlength(
|
| 141 |
+
self.text,
|
| 142 |
+
self._get_fontmode(),
|
| 143 |
+
self.direction,
|
| 144 |
+
self.features,
|
| 145 |
+
self.language,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def _split(
|
| 149 |
+
self, xy: tuple[float, float], anchor: str | None, align: str
|
| 150 |
+
) -> list[tuple[tuple[float, float], str, str | bytes]]:
|
| 151 |
+
if anchor is None:
|
| 152 |
+
anchor = "lt" if self.direction == "ttb" else "la"
|
| 153 |
+
elif len(anchor) != 2:
|
| 154 |
+
msg = "anchor must be a 2 character string"
|
| 155 |
+
raise ValueError(msg)
|
| 156 |
+
|
| 157 |
+
lines = (
|
| 158 |
+
self.text.split("\n")
|
| 159 |
+
if isinstance(self.text, str)
|
| 160 |
+
else self.text.split(b"\n")
|
| 161 |
+
)
|
| 162 |
+
if len(lines) == 1:
|
| 163 |
+
return [(xy, anchor, self.text)]
|
| 164 |
+
|
| 165 |
+
if anchor[1] in "tb" and self.direction != "ttb":
|
| 166 |
+
msg = "anchor not supported for multiline text"
|
| 167 |
+
raise ValueError(msg)
|
| 168 |
+
|
| 169 |
+
fontmode = self._get_fontmode()
|
| 170 |
+
line_spacing = (
|
| 171 |
+
self.font.getbbox(
|
| 172 |
+
"A",
|
| 173 |
+
fontmode,
|
| 174 |
+
None,
|
| 175 |
+
self.features,
|
| 176 |
+
self.language,
|
| 177 |
+
self.stroke_width,
|
| 178 |
+
)[3]
|
| 179 |
+
+ self.stroke_width
|
| 180 |
+
+ self.spacing
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
top = xy[1]
|
| 184 |
+
parts = []
|
| 185 |
+
if self.direction == "ttb":
|
| 186 |
+
left = xy[0]
|
| 187 |
+
for line in lines:
|
| 188 |
+
parts.append(((left, top), anchor, line))
|
| 189 |
+
left += line_spacing
|
| 190 |
+
else:
|
| 191 |
+
widths = []
|
| 192 |
+
max_width: float = 0
|
| 193 |
+
for line in lines:
|
| 194 |
+
line_width = self.font.getlength(
|
| 195 |
+
line, fontmode, self.direction, self.features, self.language
|
| 196 |
+
)
|
| 197 |
+
widths.append(line_width)
|
| 198 |
+
max_width = max(max_width, line_width)
|
| 199 |
+
|
| 200 |
+
if anchor[1] == "m":
|
| 201 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
| 202 |
+
elif anchor[1] == "d":
|
| 203 |
+
top -= (len(lines) - 1) * line_spacing
|
| 204 |
+
|
| 205 |
+
idx = -1
|
| 206 |
+
for line in lines:
|
| 207 |
+
left = xy[0]
|
| 208 |
+
idx += 1
|
| 209 |
+
width_difference = max_width - widths[idx]
|
| 210 |
+
|
| 211 |
+
# align by align parameter
|
| 212 |
+
if align in ("left", "justify"):
|
| 213 |
+
pass
|
| 214 |
+
elif align == "center":
|
| 215 |
+
left += width_difference / 2.0
|
| 216 |
+
elif align == "right":
|
| 217 |
+
left += width_difference
|
| 218 |
+
else:
|
| 219 |
+
msg = 'align must be "left", "center", "right" or "justify"'
|
| 220 |
+
raise ValueError(msg)
|
| 221 |
+
|
| 222 |
+
if (
|
| 223 |
+
align == "justify"
|
| 224 |
+
and width_difference != 0
|
| 225 |
+
and idx != len(lines) - 1
|
| 226 |
+
):
|
| 227 |
+
words = (
|
| 228 |
+
line.split(" ") if isinstance(line, str) else line.split(b" ")
|
| 229 |
+
)
|
| 230 |
+
if len(words) > 1:
|
| 231 |
+
# align left by anchor
|
| 232 |
+
if anchor[0] == "m":
|
| 233 |
+
left -= max_width / 2.0
|
| 234 |
+
elif anchor[0] == "r":
|
| 235 |
+
left -= max_width
|
| 236 |
+
|
| 237 |
+
word_widths = [
|
| 238 |
+
self.font.getlength(
|
| 239 |
+
word,
|
| 240 |
+
fontmode,
|
| 241 |
+
self.direction,
|
| 242 |
+
self.features,
|
| 243 |
+
self.language,
|
| 244 |
+
)
|
| 245 |
+
for word in words
|
| 246 |
+
]
|
| 247 |
+
word_anchor = "l" + anchor[1]
|
| 248 |
+
width_difference = max_width - sum(word_widths)
|
| 249 |
+
i = 0
|
| 250 |
+
for word in words:
|
| 251 |
+
parts.append(((left, top), word_anchor, word))
|
| 252 |
+
left += word_widths[i] + width_difference / (len(words) - 1)
|
| 253 |
+
i += 1
|
| 254 |
+
top += line_spacing
|
| 255 |
+
continue
|
| 256 |
+
|
| 257 |
+
# align left by anchor
|
| 258 |
+
if anchor[0] == "m":
|
| 259 |
+
left -= width_difference / 2.0
|
| 260 |
+
elif anchor[0] == "r":
|
| 261 |
+
left -= width_difference
|
| 262 |
+
parts.append(((left, top), anchor, line))
|
| 263 |
+
top += line_spacing
|
| 264 |
+
|
| 265 |
+
return parts
|
| 266 |
+
|
| 267 |
+
def get_bbox(
|
| 268 |
+
self,
|
| 269 |
+
xy: tuple[float, float] = (0, 0),
|
| 270 |
+
anchor: str | None = None,
|
| 271 |
+
align: str = "left",
|
| 272 |
+
) -> tuple[float, float, float, float]:
|
| 273 |
+
"""
|
| 274 |
+
Returns bounding box (in pixels) of text.
|
| 275 |
+
|
| 276 |
+
Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel
|
| 277 |
+
precision. The bounding box includes extra margins for some fonts, e.g. italics
|
| 278 |
+
or accents.
|
| 279 |
+
|
| 280 |
+
:param xy: The anchor coordinates of the text.
|
| 281 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 282 |
+
the anchor to the text. The default alignment is top left,
|
| 283 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 284 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 285 |
+
:param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or
|
| 286 |
+
``"justify"`` determines the relative alignment of lines. Use the
|
| 287 |
+
``anchor`` parameter to specify the alignment to ``xy``.
|
| 288 |
+
|
| 289 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 290 |
+
"""
|
| 291 |
+
bbox: tuple[float, float, float, float] | None = None
|
| 292 |
+
fontmode = self._get_fontmode()
|
| 293 |
+
for xy, anchor, line in self._split(xy, anchor, align):
|
| 294 |
+
bbox_line = self.font.getbbox(
|
| 295 |
+
line,
|
| 296 |
+
fontmode,
|
| 297 |
+
self.direction,
|
| 298 |
+
self.features,
|
| 299 |
+
self.language,
|
| 300 |
+
self.stroke_width,
|
| 301 |
+
anchor,
|
| 302 |
+
)
|
| 303 |
+
bbox_line = (
|
| 304 |
+
bbox_line[0] + xy[0],
|
| 305 |
+
bbox_line[1] + xy[1],
|
| 306 |
+
bbox_line[2] + xy[0],
|
| 307 |
+
bbox_line[3] + xy[1],
|
| 308 |
+
)
|
| 309 |
+
if bbox is None:
|
| 310 |
+
bbox = bbox_line
|
| 311 |
+
else:
|
| 312 |
+
bbox = (
|
| 313 |
+
min(bbox[0], bbox_line[0]),
|
| 314 |
+
min(bbox[1], bbox_line[1]),
|
| 315 |
+
max(bbox[2], bbox_line[2]),
|
| 316 |
+
max(bbox[3], bbox_line[3]),
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
assert bbox is not None
|
| 320 |
+
return bbox
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageTk.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageTransform.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# transform wrappers
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2002-04-08 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2002 by Secret Labs AB
|
| 11 |
+
# Copyright (c) 2002 by Fredrik Lundh
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from collections.abc import Sequence
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
from . import Image
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Transform(Image.ImageTransformHandler):
|
| 24 |
+
"""Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
|
| 25 |
+
|
| 26 |
+
method: Image.Transform
|
| 27 |
+
|
| 28 |
+
def __init__(self, data: Sequence[Any]) -> None:
|
| 29 |
+
self.data = data
|
| 30 |
+
|
| 31 |
+
def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
|
| 32 |
+
return self.method, self.data
|
| 33 |
+
|
| 34 |
+
def transform(
|
| 35 |
+
self,
|
| 36 |
+
size: tuple[int, int],
|
| 37 |
+
image: Image.Image,
|
| 38 |
+
**options: Any,
|
| 39 |
+
) -> Image.Image:
|
| 40 |
+
"""Perform the transform. Called from :py:meth:`.Image.transform`."""
|
| 41 |
+
# can be overridden
|
| 42 |
+
method, data = self.getdata()
|
| 43 |
+
return image.transform(size, method, data, **options)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AffineTransform(Transform):
|
| 47 |
+
"""
|
| 48 |
+
Define an affine image transform.
|
| 49 |
+
|
| 50 |
+
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
|
| 51 |
+
two rows from the inverse of an affine transform matrix. For each pixel
|
| 52 |
+
(x, y) in the output image, the new value is taken from a position (a x +
|
| 53 |
+
b y + c, d x + e y + f) in the input image, rounded to nearest pixel.
|
| 54 |
+
|
| 55 |
+
This function can be used to scale, translate, rotate, and shear the
|
| 56 |
+
original image.
|
| 57 |
+
|
| 58 |
+
See :py:meth:`.Image.transform`
|
| 59 |
+
|
| 60 |
+
:param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
|
| 61 |
+
from the inverse of an affine transform matrix.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
method = Image.Transform.AFFINE
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class PerspectiveTransform(Transform):
|
| 68 |
+
"""
|
| 69 |
+
Define a perspective image transform.
|
| 70 |
+
|
| 71 |
+
This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
|
| 72 |
+
(x, y) in the output image, the new value is taken from a position
|
| 73 |
+
((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
|
| 74 |
+
the input image, rounded to nearest pixel.
|
| 75 |
+
|
| 76 |
+
This function can be used to scale, translate, rotate, and shear the
|
| 77 |
+
original image.
|
| 78 |
+
|
| 79 |
+
See :py:meth:`.Image.transform`
|
| 80 |
+
|
| 81 |
+
:param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
method = Image.Transform.PERSPECTIVE
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ExtentTransform(Transform):
|
| 88 |
+
"""
|
| 89 |
+
Define a transform to extract a subregion from an image.
|
| 90 |
+
|
| 91 |
+
Maps a rectangle (defined by two corners) from the image to a rectangle of
|
| 92 |
+
the given size. The resulting image will contain data sampled from between
|
| 93 |
+
the corners, such that (x0, y0) in the input image will end up at (0,0) in
|
| 94 |
+
the output image, and (x1, y1) at size.
|
| 95 |
+
|
| 96 |
+
This method can be used to crop, stretch, shrink, or mirror an arbitrary
|
| 97 |
+
rectangle in the current image. It is slightly slower than crop, but about
|
| 98 |
+
as fast as a corresponding resize operation.
|
| 99 |
+
|
| 100 |
+
See :py:meth:`.Image.transform`
|
| 101 |
+
|
| 102 |
+
:param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
|
| 103 |
+
input image's coordinate system. See :ref:`coordinate-system`.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
method = Image.Transform.EXTENT
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class QuadTransform(Transform):
|
| 110 |
+
"""
|
| 111 |
+
Define a quad image transform.
|
| 112 |
+
|
| 113 |
+
Maps a quadrilateral (a region defined by four corners) from the image to a
|
| 114 |
+
rectangle of the given size.
|
| 115 |
+
|
| 116 |
+
See :py:meth:`.Image.transform`
|
| 117 |
+
|
| 118 |
+
:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
|
| 119 |
+
upper left, lower left, lower right, and upper right corner of the
|
| 120 |
+
source quadrilateral.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
method = Image.Transform.QUAD
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class MeshTransform(Transform):
|
| 127 |
+
"""
|
| 128 |
+
Define a mesh image transform. A mesh transform consists of one or more
|
| 129 |
+
individual quad transforms.
|
| 130 |
+
|
| 131 |
+
See :py:meth:`.Image.transform`
|
| 132 |
+
|
| 133 |
+
:param data: A list of (bbox, quad) tuples.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
method = Image.Transform.MESH
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImageWin.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a Windows DIB display interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-05-20 fl Created
|
| 9 |
+
# 1996-09-20 fl Fixed subregion exposure
|
| 10 |
+
# 1997-09-21 fl Added draw primitive (for tzPrint)
|
| 11 |
+
# 2003-05-21 fl Added experimental Window/ImageWindow classes
|
| 12 |
+
# 2003-09-05 fl Added fromstring/tostring methods
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) Secret Labs AB 1997-2003.
|
| 15 |
+
# Copyright (c) Fredrik Lundh 1996-2003.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from . import Image
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class HDC:
|
| 25 |
+
"""
|
| 26 |
+
Wraps an HDC integer. The resulting object can be passed to the
|
| 27 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
| 28 |
+
methods.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, dc: int) -> None:
|
| 32 |
+
self.dc = dc
|
| 33 |
+
|
| 34 |
+
def __int__(self) -> int:
|
| 35 |
+
return self.dc
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class HWND:
|
| 39 |
+
"""
|
| 40 |
+
Wraps an HWND integer. The resulting object can be passed to the
|
| 41 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
| 42 |
+
methods, instead of a DC.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, wnd: int) -> None:
|
| 46 |
+
self.wnd = wnd
|
| 47 |
+
|
| 48 |
+
def __int__(self) -> int:
|
| 49 |
+
return self.wnd
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Dib:
|
| 53 |
+
"""
|
| 54 |
+
A Windows bitmap with the given mode and size. The mode can be one of "1",
|
| 55 |
+
"L", "P", or "RGB".
|
| 56 |
+
|
| 57 |
+
If the display requires a palette, this constructor creates a suitable
|
| 58 |
+
palette and associates it with the image. For an "L" image, 128 graylevels
|
| 59 |
+
are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
|
| 60 |
+
with 20 graylevels.
|
| 61 |
+
|
| 62 |
+
To make sure that palettes work properly under Windows, you must call the
|
| 63 |
+
``palette`` method upon certain events from Windows.
|
| 64 |
+
|
| 65 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
| 66 |
+
used, a size must also be given. The mode can be one of "1",
|
| 67 |
+
"L", "P", or "RGB".
|
| 68 |
+
:param size: If the first argument is a mode string, this
|
| 69 |
+
defines the size of the image.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self, image: Image.Image | str, size: tuple[int, int] | None = None
|
| 74 |
+
) -> None:
|
| 75 |
+
if isinstance(image, str):
|
| 76 |
+
mode = image
|
| 77 |
+
image = ""
|
| 78 |
+
if size is None:
|
| 79 |
+
msg = "If first argument is mode, size is required"
|
| 80 |
+
raise ValueError(msg)
|
| 81 |
+
else:
|
| 82 |
+
mode = image.mode
|
| 83 |
+
size = image.size
|
| 84 |
+
if mode not in ["1", "L", "P", "RGB"]:
|
| 85 |
+
mode = Image.getmodebase(mode)
|
| 86 |
+
self.image = Image.core.display(mode, size)
|
| 87 |
+
self.mode = mode
|
| 88 |
+
self.size = size
|
| 89 |
+
if image:
|
| 90 |
+
assert not isinstance(image, str)
|
| 91 |
+
self.paste(image)
|
| 92 |
+
|
| 93 |
+
def expose(self, handle: int | HDC | HWND) -> None:
|
| 94 |
+
"""
|
| 95 |
+
Copy the bitmap contents to a device context.
|
| 96 |
+
|
| 97 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
| 98 |
+
HDC or HWND instance. In PythonWin, you can use
|
| 99 |
+
``CDC.GetHandleAttrib()`` to get a suitable handle.
|
| 100 |
+
"""
|
| 101 |
+
handle_int = int(handle)
|
| 102 |
+
if isinstance(handle, HWND):
|
| 103 |
+
dc = self.image.getdc(handle_int)
|
| 104 |
+
try:
|
| 105 |
+
self.image.expose(dc)
|
| 106 |
+
finally:
|
| 107 |
+
self.image.releasedc(handle_int, dc)
|
| 108 |
+
else:
|
| 109 |
+
self.image.expose(handle_int)
|
| 110 |
+
|
| 111 |
+
def draw(
|
| 112 |
+
self,
|
| 113 |
+
handle: int | HDC | HWND,
|
| 114 |
+
dst: tuple[int, int, int, int],
|
| 115 |
+
src: tuple[int, int, int, int] | None = None,
|
| 116 |
+
) -> None:
|
| 117 |
+
"""
|
| 118 |
+
Same as expose, but allows you to specify where to draw the image, and
|
| 119 |
+
what part of it to draw.
|
| 120 |
+
|
| 121 |
+
The destination and source areas are given as 4-tuple rectangles. If
|
| 122 |
+
the source is omitted, the entire image is copied. If the source and
|
| 123 |
+
the destination have different sizes, the image is resized as
|
| 124 |
+
necessary.
|
| 125 |
+
"""
|
| 126 |
+
if src is None:
|
| 127 |
+
src = (0, 0) + self.size
|
| 128 |
+
handle_int = int(handle)
|
| 129 |
+
if isinstance(handle, HWND):
|
| 130 |
+
dc = self.image.getdc(handle_int)
|
| 131 |
+
try:
|
| 132 |
+
self.image.draw(dc, dst, src)
|
| 133 |
+
finally:
|
| 134 |
+
self.image.releasedc(handle_int, dc)
|
| 135 |
+
else:
|
| 136 |
+
self.image.draw(handle_int, dst, src)
|
| 137 |
+
|
| 138 |
+
def query_palette(self, handle: int | HDC | HWND) -> int:
|
| 139 |
+
"""
|
| 140 |
+
Installs the palette associated with the image in the given device
|
| 141 |
+
context.
|
| 142 |
+
|
| 143 |
+
This method should be called upon **QUERYNEWPALETTE** and
|
| 144 |
+
**PALETTECHANGED** events from Windows. If this method returns a
|
| 145 |
+
non-zero value, one or more display palette entries were changed, and
|
| 146 |
+
the image should be redrawn.
|
| 147 |
+
|
| 148 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
| 149 |
+
HDC or HWND instance.
|
| 150 |
+
:return: The number of entries that were changed (if one or more entries,
|
| 151 |
+
this indicates that the image should be redrawn).
|
| 152 |
+
"""
|
| 153 |
+
handle_int = int(handle)
|
| 154 |
+
if isinstance(handle, HWND):
|
| 155 |
+
handle = self.image.getdc(handle_int)
|
| 156 |
+
try:
|
| 157 |
+
result = self.image.query_palette(handle)
|
| 158 |
+
finally:
|
| 159 |
+
self.image.releasedc(handle, handle)
|
| 160 |
+
else:
|
| 161 |
+
result = self.image.query_palette(handle_int)
|
| 162 |
+
return result
|
| 163 |
+
|
| 164 |
+
def paste(
|
| 165 |
+
self, im: Image.Image, box: tuple[int, int, int, int] | None = None
|
| 166 |
+
) -> None:
|
| 167 |
+
"""
|
| 168 |
+
Paste a PIL image into the bitmap image.
|
| 169 |
+
|
| 170 |
+
:param im: A PIL image. The size must match the target region.
|
| 171 |
+
If the mode does not match, the image is converted to the
|
| 172 |
+
mode of the bitmap image.
|
| 173 |
+
:param box: A 4-tuple defining the left, upper, right, and
|
| 174 |
+
lower pixel coordinate. See :ref:`coordinate-system`. If
|
| 175 |
+
None is given instead of a tuple, all of the image is
|
| 176 |
+
assumed.
|
| 177 |
+
"""
|
| 178 |
+
im.load()
|
| 179 |
+
if self.mode != im.mode:
|
| 180 |
+
im = im.convert(self.mode)
|
| 181 |
+
if box:
|
| 182 |
+
self.image.paste(im.im, box)
|
| 183 |
+
else:
|
| 184 |
+
self.image.paste(im.im)
|
| 185 |
+
|
| 186 |
+
def frombytes(self, buffer: bytes) -> None:
|
| 187 |
+
"""
|
| 188 |
+
Load display memory contents from byte data.
|
| 189 |
+
|
| 190 |
+
:param buffer: A buffer containing display data (usually
|
| 191 |
+
data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
|
| 192 |
+
"""
|
| 193 |
+
self.image.frombytes(buffer)
|
| 194 |
+
|
| 195 |
+
def tobytes(self) -> bytes:
|
| 196 |
+
"""
|
| 197 |
+
Copy display memory contents to bytes object.
|
| 198 |
+
|
| 199 |
+
:return: A bytes object containing display data.
|
| 200 |
+
"""
|
| 201 |
+
return self.image.tobytes()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class Window:
|
| 205 |
+
"""Create a Window with the given title size."""
|
| 206 |
+
|
| 207 |
+
def __init__(
|
| 208 |
+
self, title: str = "PIL", width: int | None = None, height: int | None = None
|
| 209 |
+
) -> None:
|
| 210 |
+
self.hwnd = Image.core.createwindow(
|
| 211 |
+
title, self.__dispatcher, width or 0, height or 0
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def __dispatcher(self, action: str, *args: int) -> None:
|
| 215 |
+
getattr(self, f"ui_handle_{action}")(*args)
|
| 216 |
+
|
| 217 |
+
def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None:
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
def ui_handle_destroy(self) -> None:
|
| 224 |
+
pass
|
| 225 |
+
|
| 226 |
+
def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
|
| 227 |
+
pass
|
| 228 |
+
|
| 229 |
+
def ui_handle_resize(self, width: int, height: int) -> None:
|
| 230 |
+
pass
|
| 231 |
+
|
| 232 |
+
def mainloop(self) -> None:
|
| 233 |
+
Image.core.eventloop()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class ImageWindow(Window):
|
| 237 |
+
"""Create an image window which displays the given image."""
|
| 238 |
+
|
| 239 |
+
def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None:
|
| 240 |
+
if not isinstance(image, Dib):
|
| 241 |
+
image = Dib(image)
|
| 242 |
+
self.image = image
|
| 243 |
+
width, height = image.size
|
| 244 |
+
super().__init__(title, width=width, height=height)
|
| 245 |
+
|
| 246 |
+
def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
|
| 247 |
+
self.image.draw(dc, (x0, y0, x1, y1))
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# IM Tools support for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1996-05-27 fl Created (read 8-bit images only)
|
| 9 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
|
| 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
|
| 21 |
+
|
| 22 |
+
#
|
| 23 |
+
# --------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
##
|
| 29 |
+
# Image plugin for IM Tools images.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ImtImageFile(ImageFile.ImageFile):
|
| 33 |
+
format = "IMT"
|
| 34 |
+
format_description = "IM Tools"
|
| 35 |
+
|
| 36 |
+
def _open(self) -> None:
|
| 37 |
+
# Quick rejection: if there's not a LF among the first
|
| 38 |
+
# 100 bytes, this is (probably) not a text header.
|
| 39 |
+
|
| 40 |
+
assert self.fp is not None
|
| 41 |
+
|
| 42 |
+
buffer = self.fp.read(100)
|
| 43 |
+
if b"\n" not in buffer:
|
| 44 |
+
msg = "not an IM file"
|
| 45 |
+
raise SyntaxError(msg)
|
| 46 |
+
|
| 47 |
+
xsize = ysize = 0
|
| 48 |
+
|
| 49 |
+
while True:
|
| 50 |
+
if buffer:
|
| 51 |
+
s = buffer[:1]
|
| 52 |
+
buffer = buffer[1:]
|
| 53 |
+
else:
|
| 54 |
+
s = self.fp.read(1)
|
| 55 |
+
if not s:
|
| 56 |
+
break
|
| 57 |
+
|
| 58 |
+
if s == b"\x0c":
|
| 59 |
+
# image data begins
|
| 60 |
+
self.tile = [
|
| 61 |
+
ImageFile._Tile(
|
| 62 |
+
"raw",
|
| 63 |
+
(0, 0) + self.size,
|
| 64 |
+
self.fp.tell() - len(buffer),
|
| 65 |
+
self.mode,
|
| 66 |
+
)
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
break
|
| 70 |
+
|
| 71 |
+
else:
|
| 72 |
+
# read key/value pair
|
| 73 |
+
if b"\n" not in buffer:
|
| 74 |
+
buffer += self.fp.read(100)
|
| 75 |
+
lines = buffer.split(b"\n")
|
| 76 |
+
s += lines.pop(0)
|
| 77 |
+
buffer = b"\n".join(lines)
|
| 78 |
+
if len(s) == 1 or len(s) > 100:
|
| 79 |
+
break
|
| 80 |
+
if s[0] == ord(b"*"):
|
| 81 |
+
continue # comment
|
| 82 |
+
|
| 83 |
+
m = field.match(s)
|
| 84 |
+
if not m:
|
| 85 |
+
break
|
| 86 |
+
k, v = m.group(1, 2)
|
| 87 |
+
if k == b"width":
|
| 88 |
+
xsize = int(v)
|
| 89 |
+
self._size = xsize, ysize
|
| 90 |
+
elif k == b"height":
|
| 91 |
+
ysize = int(v)
|
| 92 |
+
self._size = xsize, ysize
|
| 93 |
+
elif k == b"pixel" and v == b"n8":
|
| 94 |
+
self._mode = "L"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
#
|
| 98 |
+
# --------------------------------------------------------------------
|
| 99 |
+
|
| 100 |
+
Image.register_open(ImtImageFile.format, ImtImageFile)
|
| 101 |
+
|
| 102 |
+
#
|
| 103 |
+
# no extension registered (".im" is simply too common)
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/IptcImagePlugin.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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added getiptcinfo helper
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997-2002.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1995.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
from typing import cast
|
| 21 |
+
|
| 22 |
+
from . import Image, ImageFile
|
| 23 |
+
from ._binary import i16be as i16
|
| 24 |
+
from ._binary import i32be as i32
|
| 25 |
+
|
| 26 |
+
COMPRESSION = {1: "raw", 5: "jpeg"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
#
|
| 30 |
+
# Helpers
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _i(c: bytes) -> int:
|
| 34 |
+
return i32((b"\0\0\0\0" + c)[-4:])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
##
|
| 38 |
+
# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
|
| 39 |
+
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class IptcImageFile(ImageFile.ImageFile):
|
| 43 |
+
format = "IPTC"
|
| 44 |
+
format_description = "IPTC/NAA"
|
| 45 |
+
|
| 46 |
+
def getint(self, key: tuple[int, int]) -> int:
|
| 47 |
+
return _i(self.info[key])
|
| 48 |
+
|
| 49 |
+
def field(self) -> tuple[tuple[int, int] | None, int]:
|
| 50 |
+
#
|
| 51 |
+
# get a IPTC field header
|
| 52 |
+
assert self.fp is not None
|
| 53 |
+
s = self.fp.read(5)
|
| 54 |
+
if not s.strip(b"\x00"):
|
| 55 |
+
return None, 0
|
| 56 |
+
|
| 57 |
+
tag = s[1], s[2]
|
| 58 |
+
|
| 59 |
+
# syntax
|
| 60 |
+
if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:
|
| 61 |
+
msg = "invalid IPTC/NAA file"
|
| 62 |
+
raise SyntaxError(msg)
|
| 63 |
+
|
| 64 |
+
# field size
|
| 65 |
+
size = s[3]
|
| 66 |
+
if size > 132:
|
| 67 |
+
msg = "illegal field length in IPTC/NAA file"
|
| 68 |
+
raise OSError(msg)
|
| 69 |
+
elif size == 128:
|
| 70 |
+
size = 0
|
| 71 |
+
elif size > 128:
|
| 72 |
+
size = _i(self.fp.read(size - 128))
|
| 73 |
+
else:
|
| 74 |
+
size = i16(s, 3)
|
| 75 |
+
|
| 76 |
+
return tag, size
|
| 77 |
+
|
| 78 |
+
def _open(self) -> None:
|
| 79 |
+
# load descriptive fields
|
| 80 |
+
assert self.fp is not None
|
| 81 |
+
while True:
|
| 82 |
+
offset = self.fp.tell()
|
| 83 |
+
tag, size = self.field()
|
| 84 |
+
if not tag or tag == (8, 10):
|
| 85 |
+
break
|
| 86 |
+
if size:
|
| 87 |
+
tagdata = self.fp.read(size)
|
| 88 |
+
else:
|
| 89 |
+
tagdata = None
|
| 90 |
+
if tag in self.info:
|
| 91 |
+
if isinstance(self.info[tag], list):
|
| 92 |
+
self.info[tag].append(tagdata)
|
| 93 |
+
else:
|
| 94 |
+
self.info[tag] = [self.info[tag], tagdata]
|
| 95 |
+
else:
|
| 96 |
+
self.info[tag] = tagdata
|
| 97 |
+
|
| 98 |
+
# mode
|
| 99 |
+
layers = self.info[(3, 60)][0]
|
| 100 |
+
component = self.info[(3, 60)][1]
|
| 101 |
+
if layers == 1 and not component:
|
| 102 |
+
self._mode = "L"
|
| 103 |
+
band = None
|
| 104 |
+
else:
|
| 105 |
+
if layers == 3 and component:
|
| 106 |
+
self._mode = "RGB"
|
| 107 |
+
elif layers == 4 and component:
|
| 108 |
+
self._mode = "CMYK"
|
| 109 |
+
if (3, 65) in self.info:
|
| 110 |
+
band = self.info[(3, 65)][0] - 1
|
| 111 |
+
else:
|
| 112 |
+
band = 0
|
| 113 |
+
|
| 114 |
+
# size
|
| 115 |
+
self._size = self.getint((3, 20)), self.getint((3, 30))
|
| 116 |
+
|
| 117 |
+
# compression
|
| 118 |
+
try:
|
| 119 |
+
compression = COMPRESSION[self.getint((3, 120))]
|
| 120 |
+
except KeyError as e:
|
| 121 |
+
msg = "Unknown IPTC image compression"
|
| 122 |
+
raise OSError(msg) from e
|
| 123 |
+
|
| 124 |
+
# tile
|
| 125 |
+
if tag == (8, 10):
|
| 126 |
+
self.tile = [
|
| 127 |
+
ImageFile._Tile("iptc", (0, 0) + self.size, offset, (compression, band))
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 131 |
+
if self.tile:
|
| 132 |
+
args = self.tile[0].args
|
| 133 |
+
assert isinstance(args, tuple)
|
| 134 |
+
compression, band = args
|
| 135 |
+
|
| 136 |
+
assert self.fp is not None
|
| 137 |
+
self.fp.seek(self.tile[0].offset)
|
| 138 |
+
|
| 139 |
+
# Copy image data to temporary file
|
| 140 |
+
o = BytesIO()
|
| 141 |
+
if compression == "raw":
|
| 142 |
+
# To simplify access to the extracted file,
|
| 143 |
+
# prepend a PPM header
|
| 144 |
+
o.write(b"P5\n%d %d\n255\n" % self.size)
|
| 145 |
+
while True:
|
| 146 |
+
type, size = self.field()
|
| 147 |
+
if type != (8, 10):
|
| 148 |
+
break
|
| 149 |
+
while size > 0:
|
| 150 |
+
s = self.fp.read(min(size, 8192))
|
| 151 |
+
if not s:
|
| 152 |
+
break
|
| 153 |
+
o.write(s)
|
| 154 |
+
size -= len(s)
|
| 155 |
+
|
| 156 |
+
with Image.open(o) as _im:
|
| 157 |
+
if band is not None:
|
| 158 |
+
bands = [Image.new("L", _im.size)] * Image.getmodebands(self.mode)
|
| 159 |
+
bands[band] = _im
|
| 160 |
+
im = Image.merge(self.mode, bands)
|
| 161 |
+
else:
|
| 162 |
+
im = _im
|
| 163 |
+
im.load()
|
| 164 |
+
self.im = im.im
|
| 165 |
+
self.tile = []
|
| 166 |
+
return ImageFile.ImageFile.load(self)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
Image.register_open(IptcImageFile.format, IptcImageFile)
|
| 170 |
+
|
| 171 |
+
Image.register_extension(IptcImageFile.format, ".iim")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def getiptcinfo(
|
| 175 |
+
im: ImageFile.ImageFile,
|
| 176 |
+
) -> dict[tuple[int, int], bytes | list[bytes]] | None:
|
| 177 |
+
"""
|
| 178 |
+
Get IPTC information from TIFF, JPEG, or IPTC file.
|
| 179 |
+
|
| 180 |
+
:param im: An image containing IPTC data.
|
| 181 |
+
:returns: A dictionary containing IPTC information, or None if
|
| 182 |
+
no IPTC information block was found.
|
| 183 |
+
"""
|
| 184 |
+
from . import JpegImagePlugin, TiffImagePlugin
|
| 185 |
+
|
| 186 |
+
data = None
|
| 187 |
+
|
| 188 |
+
info: dict[tuple[int, int], bytes | list[bytes]] = {}
|
| 189 |
+
if isinstance(im, IptcImageFile):
|
| 190 |
+
# return info dictionary right away
|
| 191 |
+
for k, v in im.info.items():
|
| 192 |
+
if isinstance(k, tuple):
|
| 193 |
+
info[k] = v
|
| 194 |
+
return info
|
| 195 |
+
|
| 196 |
+
elif isinstance(im, JpegImagePlugin.JpegImageFile):
|
| 197 |
+
# extract the IPTC/NAA resource
|
| 198 |
+
photoshop = im.info.get("photoshop")
|
| 199 |
+
if photoshop:
|
| 200 |
+
data = photoshop.get(0x0404)
|
| 201 |
+
|
| 202 |
+
elif isinstance(im, TiffImagePlugin.TiffImageFile):
|
| 203 |
+
# get raw data from the IPTC/NAA tag (PhotoShop tags the data
|
| 204 |
+
# as 4-byte integers, so we cannot use the get method...)
|
| 205 |
+
try:
|
| 206 |
+
data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
|
| 207 |
+
except KeyError:
|
| 208 |
+
pass
|
| 209 |
+
|
| 210 |
+
if data is None:
|
| 211 |
+
return None # no properties
|
| 212 |
+
|
| 213 |
+
# create an IptcImagePlugin object without initializing it
|
| 214 |
+
class FakeImage:
|
| 215 |
+
pass
|
| 216 |
+
|
| 217 |
+
fake_im = FakeImage()
|
| 218 |
+
fake_im.__class__ = IptcImageFile # type: ignore[assignment]
|
| 219 |
+
iptc_im = cast(IptcImageFile, fake_im)
|
| 220 |
+
|
| 221 |
+
# parse the IPTC information chunk
|
| 222 |
+
iptc_im.info = {}
|
| 223 |
+
iptc_im.fp = BytesIO(data)
|
| 224 |
+
|
| 225 |
+
try:
|
| 226 |
+
iptc_im._open()
|
| 227 |
+
except (IndexError, KeyError):
|
| 228 |
+
pass # expected failure
|
| 229 |
+
|
| 230 |
+
for k, v in iptc_im.info.items():
|
| 231 |
+
if isinstance(k, tuple):
|
| 232 |
+
info[k] = v
|
| 233 |
+
return info
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# JPEG2000 file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2014-03-12 ajh Created
|
| 9 |
+
# 2021-06-30 rogermb Extract dpi information from the 'resc' header box
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2014 Coriolis Systems Limited
|
| 12 |
+
# Copyright (c) 2014 Alastair Houghton
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
import os
|
| 20 |
+
import struct
|
| 21 |
+
from typing import cast
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile, ImagePalette, _binary
|
| 24 |
+
|
| 25 |
+
TYPE_CHECKING = False
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from collections.abc import Callable
|
| 28 |
+
from typing import IO
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BoxReader:
|
| 32 |
+
"""
|
| 33 |
+
A small helper class to read fields stored in JPEG2000 header boxes
|
| 34 |
+
and to easily step into and read sub-boxes.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, fp: IO[bytes], length: int = -1) -> None:
|
| 38 |
+
self.fp = fp
|
| 39 |
+
self.has_length = length >= 0
|
| 40 |
+
self.length = length
|
| 41 |
+
self.remaining_in_box = -1
|
| 42 |
+
|
| 43 |
+
def _can_read(self, num_bytes: int) -> bool:
|
| 44 |
+
if self.has_length and self.fp.tell() + num_bytes > self.length:
|
| 45 |
+
# Outside box: ensure we don't read past the known file length
|
| 46 |
+
return False
|
| 47 |
+
if self.remaining_in_box >= 0:
|
| 48 |
+
# Inside box contents: ensure read does not go past box boundaries
|
| 49 |
+
return num_bytes <= self.remaining_in_box
|
| 50 |
+
else:
|
| 51 |
+
return True # No length known, just read
|
| 52 |
+
|
| 53 |
+
def _read_bytes(self, num_bytes: int) -> bytes:
|
| 54 |
+
if not self._can_read(num_bytes):
|
| 55 |
+
msg = "Not enough data in header"
|
| 56 |
+
raise SyntaxError(msg)
|
| 57 |
+
|
| 58 |
+
data = self.fp.read(num_bytes)
|
| 59 |
+
if len(data) < num_bytes:
|
| 60 |
+
msg = f"Expected to read {num_bytes} bytes but only got {len(data)}."
|
| 61 |
+
raise OSError(msg)
|
| 62 |
+
|
| 63 |
+
if self.remaining_in_box > 0:
|
| 64 |
+
self.remaining_in_box -= num_bytes
|
| 65 |
+
return data
|
| 66 |
+
|
| 67 |
+
def read_fields(self, field_format: str) -> tuple[int | bytes, ...]:
|
| 68 |
+
size = struct.calcsize(field_format)
|
| 69 |
+
data = self._read_bytes(size)
|
| 70 |
+
return struct.unpack(field_format, data)
|
| 71 |
+
|
| 72 |
+
def read_boxes(self) -> BoxReader:
|
| 73 |
+
size = self.remaining_in_box
|
| 74 |
+
data = self._read_bytes(size)
|
| 75 |
+
return BoxReader(io.BytesIO(data), size)
|
| 76 |
+
|
| 77 |
+
def has_next_box(self) -> bool:
|
| 78 |
+
if self.has_length:
|
| 79 |
+
return self.fp.tell() + self.remaining_in_box < self.length
|
| 80 |
+
else:
|
| 81 |
+
return True
|
| 82 |
+
|
| 83 |
+
def next_box_type(self) -> bytes:
|
| 84 |
+
# Skip the rest of the box if it has not been read
|
| 85 |
+
if self.remaining_in_box > 0:
|
| 86 |
+
self.fp.seek(self.remaining_in_box, os.SEEK_CUR)
|
| 87 |
+
self.remaining_in_box = -1
|
| 88 |
+
|
| 89 |
+
# Read the length and type of the next box
|
| 90 |
+
lbox, tbox = cast(tuple[int, bytes], self.read_fields(">I4s"))
|
| 91 |
+
if lbox == 1:
|
| 92 |
+
lbox = cast(int, self.read_fields(">Q")[0])
|
| 93 |
+
hlen = 16
|
| 94 |
+
else:
|
| 95 |
+
hlen = 8
|
| 96 |
+
|
| 97 |
+
if lbox < hlen or not self._can_read(lbox - hlen):
|
| 98 |
+
msg = "Invalid header length"
|
| 99 |
+
raise SyntaxError(msg)
|
| 100 |
+
|
| 101 |
+
self.remaining_in_box = lbox - hlen
|
| 102 |
+
return tbox
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]:
|
| 106 |
+
"""Parse the JPEG 2000 codestream to extract the size and component
|
| 107 |
+
count from the SIZ marker segment, returning a PIL (size, mode) tuple."""
|
| 108 |
+
|
| 109 |
+
hdr = fp.read(2)
|
| 110 |
+
lsiz = _binary.i16be(hdr)
|
| 111 |
+
siz = hdr + fp.read(lsiz - 2)
|
| 112 |
+
lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(
|
| 113 |
+
">HHIIIIIIIIH", siz
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
size = (xsiz - xosiz, ysiz - yosiz)
|
| 117 |
+
if csiz == 1:
|
| 118 |
+
ssiz = struct.unpack_from(">B", siz, 38)
|
| 119 |
+
if (ssiz[0] & 0x7F) + 1 > 8:
|
| 120 |
+
mode = "I;16"
|
| 121 |
+
else:
|
| 122 |
+
mode = "L"
|
| 123 |
+
elif csiz == 2:
|
| 124 |
+
mode = "LA"
|
| 125 |
+
elif csiz == 3:
|
| 126 |
+
mode = "RGB"
|
| 127 |
+
elif csiz == 4:
|
| 128 |
+
mode = "RGBA"
|
| 129 |
+
else:
|
| 130 |
+
msg = "unable to determine J2K image mode"
|
| 131 |
+
raise SyntaxError(msg)
|
| 132 |
+
|
| 133 |
+
return size, mode
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _res_to_dpi(num: int, denom: int, exp: int) -> float | None:
|
| 137 |
+
"""Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution,
|
| 138 |
+
calculated as (num / denom) * 10^exp and stored in dots per meter,
|
| 139 |
+
to floating-point dots per inch."""
|
| 140 |
+
if denom == 0:
|
| 141 |
+
return None
|
| 142 |
+
return (254 * num * (10**exp)) / (10000 * denom)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _parse_jp2_header(
|
| 146 |
+
fp: IO[bytes],
|
| 147 |
+
) -> tuple[
|
| 148 |
+
tuple[int, int],
|
| 149 |
+
str,
|
| 150 |
+
str | None,
|
| 151 |
+
tuple[float, float] | None,
|
| 152 |
+
ImagePalette.ImagePalette | None,
|
| 153 |
+
]:
|
| 154 |
+
"""Parse the JP2 header box to extract size, component count,
|
| 155 |
+
color space information, and optionally DPI information,
|
| 156 |
+
returning a (size, mode, mimetype, dpi) tuple."""
|
| 157 |
+
|
| 158 |
+
# Find the JP2 header box
|
| 159 |
+
reader = BoxReader(fp)
|
| 160 |
+
header = None
|
| 161 |
+
mimetype = None
|
| 162 |
+
while reader.has_next_box():
|
| 163 |
+
tbox = reader.next_box_type()
|
| 164 |
+
|
| 165 |
+
if tbox == b"jp2h":
|
| 166 |
+
header = reader.read_boxes()
|
| 167 |
+
break
|
| 168 |
+
elif tbox == b"ftyp":
|
| 169 |
+
if reader.read_fields(">4s")[0] == b"jpx ":
|
| 170 |
+
mimetype = "image/jpx"
|
| 171 |
+
assert header is not None
|
| 172 |
+
|
| 173 |
+
size = None
|
| 174 |
+
mode = None
|
| 175 |
+
bpc = None
|
| 176 |
+
nc = None
|
| 177 |
+
dpi = None # 2-tuple of DPI info, or None
|
| 178 |
+
palette = None
|
| 179 |
+
|
| 180 |
+
while header.has_next_box():
|
| 181 |
+
tbox = header.next_box_type()
|
| 182 |
+
|
| 183 |
+
if tbox == b"ihdr":
|
| 184 |
+
height, width, nc, bpc = header.read_fields(">IIHB")
|
| 185 |
+
assert isinstance(height, int)
|
| 186 |
+
assert isinstance(width, int)
|
| 187 |
+
assert isinstance(bpc, int)
|
| 188 |
+
size = (width, height)
|
| 189 |
+
if nc == 1 and (bpc & 0x7F) > 8:
|
| 190 |
+
mode = "I;16"
|
| 191 |
+
elif nc == 1:
|
| 192 |
+
mode = "L"
|
| 193 |
+
elif nc == 2:
|
| 194 |
+
mode = "LA"
|
| 195 |
+
elif nc == 3:
|
| 196 |
+
mode = "RGB"
|
| 197 |
+
elif nc == 4:
|
| 198 |
+
mode = "RGBA"
|
| 199 |
+
elif tbox == b"colr" and nc == 4:
|
| 200 |
+
meth, _, _, enumcs = header.read_fields(">BBBI")
|
| 201 |
+
if meth == 1 and enumcs == 12:
|
| 202 |
+
mode = "CMYK"
|
| 203 |
+
elif tbox == b"pclr" and mode in ("L", "LA"):
|
| 204 |
+
ne, npc = header.read_fields(">HB")
|
| 205 |
+
assert isinstance(ne, int)
|
| 206 |
+
assert isinstance(npc, int)
|
| 207 |
+
max_bitdepth = 0
|
| 208 |
+
for bitdepth in header.read_fields(">" + ("B" * npc)):
|
| 209 |
+
assert isinstance(bitdepth, int)
|
| 210 |
+
if bitdepth > max_bitdepth:
|
| 211 |
+
max_bitdepth = bitdepth
|
| 212 |
+
if max_bitdepth <= 8:
|
| 213 |
+
palette = ImagePalette.ImagePalette("RGBA" if npc == 4 else "RGB")
|
| 214 |
+
for i in range(ne):
|
| 215 |
+
color: list[int] = []
|
| 216 |
+
for value in header.read_fields(">" + ("B" * npc)):
|
| 217 |
+
assert isinstance(value, int)
|
| 218 |
+
color.append(value)
|
| 219 |
+
palette.getcolor(tuple(color))
|
| 220 |
+
mode = "P" if mode == "L" else "PA"
|
| 221 |
+
elif tbox == b"res ":
|
| 222 |
+
res = header.read_boxes()
|
| 223 |
+
while res.has_next_box():
|
| 224 |
+
tres = res.next_box_type()
|
| 225 |
+
if tres == b"resc":
|
| 226 |
+
vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
|
| 227 |
+
assert isinstance(vrcn, int)
|
| 228 |
+
assert isinstance(vrcd, int)
|
| 229 |
+
assert isinstance(hrcn, int)
|
| 230 |
+
assert isinstance(hrcd, int)
|
| 231 |
+
assert isinstance(vrce, int)
|
| 232 |
+
assert isinstance(hrce, int)
|
| 233 |
+
hres = _res_to_dpi(hrcn, hrcd, hrce)
|
| 234 |
+
vres = _res_to_dpi(vrcn, vrcd, vrce)
|
| 235 |
+
if hres is not None and vres is not None:
|
| 236 |
+
dpi = (hres, vres)
|
| 237 |
+
break
|
| 238 |
+
|
| 239 |
+
if size is None or mode is None:
|
| 240 |
+
msg = "Malformed JP2 header"
|
| 241 |
+
raise SyntaxError(msg)
|
| 242 |
+
|
| 243 |
+
return size, mode, mimetype, dpi, palette
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
##
|
| 247 |
+
# Image plugin for JPEG2000 images.
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class Jpeg2KImageFile(ImageFile.ImageFile):
|
| 251 |
+
format = "JPEG2000"
|
| 252 |
+
format_description = "JPEG 2000 (ISO 15444)"
|
| 253 |
+
|
| 254 |
+
def _open(self) -> None:
|
| 255 |
+
assert self.fp is not None
|
| 256 |
+
sig = self.fp.read(4)
|
| 257 |
+
if sig == b"\xff\x4f\xff\x51":
|
| 258 |
+
self.codec = "j2k"
|
| 259 |
+
self._size, self._mode = _parse_codestream(self.fp)
|
| 260 |
+
self._parse_comment()
|
| 261 |
+
else:
|
| 262 |
+
sig = sig + self.fp.read(8)
|
| 263 |
+
|
| 264 |
+
if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":
|
| 265 |
+
self.codec = "jp2"
|
| 266 |
+
header = _parse_jp2_header(self.fp)
|
| 267 |
+
self._size, self._mode, self.custom_mimetype, dpi, self.palette = header
|
| 268 |
+
if dpi is not None:
|
| 269 |
+
self.info["dpi"] = dpi
|
| 270 |
+
if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
|
| 271 |
+
hdr = self.fp.read(2)
|
| 272 |
+
length = _binary.i16be(hdr)
|
| 273 |
+
self.fp.seek(length - 2, os.SEEK_CUR)
|
| 274 |
+
self._parse_comment()
|
| 275 |
+
else:
|
| 276 |
+
msg = "not a JPEG 2000 file"
|
| 277 |
+
raise SyntaxError(msg)
|
| 278 |
+
|
| 279 |
+
self._reduce = 0
|
| 280 |
+
self.layers = 0
|
| 281 |
+
|
| 282 |
+
fd = -1
|
| 283 |
+
length = -1
|
| 284 |
+
|
| 285 |
+
try:
|
| 286 |
+
fd = self.fp.fileno()
|
| 287 |
+
length = os.fstat(fd).st_size
|
| 288 |
+
except Exception:
|
| 289 |
+
fd = -1
|
| 290 |
+
try:
|
| 291 |
+
pos = self.fp.tell()
|
| 292 |
+
self.fp.seek(0, io.SEEK_END)
|
| 293 |
+
length = self.fp.tell()
|
| 294 |
+
self.fp.seek(pos)
|
| 295 |
+
except Exception:
|
| 296 |
+
length = -1
|
| 297 |
+
|
| 298 |
+
self.tile = [
|
| 299 |
+
ImageFile._Tile(
|
| 300 |
+
"jpeg2k",
|
| 301 |
+
(0, 0) + self.size,
|
| 302 |
+
0,
|
| 303 |
+
(self.codec, self._reduce, self.layers, fd, length),
|
| 304 |
+
)
|
| 305 |
+
]
|
| 306 |
+
|
| 307 |
+
def _parse_comment(self) -> None:
|
| 308 |
+
assert self.fp is not None
|
| 309 |
+
while True:
|
| 310 |
+
marker = self.fp.read(2)
|
| 311 |
+
if not marker:
|
| 312 |
+
break
|
| 313 |
+
typ = marker[1]
|
| 314 |
+
if typ in (0x90, 0xD9):
|
| 315 |
+
# Start of tile or end of codestream
|
| 316 |
+
break
|
| 317 |
+
hdr = self.fp.read(2)
|
| 318 |
+
length = _binary.i16be(hdr)
|
| 319 |
+
if typ == 0x64:
|
| 320 |
+
# Comment
|
| 321 |
+
self.info["comment"] = self.fp.read(length - 2)[2:]
|
| 322 |
+
break
|
| 323 |
+
else:
|
| 324 |
+
self.fp.seek(length - 2, os.SEEK_CUR)
|
| 325 |
+
|
| 326 |
+
@property # type: ignore[override]
|
| 327 |
+
def reduce(
|
| 328 |
+
self,
|
| 329 |
+
) -> (
|
| 330 |
+
Callable[[int | tuple[int, int], tuple[int, int, int, int] | None], Image.Image]
|
| 331 |
+
| int
|
| 332 |
+
):
|
| 333 |
+
# https://github.com/python-pillow/Pillow/issues/4343 found that the
|
| 334 |
+
# new Image 'reduce' method was shadowed by this plugin's 'reduce'
|
| 335 |
+
# property. This attempts to allow for both scenarios
|
| 336 |
+
return self._reduce or super().reduce
|
| 337 |
+
|
| 338 |
+
@reduce.setter
|
| 339 |
+
def reduce(self, value: int) -> None:
|
| 340 |
+
self._reduce = value
|
| 341 |
+
|
| 342 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 343 |
+
if self.tile and self._reduce:
|
| 344 |
+
power = 1 << self._reduce
|
| 345 |
+
adjust = power >> 1
|
| 346 |
+
self._size = (
|
| 347 |
+
int((self.size[0] + adjust) / power),
|
| 348 |
+
int((self.size[1] + adjust) / power),
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# Update the reduce and layers settings
|
| 352 |
+
t = self.tile[0]
|
| 353 |
+
assert isinstance(t[3], tuple)
|
| 354 |
+
t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
|
| 355 |
+
self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)]
|
| 356 |
+
|
| 357 |
+
return ImageFile.ImageFile.load(self)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _accept(prefix: bytes) -> bool:
|
| 361 |
+
return prefix.startswith(
|
| 362 |
+
(b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a")
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# ------------------------------------------------------------
|
| 367 |
+
# Save support
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 371 |
+
# Get the keyword arguments
|
| 372 |
+
info = im.encoderinfo
|
| 373 |
+
|
| 374 |
+
if isinstance(filename, str):
|
| 375 |
+
filename = filename.encode()
|
| 376 |
+
if filename.endswith(b".j2k") or info.get("no_jp2", False):
|
| 377 |
+
kind = "j2k"
|
| 378 |
+
else:
|
| 379 |
+
kind = "jp2"
|
| 380 |
+
|
| 381 |
+
offset = info.get("offset", None)
|
| 382 |
+
tile_offset = info.get("tile_offset", None)
|
| 383 |
+
tile_size = info.get("tile_size", None)
|
| 384 |
+
quality_mode = info.get("quality_mode", "rates")
|
| 385 |
+
quality_layers = info.get("quality_layers", None)
|
| 386 |
+
if quality_layers is not None and not (
|
| 387 |
+
isinstance(quality_layers, (list, tuple))
|
| 388 |
+
and all(
|
| 389 |
+
isinstance(quality_layer, (int, float)) for quality_layer in quality_layers
|
| 390 |
+
)
|
| 391 |
+
):
|
| 392 |
+
msg = "quality_layers must be a sequence of numbers"
|
| 393 |
+
raise ValueError(msg)
|
| 394 |
+
|
| 395 |
+
num_resolutions = info.get("num_resolutions", 0)
|
| 396 |
+
cblk_size = info.get("codeblock_size", None)
|
| 397 |
+
precinct_size = info.get("precinct_size", None)
|
| 398 |
+
irreversible = info.get("irreversible", False)
|
| 399 |
+
progression = info.get("progression", "LRCP")
|
| 400 |
+
cinema_mode = info.get("cinema_mode", "no")
|
| 401 |
+
mct = info.get("mct", 0)
|
| 402 |
+
signed = info.get("signed", False)
|
| 403 |
+
comment = info.get("comment")
|
| 404 |
+
if isinstance(comment, str):
|
| 405 |
+
comment = comment.encode()
|
| 406 |
+
plt = info.get("plt", False)
|
| 407 |
+
|
| 408 |
+
fd = -1
|
| 409 |
+
if hasattr(fp, "fileno"):
|
| 410 |
+
try:
|
| 411 |
+
fd = fp.fileno()
|
| 412 |
+
except Exception:
|
| 413 |
+
fd = -1
|
| 414 |
+
|
| 415 |
+
im.encoderconfig = (
|
| 416 |
+
offset,
|
| 417 |
+
tile_offset,
|
| 418 |
+
tile_size,
|
| 419 |
+
quality_mode,
|
| 420 |
+
quality_layers,
|
| 421 |
+
num_resolutions,
|
| 422 |
+
cblk_size,
|
| 423 |
+
precinct_size,
|
| 424 |
+
irreversible,
|
| 425 |
+
progression,
|
| 426 |
+
cinema_mode,
|
| 427 |
+
mct,
|
| 428 |
+
signed,
|
| 429 |
+
fd,
|
| 430 |
+
comment,
|
| 431 |
+
plt,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
ImageFile._save(im, fp, [ImageFile._Tile("jpeg2k", (0, 0) + im.size, 0, kind)])
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
# ------------------------------------------------------------
|
| 438 |
+
# Registry stuff
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept)
|
| 442 |
+
Image.register_save(Jpeg2KImageFile.format, _save)
|
| 443 |
+
|
| 444 |
+
Image.register_extensions(
|
| 445 |
+
Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"]
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
Image.register_mime(Jpeg2KImageFile.format, "image/jp2")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/JpegImagePlugin.py
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
assert self.fp is not None
|
| 65 |
+
n = i16(self.fp.read(2)) - 2
|
| 66 |
+
ImageFile._safe_read(self.fp, n)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def APP(self: JpegImageFile, marker: int) -> None:
|
| 70 |
+
#
|
| 71 |
+
# Application marker. Store these in the APP dictionary.
|
| 72 |
+
# Also look for well-known application markers.
|
| 73 |
+
|
| 74 |
+
assert self.fp is not None
|
| 75 |
+
n = i16(self.fp.read(2)) - 2
|
| 76 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 77 |
+
|
| 78 |
+
app = f"APP{marker & 15}"
|
| 79 |
+
|
| 80 |
+
self.app[app] = s # compatibility
|
| 81 |
+
self.applist.append((app, s))
|
| 82 |
+
|
| 83 |
+
if marker == 0xFFE0 and s.startswith(b"JFIF"):
|
| 84 |
+
# extract JFIF information
|
| 85 |
+
self.info["jfif"] = version = i16(s, 5) # version
|
| 86 |
+
self.info["jfif_version"] = divmod(version, 256)
|
| 87 |
+
# extract JFIF properties
|
| 88 |
+
try:
|
| 89 |
+
jfif_unit = s[7]
|
| 90 |
+
jfif_density = i16(s, 8), i16(s, 10)
|
| 91 |
+
except Exception:
|
| 92 |
+
pass
|
| 93 |
+
else:
|
| 94 |
+
if jfif_unit == 1:
|
| 95 |
+
self.info["dpi"] = jfif_density
|
| 96 |
+
elif jfif_unit == 2: # cm
|
| 97 |
+
# 1 dpcm = 2.54 dpi
|
| 98 |
+
self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)
|
| 99 |
+
self.info["jfif_unit"] = jfif_unit
|
| 100 |
+
self.info["jfif_density"] = jfif_density
|
| 101 |
+
elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):
|
| 102 |
+
# extract EXIF information
|
| 103 |
+
if "exif" in self.info:
|
| 104 |
+
self.info["exif"] += s[6:]
|
| 105 |
+
else:
|
| 106 |
+
self.info["exif"] = s
|
| 107 |
+
self._exif_offset = self.fp.tell() - n + 6
|
| 108 |
+
elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
|
| 109 |
+
self.info["xmp"] = s.split(b"\x00", 1)[1]
|
| 110 |
+
elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):
|
| 111 |
+
# extract FlashPix information (incomplete)
|
| 112 |
+
self.info["flashpix"] = s # FIXME: value will change
|
| 113 |
+
elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):
|
| 114 |
+
# Since an ICC profile can be larger than the maximum size of
|
| 115 |
+
# a JPEG marker (64K), we need provisions to split it into
|
| 116 |
+
# multiple markers. The format defined by the ICC specifies
|
| 117 |
+
# one or more APP2 markers containing the following data:
|
| 118 |
+
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
|
| 119 |
+
# Marker sequence number 1, 2, etc (1 byte)
|
| 120 |
+
# Number of markers Total of APP2's used (1 byte)
|
| 121 |
+
# Profile data (remainder of APP2 data)
|
| 122 |
+
# Decoders should use the marker sequence numbers to
|
| 123 |
+
# reassemble the profile, rather than assuming that the APP2
|
| 124 |
+
# markers appear in the correct sequence.
|
| 125 |
+
self.icclist.append(s)
|
| 126 |
+
elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):
|
| 127 |
+
# parse the image resource block
|
| 128 |
+
offset = 14
|
| 129 |
+
photoshop = self.info.setdefault("photoshop", {})
|
| 130 |
+
while s[offset : offset + 4] == b"8BIM":
|
| 131 |
+
try:
|
| 132 |
+
offset += 4
|
| 133 |
+
# resource code
|
| 134 |
+
code = i16(s, offset)
|
| 135 |
+
offset += 2
|
| 136 |
+
# resource name (usually empty)
|
| 137 |
+
name_len = s[offset]
|
| 138 |
+
# name = s[offset+1:offset+1+name_len]
|
| 139 |
+
offset += 1 + name_len
|
| 140 |
+
offset += offset & 1 # align
|
| 141 |
+
# resource data block
|
| 142 |
+
size = i32(s, offset)
|
| 143 |
+
offset += 4
|
| 144 |
+
data = s[offset : offset + size]
|
| 145 |
+
if code == 0x03ED: # ResolutionInfo
|
| 146 |
+
photoshop[code] = {
|
| 147 |
+
"XResolution": i32(data, 0) / 65536,
|
| 148 |
+
"DisplayedUnitsX": i16(data, 4),
|
| 149 |
+
"YResolution": i32(data, 8) / 65536,
|
| 150 |
+
"DisplayedUnitsY": i16(data, 12),
|
| 151 |
+
}
|
| 152 |
+
else:
|
| 153 |
+
photoshop[code] = data
|
| 154 |
+
offset += size
|
| 155 |
+
offset += offset & 1 # align
|
| 156 |
+
except struct.error:
|
| 157 |
+
break # insufficient data
|
| 158 |
+
|
| 159 |
+
elif marker == 0xFFEE and s.startswith(b"Adobe"):
|
| 160 |
+
self.info["adobe"] = i16(s, 5)
|
| 161 |
+
# extract Adobe custom properties
|
| 162 |
+
try:
|
| 163 |
+
adobe_transform = s[11]
|
| 164 |
+
except IndexError:
|
| 165 |
+
pass
|
| 166 |
+
else:
|
| 167 |
+
self.info["adobe_transform"] = adobe_transform
|
| 168 |
+
elif marker == 0xFFE2 and s.startswith(b"MPF\0"):
|
| 169 |
+
# extract MPO information
|
| 170 |
+
self.info["mp"] = s[4:]
|
| 171 |
+
# offset is current location minus buffer size
|
| 172 |
+
# plus constant header size
|
| 173 |
+
self.info["mpoffset"] = self.fp.tell() - n + 4
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def COM(self: JpegImageFile, marker: int) -> None:
|
| 177 |
+
#
|
| 178 |
+
# Comment marker. Store these in the APP dictionary.
|
| 179 |
+
assert self.fp is not None
|
| 180 |
+
n = i16(self.fp.read(2)) - 2
|
| 181 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 182 |
+
|
| 183 |
+
self.info["comment"] = s
|
| 184 |
+
self.app["COM"] = s # compatibility
|
| 185 |
+
self.applist.append(("COM", s))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def SOF(self: JpegImageFile, marker: int) -> None:
|
| 189 |
+
#
|
| 190 |
+
# Start of frame marker. Defines the size and mode of the
|
| 191 |
+
# image. JPEG is colour blind, so we use some simple
|
| 192 |
+
# heuristics to map the number of layers to an appropriate
|
| 193 |
+
# mode. Note that this could be made a bit brighter, by
|
| 194 |
+
# looking for JFIF and Adobe APP markers.
|
| 195 |
+
|
| 196 |
+
assert self.fp is not None
|
| 197 |
+
n = i16(self.fp.read(2)) - 2
|
| 198 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 199 |
+
self._size = i16(s, 3), i16(s, 1)
|
| 200 |
+
if self._im is not None and self.size != self.im.size:
|
| 201 |
+
self._im = None
|
| 202 |
+
|
| 203 |
+
self.bits = s[0]
|
| 204 |
+
if self.bits != 8:
|
| 205 |
+
msg = f"cannot handle {self.bits}-bit layers"
|
| 206 |
+
raise SyntaxError(msg)
|
| 207 |
+
|
| 208 |
+
self.layers = s[5]
|
| 209 |
+
if self.layers == 1:
|
| 210 |
+
self._mode = "L"
|
| 211 |
+
elif self.layers == 3:
|
| 212 |
+
self._mode = "RGB"
|
| 213 |
+
elif self.layers == 4:
|
| 214 |
+
self._mode = "CMYK"
|
| 215 |
+
else:
|
| 216 |
+
msg = f"cannot handle {self.layers}-layer images"
|
| 217 |
+
raise SyntaxError(msg)
|
| 218 |
+
|
| 219 |
+
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
|
| 220 |
+
self.info["progressive"] = self.info["progression"] = 1
|
| 221 |
+
|
| 222 |
+
if self.icclist:
|
| 223 |
+
# fixup icc profile
|
| 224 |
+
self.icclist.sort() # sort by sequence number
|
| 225 |
+
if self.icclist[0][13] == len(self.icclist):
|
| 226 |
+
profile = [p[14:] for p in self.icclist]
|
| 227 |
+
icc_profile = b"".join(profile)
|
| 228 |
+
else:
|
| 229 |
+
icc_profile = None # wrong number of fragments
|
| 230 |
+
self.info["icc_profile"] = icc_profile
|
| 231 |
+
self.icclist = []
|
| 232 |
+
|
| 233 |
+
for i in range(6, len(s), 3):
|
| 234 |
+
t = s[i : i + 3]
|
| 235 |
+
# 4-tuples: id, vsamp, hsamp, qtable
|
| 236 |
+
self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def DQT(self: JpegImageFile, marker: int) -> None:
|
| 240 |
+
#
|
| 241 |
+
# Define quantization table. Note that there might be more
|
| 242 |
+
# than one table in each marker.
|
| 243 |
+
|
| 244 |
+
# FIXME: The quantization tables can be used to estimate the
|
| 245 |
+
# compression quality.
|
| 246 |
+
|
| 247 |
+
assert self.fp is not None
|
| 248 |
+
n = i16(self.fp.read(2)) - 2
|
| 249 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 250 |
+
while len(s):
|
| 251 |
+
v = s[0]
|
| 252 |
+
precision = 1 if (v // 16 == 0) else 2 # in bytes
|
| 253 |
+
qt_length = 1 + precision * 64
|
| 254 |
+
if len(s) < qt_length:
|
| 255 |
+
msg = "bad quantization table marker"
|
| 256 |
+
raise SyntaxError(msg)
|
| 257 |
+
data = array.array("B" if precision == 1 else "H", s[1:qt_length])
|
| 258 |
+
if sys.byteorder == "little" and precision > 1:
|
| 259 |
+
data.byteswap() # the values are always big-endian
|
| 260 |
+
self.quantization[v & 15] = [data[i] for i in zigzag_index]
|
| 261 |
+
s = s[qt_length:]
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
#
|
| 265 |
+
# JPEG marker table
|
| 266 |
+
|
| 267 |
+
MARKER = {
|
| 268 |
+
0xFFC0: ("SOF0", "Baseline DCT", SOF),
|
| 269 |
+
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
|
| 270 |
+
0xFFC2: ("SOF2", "Progressive DCT", SOF),
|
| 271 |
+
0xFFC3: ("SOF3", "Spatial lossless", SOF),
|
| 272 |
+
0xFFC4: ("DHT", "Define Huffman table", Skip),
|
| 273 |
+
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
|
| 274 |
+
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
|
| 275 |
+
0xFFC7: ("SOF7", "Differential spatial", SOF),
|
| 276 |
+
0xFFC8: ("JPG", "Extension", None),
|
| 277 |
+
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
|
| 278 |
+
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
|
| 279 |
+
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
|
| 280 |
+
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
|
| 281 |
+
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
|
| 282 |
+
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
|
| 283 |
+
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
|
| 284 |
+
0xFFD0: ("RST0", "Restart 0", None),
|
| 285 |
+
0xFFD1: ("RST1", "Restart 1", None),
|
| 286 |
+
0xFFD2: ("RST2", "Restart 2", None),
|
| 287 |
+
0xFFD3: ("RST3", "Restart 3", None),
|
| 288 |
+
0xFFD4: ("RST4", "Restart 4", None),
|
| 289 |
+
0xFFD5: ("RST5", "Restart 5", None),
|
| 290 |
+
0xFFD6: ("RST6", "Restart 6", None),
|
| 291 |
+
0xFFD7: ("RST7", "Restart 7", None),
|
| 292 |
+
0xFFD8: ("SOI", "Start of image", None),
|
| 293 |
+
0xFFD9: ("EOI", "End of image", None),
|
| 294 |
+
0xFFDA: ("SOS", "Start of scan", Skip),
|
| 295 |
+
0xFFDB: ("DQT", "Define quantization table", DQT),
|
| 296 |
+
0xFFDC: ("DNL", "Define number of lines", Skip),
|
| 297 |
+
0xFFDD: ("DRI", "Define restart interval", Skip),
|
| 298 |
+
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
|
| 299 |
+
0xFFDF: ("EXP", "Expand reference component", Skip),
|
| 300 |
+
0xFFE0: ("APP0", "Application segment 0", APP),
|
| 301 |
+
0xFFE1: ("APP1", "Application segment 1", APP),
|
| 302 |
+
0xFFE2: ("APP2", "Application segment 2", APP),
|
| 303 |
+
0xFFE3: ("APP3", "Application segment 3", APP),
|
| 304 |
+
0xFFE4: ("APP4", "Application segment 4", APP),
|
| 305 |
+
0xFFE5: ("APP5", "Application segment 5", APP),
|
| 306 |
+
0xFFE6: ("APP6", "Application segment 6", APP),
|
| 307 |
+
0xFFE7: ("APP7", "Application segment 7", APP),
|
| 308 |
+
0xFFE8: ("APP8", "Application segment 8", APP),
|
| 309 |
+
0xFFE9: ("APP9", "Application segment 9", APP),
|
| 310 |
+
0xFFEA: ("APP10", "Application segment 10", APP),
|
| 311 |
+
0xFFEB: ("APP11", "Application segment 11", APP),
|
| 312 |
+
0xFFEC: ("APP12", "Application segment 12", APP),
|
| 313 |
+
0xFFED: ("APP13", "Application segment 13", APP),
|
| 314 |
+
0xFFEE: ("APP14", "Application segment 14", APP),
|
| 315 |
+
0xFFEF: ("APP15", "Application segment 15", APP),
|
| 316 |
+
0xFFF0: ("JPG0", "Extension 0", None),
|
| 317 |
+
0xFFF1: ("JPG1", "Extension 1", None),
|
| 318 |
+
0xFFF2: ("JPG2", "Extension 2", None),
|
| 319 |
+
0xFFF3: ("JPG3", "Extension 3", None),
|
| 320 |
+
0xFFF4: ("JPG4", "Extension 4", None),
|
| 321 |
+
0xFFF5: ("JPG5", "Extension 5", None),
|
| 322 |
+
0xFFF6: ("JPG6", "Extension 6", None),
|
| 323 |
+
0xFFF7: ("JPG7", "Extension 7", None),
|
| 324 |
+
0xFFF8: ("JPG8", "Extension 8", None),
|
| 325 |
+
0xFFF9: ("JPG9", "Extension 9", None),
|
| 326 |
+
0xFFFA: ("JPG10", "Extension 10", None),
|
| 327 |
+
0xFFFB: ("JPG11", "Extension 11", None),
|
| 328 |
+
0xFFFC: ("JPG12", "Extension 12", None),
|
| 329 |
+
0xFFFD: ("JPG13", "Extension 13", None),
|
| 330 |
+
0xFFFE: ("COM", "Comment", COM),
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _accept(prefix: bytes) -> bool:
|
| 335 |
+
# Magic number was taken from https://en.wikipedia.org/wiki/JPEG
|
| 336 |
+
return prefix.startswith(b"\xff\xd8\xff")
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
##
|
| 340 |
+
# Image plugin for JPEG and JFIF images.
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class JpegImageFile(ImageFile.ImageFile):
|
| 344 |
+
format = "JPEG"
|
| 345 |
+
format_description = "JPEG (ISO 10918)"
|
| 346 |
+
|
| 347 |
+
def _open(self) -> None:
|
| 348 |
+
assert self.fp is not None
|
| 349 |
+
s = self.fp.read(3)
|
| 350 |
+
|
| 351 |
+
if not _accept(s):
|
| 352 |
+
msg = "not a JPEG file"
|
| 353 |
+
raise SyntaxError(msg)
|
| 354 |
+
s = b"\xff"
|
| 355 |
+
|
| 356 |
+
# Create attributes
|
| 357 |
+
self.bits = self.layers = 0
|
| 358 |
+
self._exif_offset = 0
|
| 359 |
+
|
| 360 |
+
# JPEG specifics (internal)
|
| 361 |
+
self.layer: list[tuple[int, int, int, int]] = []
|
| 362 |
+
self._huffman_dc: dict[Any, Any] = {}
|
| 363 |
+
self._huffman_ac: dict[Any, Any] = {}
|
| 364 |
+
self.quantization: dict[int, list[int]] = {}
|
| 365 |
+
self.app: dict[str, bytes] = {} # compatibility
|
| 366 |
+
self.applist: list[tuple[str, bytes]] = []
|
| 367 |
+
self.icclist: list[bytes] = []
|
| 368 |
+
|
| 369 |
+
while True:
|
| 370 |
+
i = s[0]
|
| 371 |
+
if i == 0xFF:
|
| 372 |
+
s = s + self.fp.read(1)
|
| 373 |
+
i = i16(s)
|
| 374 |
+
else:
|
| 375 |
+
# Skip non-0xFF junk
|
| 376 |
+
s = self.fp.read(1)
|
| 377 |
+
continue
|
| 378 |
+
|
| 379 |
+
if i in MARKER:
|
| 380 |
+
name, description, handler = MARKER[i]
|
| 381 |
+
if handler is not None:
|
| 382 |
+
handler(self, i)
|
| 383 |
+
if i == 0xFFDA: # start of scan
|
| 384 |
+
rawmode = self.mode
|
| 385 |
+
if self.mode == "CMYK":
|
| 386 |
+
rawmode = "CMYK;I" # assume adobe conventions
|
| 387 |
+
self.tile = [
|
| 388 |
+
ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, ""))
|
| 389 |
+
]
|
| 390 |
+
# self.__offset = self.fp.tell()
|
| 391 |
+
break
|
| 392 |
+
s = self.fp.read(1)
|
| 393 |
+
elif i in {0, 0xFFFF}:
|
| 394 |
+
# padded marker or junk; move on
|
| 395 |
+
s = b"\xff"
|
| 396 |
+
elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
|
| 397 |
+
s = self.fp.read(1)
|
| 398 |
+
else:
|
| 399 |
+
msg = "no marker found"
|
| 400 |
+
raise SyntaxError(msg)
|
| 401 |
+
|
| 402 |
+
self._read_dpi_from_exif()
|
| 403 |
+
|
| 404 |
+
def __getstate__(self) -> list[Any]:
|
| 405 |
+
return super().__getstate__() + [self.layers, self.layer]
|
| 406 |
+
|
| 407 |
+
def __setstate__(self, state: list[Any]) -> None:
|
| 408 |
+
self.layers, self.layer = state[6:]
|
| 409 |
+
super().__setstate__(state)
|
| 410 |
+
|
| 411 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 412 |
+
"""
|
| 413 |
+
internal: read more image data
|
| 414 |
+
For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
|
| 415 |
+
so libjpeg can finish decoding
|
| 416 |
+
"""
|
| 417 |
+
assert self.fp is not None
|
| 418 |
+
s = self.fp.read(read_bytes)
|
| 419 |
+
|
| 420 |
+
if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
|
| 421 |
+
# Premature EOF.
|
| 422 |
+
# Pretend file is finished adding EOI marker
|
| 423 |
+
self._ended = True
|
| 424 |
+
return b"\xff\xd9"
|
| 425 |
+
|
| 426 |
+
return s
|
| 427 |
+
|
| 428 |
+
def draft(
|
| 429 |
+
self, mode: str | None, size: tuple[int, int] | None
|
| 430 |
+
) -> tuple[str, tuple[int, int, float, float]] | None:
|
| 431 |
+
if len(self.tile) != 1:
|
| 432 |
+
return None
|
| 433 |
+
|
| 434 |
+
# Protect from second call
|
| 435 |
+
if self.decoderconfig:
|
| 436 |
+
return None
|
| 437 |
+
|
| 438 |
+
d, e, o, a = self.tile[0]
|
| 439 |
+
scale = 1
|
| 440 |
+
original_size = self.size
|
| 441 |
+
|
| 442 |
+
assert isinstance(a, tuple)
|
| 443 |
+
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
|
| 444 |
+
self._mode = mode
|
| 445 |
+
a = mode, ""
|
| 446 |
+
|
| 447 |
+
if size:
|
| 448 |
+
scale = min(self.size[0] // size[0], self.size[1] // size[1])
|
| 449 |
+
for s in [8, 4, 2, 1]:
|
| 450 |
+
if scale >= s:
|
| 451 |
+
break
|
| 452 |
+
assert e is not None
|
| 453 |
+
e = (
|
| 454 |
+
e[0],
|
| 455 |
+
e[1],
|
| 456 |
+
(e[2] - e[0] + s - 1) // s + e[0],
|
| 457 |
+
(e[3] - e[1] + s - 1) // s + e[1],
|
| 458 |
+
)
|
| 459 |
+
self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
|
| 460 |
+
scale = s
|
| 461 |
+
|
| 462 |
+
self.tile = [ImageFile._Tile(d, e, o, a)]
|
| 463 |
+
self.decoderconfig = (scale, 0)
|
| 464 |
+
|
| 465 |
+
box = (0, 0, original_size[0] / scale, original_size[1] / scale)
|
| 466 |
+
return self.mode, box
|
| 467 |
+
|
| 468 |
+
def load_djpeg(self) -> None:
|
| 469 |
+
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
|
| 470 |
+
|
| 471 |
+
f, path = tempfile.mkstemp()
|
| 472 |
+
os.close(f)
|
| 473 |
+
if os.path.exists(self.filename):
|
| 474 |
+
subprocess.check_call(["djpeg", "-outfile", path, self.filename])
|
| 475 |
+
else:
|
| 476 |
+
try:
|
| 477 |
+
os.unlink(path)
|
| 478 |
+
except OSError:
|
| 479 |
+
pass
|
| 480 |
+
|
| 481 |
+
msg = "Invalid Filename"
|
| 482 |
+
raise ValueError(msg)
|
| 483 |
+
|
| 484 |
+
try:
|
| 485 |
+
with Image.open(path) as _im:
|
| 486 |
+
_im.load()
|
| 487 |
+
self.im = _im.im
|
| 488 |
+
finally:
|
| 489 |
+
try:
|
| 490 |
+
os.unlink(path)
|
| 491 |
+
except OSError:
|
| 492 |
+
pass
|
| 493 |
+
|
| 494 |
+
self._mode = self.im.mode
|
| 495 |
+
self._size = self.im.size
|
| 496 |
+
|
| 497 |
+
self.tile = []
|
| 498 |
+
|
| 499 |
+
def _getexif(self) -> dict[int, Any] | None:
|
| 500 |
+
return _getexif(self)
|
| 501 |
+
|
| 502 |
+
def _read_dpi_from_exif(self) -> None:
|
| 503 |
+
# If DPI isn't in JPEG header, fetch from EXIF
|
| 504 |
+
if "dpi" in self.info or "exif" not in self.info:
|
| 505 |
+
return
|
| 506 |
+
try:
|
| 507 |
+
exif = self.getexif()
|
| 508 |
+
resolution_unit = exif[0x0128]
|
| 509 |
+
x_resolution = exif[0x011A]
|
| 510 |
+
try:
|
| 511 |
+
dpi = float(x_resolution[0]) / x_resolution[1]
|
| 512 |
+
except TypeError:
|
| 513 |
+
dpi = x_resolution
|
| 514 |
+
if math.isnan(dpi):
|
| 515 |
+
msg = "DPI is not a number"
|
| 516 |
+
raise ValueError(msg)
|
| 517 |
+
if resolution_unit == 3: # cm
|
| 518 |
+
# 1 dpcm = 2.54 dpi
|
| 519 |
+
dpi *= 2.54
|
| 520 |
+
self.info["dpi"] = dpi, dpi
|
| 521 |
+
except (
|
| 522 |
+
struct.error, # truncated EXIF
|
| 523 |
+
KeyError, # dpi not included
|
| 524 |
+
SyntaxError, # invalid/unreadable EXIF
|
| 525 |
+
TypeError, # dpi is an invalid float
|
| 526 |
+
ValueError, # dpi is an invalid float
|
| 527 |
+
ZeroDivisionError, # invalid dpi rational value
|
| 528 |
+
):
|
| 529 |
+
self.info["dpi"] = 72, 72
|
| 530 |
+
|
| 531 |
+
def _getmp(self) -> dict[int, Any] | None:
|
| 532 |
+
return _getmp(self)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _getexif(self: JpegImageFile) -> dict[int, Any] | None:
|
| 536 |
+
if "exif" not in self.info:
|
| 537 |
+
return None
|
| 538 |
+
return self.getexif()._get_merged_dict()
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _getmp(self: JpegImageFile) -> dict[int, Any] | None:
|
| 542 |
+
# Extract MP information. This method was inspired by the "highly
|
| 543 |
+
# experimental" _getexif version that's been in use for years now,
|
| 544 |
+
# itself based on the ImageFileDirectory class in the TIFF plugin.
|
| 545 |
+
|
| 546 |
+
# The MP record essentially consists of a TIFF file embedded in a JPEG
|
| 547 |
+
# application marker.
|
| 548 |
+
try:
|
| 549 |
+
data = self.info["mp"]
|
| 550 |
+
except KeyError:
|
| 551 |
+
return None
|
| 552 |
+
file_contents = io.BytesIO(data)
|
| 553 |
+
head = file_contents.read(8)
|
| 554 |
+
endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"
|
| 555 |
+
# process dictionary
|
| 556 |
+
from . import TiffImagePlugin
|
| 557 |
+
|
| 558 |
+
try:
|
| 559 |
+
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
| 560 |
+
file_contents.seek(info.next)
|
| 561 |
+
info.load(file_contents)
|
| 562 |
+
mp = dict(info)
|
| 563 |
+
except Exception as e:
|
| 564 |
+
msg = "malformed MP Index (unreadable directory)"
|
| 565 |
+
raise SyntaxError(msg) from e
|
| 566 |
+
# it's an error not to have a number of images
|
| 567 |
+
try:
|
| 568 |
+
quant = mp[0xB001]
|
| 569 |
+
except KeyError as e:
|
| 570 |
+
msg = "malformed MP Index (no number of images)"
|
| 571 |
+
raise SyntaxError(msg) from e
|
| 572 |
+
# get MP entries
|
| 573 |
+
mpentries = []
|
| 574 |
+
try:
|
| 575 |
+
rawmpentries = mp[0xB002]
|
| 576 |
+
for entrynum in range(quant):
|
| 577 |
+
unpackedentry = struct.unpack_from(
|
| 578 |
+
f"{endianness}LLLHH", rawmpentries, entrynum * 16
|
| 579 |
+
)
|
| 580 |
+
labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")
|
| 581 |
+
mpentry = dict(zip(labels, unpackedentry))
|
| 582 |
+
mpentryattr = {
|
| 583 |
+
"DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),
|
| 584 |
+
"DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),
|
| 585 |
+
"RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),
|
| 586 |
+
"Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,
|
| 587 |
+
"ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,
|
| 588 |
+
"MPType": mpentry["Attribute"] & 0x00FFFFFF,
|
| 589 |
+
}
|
| 590 |
+
if mpentryattr["ImageDataFormat"] == 0:
|
| 591 |
+
mpentryattr["ImageDataFormat"] = "JPEG"
|
| 592 |
+
else:
|
| 593 |
+
msg = "unsupported picture format in MPO"
|
| 594 |
+
raise SyntaxError(msg)
|
| 595 |
+
mptypemap = {
|
| 596 |
+
0x000000: "Undefined",
|
| 597 |
+
0x010001: "Large Thumbnail (VGA Equivalent)",
|
| 598 |
+
0x010002: "Large Thumbnail (Full HD Equivalent)",
|
| 599 |
+
0x020001: "Multi-Frame Image (Panorama)",
|
| 600 |
+
0x020002: "Multi-Frame Image: (Disparity)",
|
| 601 |
+
0x020003: "Multi-Frame Image: (Multi-Angle)",
|
| 602 |
+
0x030000: "Baseline MP Primary Image",
|
| 603 |
+
}
|
| 604 |
+
mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")
|
| 605 |
+
mpentry["Attribute"] = mpentryattr
|
| 606 |
+
mpentries.append(mpentry)
|
| 607 |
+
mp[0xB002] = mpentries
|
| 608 |
+
except KeyError as e:
|
| 609 |
+
msg = "malformed MP Index (bad MP Entry)"
|
| 610 |
+
raise SyntaxError(msg) from e
|
| 611 |
+
# Next we should try and parse the individual image unique ID list;
|
| 612 |
+
# we don't because I've never seen this actually used in a real MPO
|
| 613 |
+
# file and so can't test it.
|
| 614 |
+
return mp
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
# --------------------------------------------------------------------
|
| 618 |
+
# stuff to save JPEG files
|
| 619 |
+
|
| 620 |
+
RAWMODE = {
|
| 621 |
+
"1": "L",
|
| 622 |
+
"L": "L",
|
| 623 |
+
"RGB": "RGB",
|
| 624 |
+
"RGBX": "RGB",
|
| 625 |
+
"CMYK": "CMYK;I", # assume adobe conventions
|
| 626 |
+
"YCbCr": "YCbCr",
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
# fmt: off
|
| 630 |
+
zigzag_index = (
|
| 631 |
+
0, 1, 5, 6, 14, 15, 27, 28,
|
| 632 |
+
2, 4, 7, 13, 16, 26, 29, 42,
|
| 633 |
+
3, 8, 12, 17, 25, 30, 41, 43,
|
| 634 |
+
9, 11, 18, 24, 31, 40, 44, 53,
|
| 635 |
+
10, 19, 23, 32, 39, 45, 52, 54,
|
| 636 |
+
20, 22, 33, 38, 46, 51, 55, 60,
|
| 637 |
+
21, 34, 37, 47, 50, 56, 59, 61,
|
| 638 |
+
35, 36, 48, 49, 57, 58, 62, 63,
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
samplings = {
|
| 642 |
+
(1, 1, 1, 1, 1, 1): 0,
|
| 643 |
+
(2, 1, 1, 1, 1, 1): 1,
|
| 644 |
+
(2, 2, 1, 1, 1, 1): 2,
|
| 645 |
+
}
|
| 646 |
+
# fmt: on
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def get_sampling(im: Image.Image) -> int:
|
| 650 |
+
# There's no subsampling when images have only 1 layer
|
| 651 |
+
# (grayscale images) or when they are CMYK (4 layers),
|
| 652 |
+
# so set subsampling to the default value.
|
| 653 |
+
#
|
| 654 |
+
# NOTE: currently Pillow can't encode JPEG to YCCK format.
|
| 655 |
+
# If YCCK support is added in the future, subsampling code will have
|
| 656 |
+
# to be updated (here and in JpegEncode.c) to deal with 4 layers.
|
| 657 |
+
if not isinstance(im, JpegImageFile) or im.layers in (1, 4):
|
| 658 |
+
return -1
|
| 659 |
+
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
|
| 660 |
+
return samplings.get(sampling, -1)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 664 |
+
if im.width == 0 or im.height == 0:
|
| 665 |
+
msg = "cannot write empty image as JPEG"
|
| 666 |
+
raise ValueError(msg)
|
| 667 |
+
|
| 668 |
+
try:
|
| 669 |
+
rawmode = RAWMODE[im.mode]
|
| 670 |
+
except KeyError as e:
|
| 671 |
+
msg = f"cannot write mode {im.mode} as JPEG"
|
| 672 |
+
raise OSError(msg) from e
|
| 673 |
+
|
| 674 |
+
info = im.encoderinfo
|
| 675 |
+
|
| 676 |
+
dpi = [round(x) for x in info.get("dpi", (0, 0))]
|
| 677 |
+
|
| 678 |
+
quality = info.get("quality", -1)
|
| 679 |
+
subsampling = info.get("subsampling", -1)
|
| 680 |
+
qtables = info.get("qtables")
|
| 681 |
+
|
| 682 |
+
if quality == "keep":
|
| 683 |
+
quality = -1
|
| 684 |
+
subsampling = "keep"
|
| 685 |
+
qtables = "keep"
|
| 686 |
+
elif quality in presets:
|
| 687 |
+
preset = presets[quality]
|
| 688 |
+
quality = -1
|
| 689 |
+
subsampling = preset.get("subsampling", -1)
|
| 690 |
+
qtables = preset.get("quantization")
|
| 691 |
+
elif not isinstance(quality, int):
|
| 692 |
+
msg = "Invalid quality setting"
|
| 693 |
+
raise ValueError(msg)
|
| 694 |
+
else:
|
| 695 |
+
if subsampling in presets:
|
| 696 |
+
subsampling = presets[subsampling].get("subsampling", -1)
|
| 697 |
+
if isinstance(qtables, str) and qtables in presets:
|
| 698 |
+
qtables = presets[qtables].get("quantization")
|
| 699 |
+
|
| 700 |
+
if subsampling == "4:4:4":
|
| 701 |
+
subsampling = 0
|
| 702 |
+
elif subsampling == "4:2:2":
|
| 703 |
+
subsampling = 1
|
| 704 |
+
elif subsampling == "4:2:0":
|
| 705 |
+
subsampling = 2
|
| 706 |
+
elif subsampling == "4:1:1":
|
| 707 |
+
# For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.
|
| 708 |
+
# Set 4:2:0 if someone is still using that value.
|
| 709 |
+
subsampling = 2
|
| 710 |
+
elif subsampling == "keep":
|
| 711 |
+
if im.format != "JPEG":
|
| 712 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 713 |
+
raise ValueError(msg)
|
| 714 |
+
subsampling = get_sampling(im)
|
| 715 |
+
|
| 716 |
+
def validate_qtables(
|
| 717 |
+
qtables: (
|
| 718 |
+
str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None
|
| 719 |
+
),
|
| 720 |
+
) -> list[list[int]] | None:
|
| 721 |
+
if qtables is None:
|
| 722 |
+
return qtables
|
| 723 |
+
if isinstance(qtables, str):
|
| 724 |
+
try:
|
| 725 |
+
lines = [
|
| 726 |
+
int(num)
|
| 727 |
+
for line in qtables.splitlines()
|
| 728 |
+
for num in line.split("#", 1)[0].split()
|
| 729 |
+
]
|
| 730 |
+
except ValueError as e:
|
| 731 |
+
msg = "Invalid quantization table"
|
| 732 |
+
raise ValueError(msg) from e
|
| 733 |
+
else:
|
| 734 |
+
qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]
|
| 735 |
+
if isinstance(qtables, (tuple, list, dict)):
|
| 736 |
+
if isinstance(qtables, dict):
|
| 737 |
+
qtables = [
|
| 738 |
+
qtables[key] for key in range(len(qtables)) if key in qtables
|
| 739 |
+
]
|
| 740 |
+
elif isinstance(qtables, tuple):
|
| 741 |
+
qtables = list(qtables)
|
| 742 |
+
if not (0 < len(qtables) < 5):
|
| 743 |
+
msg = "None or too many quantization tables"
|
| 744 |
+
raise ValueError(msg)
|
| 745 |
+
for idx, table in enumerate(qtables):
|
| 746 |
+
try:
|
| 747 |
+
if len(table) != 64:
|
| 748 |
+
msg = "Invalid quantization table"
|
| 749 |
+
raise TypeError(msg)
|
| 750 |
+
table_array = array.array("H", table)
|
| 751 |
+
except TypeError as e:
|
| 752 |
+
msg = "Invalid quantization table"
|
| 753 |
+
raise ValueError(msg) from e
|
| 754 |
+
else:
|
| 755 |
+
qtables[idx] = list(table_array)
|
| 756 |
+
return qtables
|
| 757 |
+
|
| 758 |
+
if qtables == "keep":
|
| 759 |
+
if im.format != "JPEG":
|
| 760 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 761 |
+
raise ValueError(msg)
|
| 762 |
+
qtables = getattr(im, "quantization", None)
|
| 763 |
+
qtables = validate_qtables(qtables)
|
| 764 |
+
|
| 765 |
+
extra = info.get("extra", b"")
|
| 766 |
+
|
| 767 |
+
MAX_BYTES_IN_MARKER = 65533
|
| 768 |
+
if xmp := info.get("xmp"):
|
| 769 |
+
overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00"
|
| 770 |
+
max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
|
| 771 |
+
if len(xmp) > max_data_bytes_in_marker:
|
| 772 |
+
msg = "XMP data is too long"
|
| 773 |
+
raise ValueError(msg)
|
| 774 |
+
size = o16(2 + overhead_len + len(xmp))
|
| 775 |
+
extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp
|
| 776 |
+
|
| 777 |
+
if icc_profile := info.get("icc_profile"):
|
| 778 |
+
overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers))
|
| 779 |
+
max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
|
| 780 |
+
markers = []
|
| 781 |
+
while icc_profile:
|
| 782 |
+
markers.append(icc_profile[:max_data_bytes_in_marker])
|
| 783 |
+
icc_profile = icc_profile[max_data_bytes_in_marker:]
|
| 784 |
+
i = 1
|
| 785 |
+
for marker in markers:
|
| 786 |
+
size = o16(2 + overhead_len + len(marker))
|
| 787 |
+
extra += (
|
| 788 |
+
b"\xff\xe2"
|
| 789 |
+
+ size
|
| 790 |
+
+ b"ICC_PROFILE\0"
|
| 791 |
+
+ o8(i)
|
| 792 |
+
+ o8(len(markers))
|
| 793 |
+
+ marker
|
| 794 |
+
)
|
| 795 |
+
i += 1
|
| 796 |
+
|
| 797 |
+
comment = info.get("comment", im.info.get("comment"))
|
| 798 |
+
|
| 799 |
+
# "progressive" is the official name, but older documentation
|
| 800 |
+
# says "progression"
|
| 801 |
+
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
|
| 802 |
+
progressive = info.get("progressive", False) or info.get("progression", False)
|
| 803 |
+
|
| 804 |
+
optimize = info.get("optimize", False)
|
| 805 |
+
|
| 806 |
+
exif = info.get("exif", b"")
|
| 807 |
+
if isinstance(exif, Image.Exif):
|
| 808 |
+
exif = exif.tobytes()
|
| 809 |
+
if len(exif) > MAX_BYTES_IN_MARKER:
|
| 810 |
+
msg = "EXIF data is too long"
|
| 811 |
+
raise ValueError(msg)
|
| 812 |
+
|
| 813 |
+
# get keyword arguments
|
| 814 |
+
im.encoderconfig = (
|
| 815 |
+
quality,
|
| 816 |
+
progressive,
|
| 817 |
+
info.get("smooth", 0),
|
| 818 |
+
optimize,
|
| 819 |
+
info.get("keep_rgb", False),
|
| 820 |
+
info.get("streamtype", 0),
|
| 821 |
+
dpi,
|
| 822 |
+
subsampling,
|
| 823 |
+
info.get("restart_marker_blocks", 0),
|
| 824 |
+
info.get("restart_marker_rows", 0),
|
| 825 |
+
qtables,
|
| 826 |
+
comment,
|
| 827 |
+
extra,
|
| 828 |
+
exif,
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# if we optimize, libjpeg needs a buffer big enough to hold the whole image
|
| 832 |
+
# in a shot. Guessing on the size, at im.size bytes. (raw pixel size is
|
| 833 |
+
# channels*size, this is a value that's been used in a django patch.
|
| 834 |
+
# https://github.com/matthewwithanm/django-imagekit/issues/50
|
| 835 |
+
if optimize or progressive:
|
| 836 |
+
# CMYK can be bigger
|
| 837 |
+
if im.mode == "CMYK":
|
| 838 |
+
bufsize = 4 * im.size[0] * im.size[1]
|
| 839 |
+
# keep sets quality to -1, but the actual value may be high.
|
| 840 |
+
elif quality >= 95 or quality == -1:
|
| 841 |
+
bufsize = 2 * im.size[0] * im.size[1]
|
| 842 |
+
else:
|
| 843 |
+
bufsize = im.size[0] * im.size[1]
|
| 844 |
+
if exif:
|
| 845 |
+
bufsize += len(exif) + 5
|
| 846 |
+
if extra:
|
| 847 |
+
bufsize += len(extra) + 1
|
| 848 |
+
else:
|
| 849 |
+
# The EXIF info needs to be written as one block, + APP1, + one spare byte.
|
| 850 |
+
# Ensure that our buffer is big enough. Same with the icc_profile block.
|
| 851 |
+
bufsize = max(len(exif) + 5, len(extra) + 1)
|
| 852 |
+
|
| 853 |
+
ImageFile._save(
|
| 854 |
+
im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
##
|
| 859 |
+
# Factory for making JPEG and MPO instances
|
| 860 |
+
def jpeg_factory(
|
| 861 |
+
fp: IO[bytes], filename: str | bytes | None = None
|
| 862 |
+
) -> JpegImageFile | MpoImageFile:
|
| 863 |
+
im = JpegImageFile(fp, filename)
|
| 864 |
+
try:
|
| 865 |
+
mpheader = im._getmp()
|
| 866 |
+
if mpheader is not None and mpheader[45057] > 1:
|
| 867 |
+
for segment, content in im.applist:
|
| 868 |
+
if segment == "APP1" and b' hdrgm:Version="' in content:
|
| 869 |
+
# Ultra HDR images are not yet supported
|
| 870 |
+
return im
|
| 871 |
+
# It's actually an MPO
|
| 872 |
+
from .MpoImagePlugin import MpoImageFile
|
| 873 |
+
|
| 874 |
+
# Don't reload everything, just convert it.
|
| 875 |
+
im = MpoImageFile.adopt(im, mpheader)
|
| 876 |
+
except (TypeError, IndexError):
|
| 877 |
+
# It is really a JPEG
|
| 878 |
+
pass
|
| 879 |
+
except SyntaxError:
|
| 880 |
+
warnings.warn(
|
| 881 |
+
"Image appears to be a malformed MPO file, it will be "
|
| 882 |
+
"interpreted as a base JPEG file"
|
| 883 |
+
)
|
| 884 |
+
return im
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
# ---------------------------------------------------------------------
|
| 888 |
+
# Registry stuff
|
| 889 |
+
|
| 890 |
+
Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
|
| 891 |
+
Image.register_save(JpegImageFile.format, _save)
|
| 892 |
+
|
| 893 |
+
Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])
|
| 894 |
+
|
| 895 |
+
Image.register_mime(JpegImageFile.format, "image/jpeg")
|
workspace/outputs/audit_venv/lib/python3.11/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, 12]
|
| 240 |
+
]},
|
| 241 |
+
}
|
| 242 |
+
# fmt: on
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Basic McIdas support for PIL
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1997-05-05 fl Created (8-bit images only)
|
| 9 |
+
# 2009-03-08 fl Added 16/32-bit support.
|
| 10 |
+
#
|
| 11 |
+
# Thanks to Richard Jones and Craig Swank for specs and samples.
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import struct
|
| 21 |
+
|
| 22 |
+
from . import Image, ImageFile
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _accept(prefix: bytes) -> bool:
|
| 26 |
+
return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
##
|
| 30 |
+
# Image plugin for McIdas area images.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class McIdasImageFile(ImageFile.ImageFile):
|
| 34 |
+
format = "MCIDAS"
|
| 35 |
+
format_description = "McIdas area file"
|
| 36 |
+
|
| 37 |
+
def _open(self) -> None:
|
| 38 |
+
# parse area file directory
|
| 39 |
+
assert self.fp is not None
|
| 40 |
+
|
| 41 |
+
s = self.fp.read(256)
|
| 42 |
+
if not _accept(s) or len(s) != 256:
|
| 43 |
+
msg = "not an McIdas area file"
|
| 44 |
+
raise SyntaxError(msg)
|
| 45 |
+
|
| 46 |
+
self.area_descriptor_raw = s
|
| 47 |
+
self.area_descriptor = w = [0, *struct.unpack("!64i", s)]
|
| 48 |
+
|
| 49 |
+
# get mode
|
| 50 |
+
if w[11] == 1:
|
| 51 |
+
mode = rawmode = "L"
|
| 52 |
+
elif w[11] == 2:
|
| 53 |
+
mode = rawmode = "I;16B"
|
| 54 |
+
elif w[11] == 4:
|
| 55 |
+
# FIXME: add memory map support
|
| 56 |
+
mode = "I"
|
| 57 |
+
rawmode = "I;32B"
|
| 58 |
+
else:
|
| 59 |
+
msg = "unsupported McIdas format"
|
| 60 |
+
raise SyntaxError(msg)
|
| 61 |
+
|
| 62 |
+
self._mode = mode
|
| 63 |
+
self._size = w[10], w[9]
|
| 64 |
+
|
| 65 |
+
offset = w[34] + w[15]
|
| 66 |
+
stride = w[15] + w[10] * w[11] * w[14]
|
| 67 |
+
|
| 68 |
+
self.tile = [
|
| 69 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# --------------------------------------------------------------------
|
| 74 |
+
# registry
|
| 75 |
+
|
| 76 |
+
Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept)
|
| 77 |
+
|
| 78 |
+
# no default extension
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MicImagePlugin.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Microsoft Image Composer support for PIL
|
| 6 |
+
#
|
| 7 |
+
# Notes:
|
| 8 |
+
# uses TiffImagePlugin.py to read the actual image streams
|
| 9 |
+
#
|
| 10 |
+
# History:
|
| 11 |
+
# 97-01-20 fl Created
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import olefile
|
| 21 |
+
|
| 22 |
+
from . import Image, TiffImagePlugin
|
| 23 |
+
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _accept(prefix: bytes) -> bool:
|
| 29 |
+
return prefix.startswith(olefile.MAGIC)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
##
|
| 33 |
+
# Image plugin for Microsoft's Image Composer file format.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MicImageFile(TiffImagePlugin.TiffImageFile):
|
| 37 |
+
format = "MIC"
|
| 38 |
+
format_description = "Microsoft Image Composer"
|
| 39 |
+
_close_exclusive_fp_after_loading = False
|
| 40 |
+
|
| 41 |
+
def _open(self) -> None:
|
| 42 |
+
# read the OLE directory and see if this is a likely
|
| 43 |
+
# to be a Microsoft Image Composer file
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
self.ole = olefile.OleFileIO(self.fp)
|
| 47 |
+
except OSError as e:
|
| 48 |
+
msg = "not an MIC file; invalid OLE file"
|
| 49 |
+
raise SyntaxError(msg) from e
|
| 50 |
+
|
| 51 |
+
# find ACI subfiles with Image members (maybe not the
|
| 52 |
+
# best way to identify MIC files, but what the... ;-)
|
| 53 |
+
|
| 54 |
+
self.images = [
|
| 55 |
+
path
|
| 56 |
+
for path in self.ole.listdir()
|
| 57 |
+
if path[1:] and path[0].endswith(".ACI") and path[1] == "Image"
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
# if we didn't find any images, this is probably not
|
| 61 |
+
# an MIC file.
|
| 62 |
+
if not self.images:
|
| 63 |
+
msg = "not an MIC file; no image entries"
|
| 64 |
+
raise SyntaxError(msg)
|
| 65 |
+
|
| 66 |
+
self.frame = -1
|
| 67 |
+
self._n_frames = len(self.images)
|
| 68 |
+
self.is_animated = self._n_frames > 1
|
| 69 |
+
|
| 70 |
+
assert self.fp is not None
|
| 71 |
+
self.__fp = self.fp
|
| 72 |
+
self.seek(0)
|
| 73 |
+
|
| 74 |
+
def seek(self, frame: int) -> None:
|
| 75 |
+
if not self._seek_check(frame):
|
| 76 |
+
return
|
| 77 |
+
filename = self.images[frame]
|
| 78 |
+
self.fp = self.ole.openstream(filename)
|
| 79 |
+
|
| 80 |
+
TiffImagePlugin.TiffImageFile._open(self)
|
| 81 |
+
|
| 82 |
+
self.frame = frame
|
| 83 |
+
|
| 84 |
+
def tell(self) -> int:
|
| 85 |
+
return self.frame
|
| 86 |
+
|
| 87 |
+
def close(self) -> None:
|
| 88 |
+
self.__fp.close()
|
| 89 |
+
self.ole.close()
|
| 90 |
+
super().close()
|
| 91 |
+
|
| 92 |
+
def __exit__(self, *args: object) -> None:
|
| 93 |
+
self.__fp.close()
|
| 94 |
+
self.ole.close()
|
| 95 |
+
super().__exit__()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
#
|
| 99 |
+
# --------------------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
Image.register_open(MicImageFile.format, MicImageFile, _accept)
|
| 102 |
+
|
| 103 |
+
Image.register_extension(MicImageFile.format, ".mic")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# MPEG file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-09-09 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1995.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from . import Image, ImageFile
|
| 18 |
+
from ._binary import i8
|
| 19 |
+
from ._typing import SupportsRead
|
| 20 |
+
|
| 21 |
+
#
|
| 22 |
+
# Bitstream parser
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BitStream:
|
| 26 |
+
def __init__(self, fp: SupportsRead[bytes]) -> None:
|
| 27 |
+
self.fp = fp
|
| 28 |
+
self.bits = 0
|
| 29 |
+
self.bitbuffer = 0
|
| 30 |
+
|
| 31 |
+
def next(self) -> int:
|
| 32 |
+
return i8(self.fp.read(1))
|
| 33 |
+
|
| 34 |
+
def peek(self, bits: int) -> int:
|
| 35 |
+
while self.bits < bits:
|
| 36 |
+
self.bitbuffer = (self.bitbuffer << 8) + self.next()
|
| 37 |
+
self.bits += 8
|
| 38 |
+
return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1
|
| 39 |
+
|
| 40 |
+
def skip(self, bits: int) -> None:
|
| 41 |
+
while self.bits < bits:
|
| 42 |
+
self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1))
|
| 43 |
+
self.bits += 8
|
| 44 |
+
self.bits = self.bits - bits
|
| 45 |
+
|
| 46 |
+
def read(self, bits: int) -> int:
|
| 47 |
+
v = self.peek(bits)
|
| 48 |
+
self.bits = self.bits - bits
|
| 49 |
+
return v
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _accept(prefix: bytes) -> bool:
|
| 53 |
+
return prefix.startswith(b"\x00\x00\x01\xb3")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
##
|
| 57 |
+
# Image plugin for MPEG streams. This plugin can identify a stream,
|
| 58 |
+
# but it cannot read it.
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class MpegImageFile(ImageFile.ImageFile):
|
| 62 |
+
format = "MPEG"
|
| 63 |
+
format_description = "MPEG"
|
| 64 |
+
|
| 65 |
+
def _open(self) -> None:
|
| 66 |
+
assert self.fp is not None
|
| 67 |
+
|
| 68 |
+
s = BitStream(self.fp)
|
| 69 |
+
if s.read(32) != 0x1B3:
|
| 70 |
+
msg = "not an MPEG file"
|
| 71 |
+
raise SyntaxError(msg)
|
| 72 |
+
|
| 73 |
+
self._mode = "RGB"
|
| 74 |
+
self._size = s.read(12), s.read(12)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --------------------------------------------------------------------
|
| 78 |
+
# Registry stuff
|
| 79 |
+
|
| 80 |
+
Image.register_open(MpegImageFile.format, MpegImageFile, _accept)
|
| 81 |
+
|
| 82 |
+
Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
|
| 83 |
+
|
| 84 |
+
Image.register_mime(MpegImageFile.format, "video/mpeg")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ling
|
| 6 |
+
#
|
| 7 |
+
# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the
|
| 8 |
+
# Camera & Imaging Products Association)
|
| 9 |
+
#
|
| 10 |
+
# The multi-picture object combines multiple JPEG images (with a modified EXIF
|
| 11 |
+
# data format) into a single file. While it can theoretically be used much like
|
| 12 |
+
# a GIF animation, it is commonly used to represent 3D photographs and is (as
|
| 13 |
+
# of this writing) the most commonly used format by 3D cameras.
|
| 14 |
+
#
|
| 15 |
+
# History:
|
| 16 |
+
# 2014-03-13 Feneric Created
|
| 17 |
+
#
|
| 18 |
+
# See the README file for information on usage and redistribution.
|
| 19 |
+
#
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
import struct
|
| 24 |
+
from typing import IO, Any, cast
|
| 25 |
+
|
| 26 |
+
from . import (
|
| 27 |
+
Image,
|
| 28 |
+
ImageFile,
|
| 29 |
+
ImageSequence,
|
| 30 |
+
JpegImagePlugin,
|
| 31 |
+
TiffImagePlugin,
|
| 32 |
+
)
|
| 33 |
+
from ._binary import o32le
|
| 34 |
+
from ._util import DeferredError
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 38 |
+
JpegImagePlugin._save(im, fp, filename)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 42 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 43 |
+
if not append_images and not getattr(im, "is_animated", False):
|
| 44 |
+
_save(im, fp, filename)
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
mpf_offset = 28
|
| 48 |
+
offsets: list[int] = []
|
| 49 |
+
im_sequences = [im, *append_images]
|
| 50 |
+
total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences)
|
| 51 |
+
for im_sequence in im_sequences:
|
| 52 |
+
for im_frame in ImageSequence.Iterator(im_sequence):
|
| 53 |
+
if not offsets:
|
| 54 |
+
# APP2 marker
|
| 55 |
+
ifd_length = 66 + 16 * total
|
| 56 |
+
im_frame.encoderinfo["extra"] = (
|
| 57 |
+
b"\xff\xe2"
|
| 58 |
+
+ struct.pack(">H", 6 + ifd_length)
|
| 59 |
+
+ b"MPF\0"
|
| 60 |
+
+ b" " * ifd_length
|
| 61 |
+
)
|
| 62 |
+
exif = im_frame.encoderinfo.get("exif")
|
| 63 |
+
if isinstance(exif, Image.Exif):
|
| 64 |
+
exif = exif.tobytes()
|
| 65 |
+
im_frame.encoderinfo["exif"] = exif
|
| 66 |
+
if exif:
|
| 67 |
+
mpf_offset += 4 + len(exif)
|
| 68 |
+
|
| 69 |
+
JpegImagePlugin._save(im_frame, fp, filename)
|
| 70 |
+
offsets.append(fp.tell())
|
| 71 |
+
else:
|
| 72 |
+
encoderinfo = im_frame._attach_default_encoderinfo(im)
|
| 73 |
+
im_frame.save(fp, "JPEG")
|
| 74 |
+
im_frame.encoderinfo = encoderinfo
|
| 75 |
+
offsets.append(fp.tell() - offsets[-1])
|
| 76 |
+
|
| 77 |
+
ifd = TiffImagePlugin.ImageFileDirectory_v2()
|
| 78 |
+
ifd[0xB000] = b"0100"
|
| 79 |
+
ifd[0xB001] = len(offsets)
|
| 80 |
+
|
| 81 |
+
mpentries = b""
|
| 82 |
+
data_offset = 0
|
| 83 |
+
for i, size in enumerate(offsets):
|
| 84 |
+
if i == 0:
|
| 85 |
+
mptype = 0x030000 # Baseline MP Primary Image
|
| 86 |
+
else:
|
| 87 |
+
mptype = 0x000000 # Undefined
|
| 88 |
+
mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)
|
| 89 |
+
if i == 0:
|
| 90 |
+
data_offset -= mpf_offset
|
| 91 |
+
data_offset += size
|
| 92 |
+
ifd[0xB002] = mpentries
|
| 93 |
+
|
| 94 |
+
fp.seek(mpf_offset)
|
| 95 |
+
fp.write(b"II\x2a\x00" + o32le(8) + ifd.tobytes(8))
|
| 96 |
+
fp.seek(0, os.SEEK_END)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
##
|
| 100 |
+
# Image plugin for MPO images.
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class MpoImageFile(JpegImagePlugin.JpegImageFile):
|
| 104 |
+
format = "MPO"
|
| 105 |
+
format_description = "MPO (CIPA DC-007)"
|
| 106 |
+
_close_exclusive_fp_after_loading = False
|
| 107 |
+
|
| 108 |
+
def _open(self) -> None:
|
| 109 |
+
assert self.fp is not None
|
| 110 |
+
self.fp.seek(0) # prep the fp in order to pass the JPEG test
|
| 111 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 112 |
+
self._after_jpeg_open()
|
| 113 |
+
|
| 114 |
+
def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:
|
| 115 |
+
self.mpinfo = mpheader if mpheader is not None else self._getmp()
|
| 116 |
+
if self.mpinfo is None:
|
| 117 |
+
msg = "Image appears to be a malformed MPO file"
|
| 118 |
+
raise ValueError(msg)
|
| 119 |
+
self.n_frames = self.mpinfo[0xB001]
|
| 120 |
+
self.__mpoffsets = [
|
| 121 |
+
mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
|
| 122 |
+
]
|
| 123 |
+
self.__mpoffsets[0] = 0
|
| 124 |
+
# Note that the following assertion will only be invalid if something
|
| 125 |
+
# gets broken within JpegImagePlugin.
|
| 126 |
+
assert self.n_frames == len(self.__mpoffsets)
|
| 127 |
+
del self.info["mpoffset"] # no longer needed
|
| 128 |
+
self.is_animated = self.n_frames > 1
|
| 129 |
+
assert self.fp is not None
|
| 130 |
+
self._fp = self.fp # FIXME: hack
|
| 131 |
+
self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
|
| 132 |
+
self.__frame = 0
|
| 133 |
+
self.offset = 0
|
| 134 |
+
# for now we can only handle reading and individual frame extraction
|
| 135 |
+
self.readonly = 1
|
| 136 |
+
|
| 137 |
+
def load_seek(self, pos: int) -> None:
|
| 138 |
+
if isinstance(self._fp, DeferredError):
|
| 139 |
+
raise self._fp.ex
|
| 140 |
+
self._fp.seek(pos)
|
| 141 |
+
|
| 142 |
+
def seek(self, frame: int) -> None:
|
| 143 |
+
if not self._seek_check(frame):
|
| 144 |
+
return
|
| 145 |
+
if isinstance(self._fp, DeferredError):
|
| 146 |
+
raise self._fp.ex
|
| 147 |
+
self.fp = self._fp
|
| 148 |
+
self.offset = self.__mpoffsets[frame]
|
| 149 |
+
|
| 150 |
+
original_exif = self.info.get("exif")
|
| 151 |
+
if "exif" in self.info:
|
| 152 |
+
del self.info["exif"]
|
| 153 |
+
|
| 154 |
+
self.fp.seek(self.offset + 2) # skip SOI marker
|
| 155 |
+
if not self.fp.read(2):
|
| 156 |
+
msg = "No data found for frame"
|
| 157 |
+
raise ValueError(msg)
|
| 158 |
+
self.fp.seek(self.offset)
|
| 159 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 160 |
+
if self.info.get("exif") != original_exif:
|
| 161 |
+
self._reload_exif()
|
| 162 |
+
|
| 163 |
+
self.tile = [
|
| 164 |
+
ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])
|
| 165 |
+
]
|
| 166 |
+
self.__frame = frame
|
| 167 |
+
|
| 168 |
+
def tell(self) -> int:
|
| 169 |
+
return self.__frame
|
| 170 |
+
|
| 171 |
+
@staticmethod
|
| 172 |
+
def adopt(
|
| 173 |
+
jpeg_instance: JpegImagePlugin.JpegImageFile,
|
| 174 |
+
mpheader: dict[int, Any] | None = None,
|
| 175 |
+
) -> MpoImageFile:
|
| 176 |
+
"""
|
| 177 |
+
Transform the instance of JpegImageFile into
|
| 178 |
+
an instance of MpoImageFile.
|
| 179 |
+
After the call, the JpegImageFile is extended
|
| 180 |
+
to be an MpoImageFile.
|
| 181 |
+
|
| 182 |
+
This is essentially useful when opening a JPEG
|
| 183 |
+
file that reveals itself as an MPO, to avoid
|
| 184 |
+
double call to _open.
|
| 185 |
+
"""
|
| 186 |
+
jpeg_instance.__class__ = MpoImageFile
|
| 187 |
+
mpo_instance = cast(MpoImageFile, jpeg_instance)
|
| 188 |
+
mpo_instance._after_jpeg_open(mpheader)
|
| 189 |
+
return mpo_instance
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ---------------------------------------------------------------------
|
| 193 |
+
# Registry stuff
|
| 194 |
+
|
| 195 |
+
# Note that since MPO shares a factory with JPEG, we do not need to do a
|
| 196 |
+
# separate registration for it here.
|
| 197 |
+
# Image.register_open(MpoImageFile.format,
|
| 198 |
+
# JpegImagePlugin.jpeg_factory, _accept)
|
| 199 |
+
Image.register_save(MpoImageFile.format, _save)
|
| 200 |
+
Image.register_save_all(MpoImageFile.format, _save_all)
|
| 201 |
+
|
| 202 |
+
Image.register_extension(MpoImageFile.format, ".mpo")
|
| 203 |
+
|
| 204 |
+
Image.register_mime(MpoImageFile.format, "image/mpo")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
#
|
| 4 |
+
# MSP file handling
|
| 5 |
+
#
|
| 6 |
+
# This is the format used by the Paint program in Windows 1 and 2.
|
| 7 |
+
#
|
| 8 |
+
# History:
|
| 9 |
+
# 95-09-05 fl Created
|
| 10 |
+
# 97-01-03 fl Read/write MSP images
|
| 11 |
+
# 17-02-21 es Fixed RLE interpretation
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
| 15 |
+
# Copyright (c) Eric Soroos 2017.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
# More info on this format: https://archive.org/details/gg243631
|
| 20 |
+
# Page 313:
|
| 21 |
+
# Figure 205. Windows Paint Version 1: "DanM" Format
|
| 22 |
+
# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03
|
| 23 |
+
#
|
| 24 |
+
# See also: https://www.fileformat.info/format/mspaint/egff.htm
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import io
|
| 28 |
+
import struct
|
| 29 |
+
from typing import IO
|
| 30 |
+
|
| 31 |
+
from . import Image, ImageFile
|
| 32 |
+
from ._binary import i16le as i16
|
| 33 |
+
from ._binary import o16le as o16
|
| 34 |
+
|
| 35 |
+
#
|
| 36 |
+
# read MSP files
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _accept(prefix: bytes) -> bool:
|
| 40 |
+
return prefix.startswith((b"DanM", b"LinS"))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
##
|
| 44 |
+
# Image plugin for Windows MSP images. This plugin supports both
|
| 45 |
+
# uncompressed (Windows 1.0).
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MspImageFile(ImageFile.ImageFile):
|
| 49 |
+
format = "MSP"
|
| 50 |
+
format_description = "Windows Paint"
|
| 51 |
+
|
| 52 |
+
def _open(self) -> None:
|
| 53 |
+
# Header
|
| 54 |
+
assert self.fp is not None
|
| 55 |
+
|
| 56 |
+
s = self.fp.read(32)
|
| 57 |
+
if not _accept(s):
|
| 58 |
+
msg = "not an MSP file"
|
| 59 |
+
raise SyntaxError(msg)
|
| 60 |
+
|
| 61 |
+
# Header checksum
|
| 62 |
+
checksum = 0
|
| 63 |
+
for i in range(0, 32, 2):
|
| 64 |
+
checksum = checksum ^ i16(s, i)
|
| 65 |
+
if checksum != 0:
|
| 66 |
+
msg = "bad MSP checksum"
|
| 67 |
+
raise SyntaxError(msg)
|
| 68 |
+
|
| 69 |
+
self._mode = "1"
|
| 70 |
+
self._size = i16(s, 4), i16(s, 6)
|
| 71 |
+
|
| 72 |
+
if s.startswith(b"DanM"):
|
| 73 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")]
|
| 74 |
+
else:
|
| 75 |
+
self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class MspDecoder(ImageFile.PyDecoder):
|
| 79 |
+
# The algo for the MSP decoder is from
|
| 80 |
+
# https://www.fileformat.info/format/mspaint/egff.htm
|
| 81 |
+
# cc-by-attribution -- That page references is taken from the
|
| 82 |
+
# Encyclopedia of Graphics File Formats and is licensed by
|
| 83 |
+
# O'Reilly under the Creative Common/Attribution license
|
| 84 |
+
#
|
| 85 |
+
# For RLE encoded files, the 32byte header is followed by a scan
|
| 86 |
+
# line map, encoded as one 16bit word of encoded byte length per
|
| 87 |
+
# line.
|
| 88 |
+
#
|
| 89 |
+
# NOTE: the encoded length of the line can be 0. This was not
|
| 90 |
+
# handled in the previous version of this encoder, and there's no
|
| 91 |
+
# mention of how to handle it in the documentation. From the few
|
| 92 |
+
# examples I've seen, I've assumed that it is a fill of the
|
| 93 |
+
# background color, in this case, white.
|
| 94 |
+
#
|
| 95 |
+
#
|
| 96 |
+
# Pseudocode of the decoder:
|
| 97 |
+
# Read a BYTE value as the RunType
|
| 98 |
+
# If the RunType value is zero
|
| 99 |
+
# Read next byte as the RunCount
|
| 100 |
+
# Read the next byte as the RunValue
|
| 101 |
+
# Write the RunValue byte RunCount times
|
| 102 |
+
# If the RunType value is non-zero
|
| 103 |
+
# Use this value as the RunCount
|
| 104 |
+
# Read and write the next RunCount bytes literally
|
| 105 |
+
#
|
| 106 |
+
# e.g.:
|
| 107 |
+
# 0x00 03 ff 05 00 01 02 03 04
|
| 108 |
+
# would yield the bytes:
|
| 109 |
+
# 0xff ff ff 00 01 02 03 04
|
| 110 |
+
#
|
| 111 |
+
# which are then interpreted as a bit packed mode '1' image
|
| 112 |
+
|
| 113 |
+
_pulls_fd = True
|
| 114 |
+
|
| 115 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 116 |
+
assert self.fd is not None
|
| 117 |
+
|
| 118 |
+
img = io.BytesIO()
|
| 119 |
+
blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8))
|
| 120 |
+
try:
|
| 121 |
+
self.fd.seek(32)
|
| 122 |
+
rowmap = struct.unpack_from(
|
| 123 |
+
f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2)
|
| 124 |
+
)
|
| 125 |
+
except struct.error as e:
|
| 126 |
+
msg = "Truncated MSP file in row map"
|
| 127 |
+
raise OSError(msg) from e
|
| 128 |
+
|
| 129 |
+
for x, rowlen in enumerate(rowmap):
|
| 130 |
+
try:
|
| 131 |
+
if rowlen == 0:
|
| 132 |
+
img.write(blank_line)
|
| 133 |
+
continue
|
| 134 |
+
row = self.fd.read(rowlen)
|
| 135 |
+
if len(row) != rowlen:
|
| 136 |
+
msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}"
|
| 137 |
+
raise OSError(msg)
|
| 138 |
+
idx = 0
|
| 139 |
+
while idx < rowlen:
|
| 140 |
+
runtype = row[idx]
|
| 141 |
+
idx += 1
|
| 142 |
+
if runtype == 0:
|
| 143 |
+
(runcount, runval) = struct.unpack_from("Bc", row, idx)
|
| 144 |
+
img.write(runval * runcount)
|
| 145 |
+
idx += 2
|
| 146 |
+
else:
|
| 147 |
+
runcount = runtype
|
| 148 |
+
img.write(row[idx : idx + runcount])
|
| 149 |
+
idx += runcount
|
| 150 |
+
|
| 151 |
+
except struct.error as e:
|
| 152 |
+
msg = f"Corrupted MSP file in row {x}"
|
| 153 |
+
raise OSError(msg) from e
|
| 154 |
+
|
| 155 |
+
self.set_as_raw(img.getvalue(), "1")
|
| 156 |
+
|
| 157 |
+
return -1, 0
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
Image.register_decoder("MSP", MspDecoder)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
#
|
| 164 |
+
# write MSP files (uncompressed only)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 168 |
+
if im.mode != "1":
|
| 169 |
+
msg = f"cannot write mode {im.mode} as MSP"
|
| 170 |
+
raise OSError(msg)
|
| 171 |
+
|
| 172 |
+
# create MSP header
|
| 173 |
+
header = [0] * 16
|
| 174 |
+
|
| 175 |
+
header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1
|
| 176 |
+
header[2], header[3] = im.size
|
| 177 |
+
header[4], header[5] = 1, 1
|
| 178 |
+
header[6], header[7] = 1, 1
|
| 179 |
+
header[8], header[9] = im.size
|
| 180 |
+
|
| 181 |
+
checksum = 0
|
| 182 |
+
for h in header:
|
| 183 |
+
checksum = checksum ^ h
|
| 184 |
+
header[12] = checksum # FIXME: is this the right field?
|
| 185 |
+
|
| 186 |
+
# header
|
| 187 |
+
for h in header:
|
| 188 |
+
fp.write(o16(h))
|
| 189 |
+
|
| 190 |
+
# image body
|
| 191 |
+
ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 32, "1")])
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
#
|
| 195 |
+
# registry
|
| 196 |
+
|
| 197 |
+
Image.register_open(MspImageFile.format, MspImageFile, _accept)
|
| 198 |
+
Image.register_save(MspImageFile.format, _save)
|
| 199 |
+
|
| 200 |
+
Image.register_extension(MspImageFile.format, ".msp")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PSDraw.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Simple PostScript graphics interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-20 fl Created
|
| 9 |
+
# 1999-01-10 fl Added gsave/grestore to image method
|
| 10 |
+
# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge)
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved.
|
| 13 |
+
# Copyright (c) 1996 by Fredrik Lundh.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import sys
|
| 20 |
+
from typing import IO
|
| 21 |
+
|
| 22 |
+
from . import EpsImagePlugin
|
| 23 |
+
|
| 24 |
+
TYPE_CHECKING = False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
##
|
| 28 |
+
# Simple PostScript graphics interface.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class PSDraw:
|
| 32 |
+
"""
|
| 33 |
+
Sets up printing to the given file. If ``fp`` is omitted,
|
| 34 |
+
``sys.stdout.buffer`` is assumed.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, fp: IO[bytes] | None = None) -> None:
|
| 38 |
+
if not fp:
|
| 39 |
+
fp = sys.stdout.buffer
|
| 40 |
+
self.fp = fp
|
| 41 |
+
|
| 42 |
+
def begin_document(self, id: str | None = None) -> None:
|
| 43 |
+
"""Set up printing of a document. (Write PostScript DSC header.)"""
|
| 44 |
+
# FIXME: incomplete
|
| 45 |
+
self.fp.write(
|
| 46 |
+
b"%!PS-Adobe-3.0\n"
|
| 47 |
+
b"save\n"
|
| 48 |
+
b"/showpage { } def\n"
|
| 49 |
+
b"%%EndComments\n"
|
| 50 |
+
b"%%BeginDocument\n"
|
| 51 |
+
)
|
| 52 |
+
# self.fp.write(ERROR_PS) # debugging!
|
| 53 |
+
self.fp.write(EDROFF_PS)
|
| 54 |
+
self.fp.write(VDI_PS)
|
| 55 |
+
self.fp.write(b"%%EndProlog\n")
|
| 56 |
+
self.isofont: dict[bytes, int] = {}
|
| 57 |
+
|
| 58 |
+
def end_document(self) -> None:
|
| 59 |
+
"""Ends printing. (Write PostScript DSC footer.)"""
|
| 60 |
+
self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n")
|
| 61 |
+
if hasattr(self.fp, "flush"):
|
| 62 |
+
self.fp.flush()
|
| 63 |
+
|
| 64 |
+
def setfont(self, font: str, size: int) -> None:
|
| 65 |
+
"""
|
| 66 |
+
Selects which font to use.
|
| 67 |
+
|
| 68 |
+
:param font: A PostScript font name
|
| 69 |
+
:param size: Size in points.
|
| 70 |
+
"""
|
| 71 |
+
font_bytes = bytes(font, "UTF-8")
|
| 72 |
+
if font_bytes not in self.isofont:
|
| 73 |
+
# reencode font
|
| 74 |
+
self.fp.write(
|
| 75 |
+
b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes)
|
| 76 |
+
)
|
| 77 |
+
self.isofont[font_bytes] = 1
|
| 78 |
+
# rough
|
| 79 |
+
self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes))
|
| 80 |
+
|
| 81 |
+
def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None:
|
| 82 |
+
"""
|
| 83 |
+
Draws a line between the two points. Coordinates are given in
|
| 84 |
+
PostScript point coordinates (72 points per inch, (0, 0) is the lower
|
| 85 |
+
left corner of the page).
|
| 86 |
+
"""
|
| 87 |
+
self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))
|
| 88 |
+
|
| 89 |
+
def rectangle(self, box: tuple[int, int, int, int]) -> None:
|
| 90 |
+
"""
|
| 91 |
+
Draws a rectangle.
|
| 92 |
+
|
| 93 |
+
:param box: A tuple of four integers, specifying left, bottom, width and
|
| 94 |
+
height.
|
| 95 |
+
"""
|
| 96 |
+
self.fp.write(b"%d %d M 0 %d %d Vr\n" % box)
|
| 97 |
+
|
| 98 |
+
def text(self, xy: tuple[int, int], text: str) -> None:
|
| 99 |
+
"""
|
| 100 |
+
Draws text at the given position. You must use
|
| 101 |
+
:py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
|
| 102 |
+
"""
|
| 103 |
+
text_bytes = bytes(text, "UTF-8")
|
| 104 |
+
text_bytes = b"\\(".join(text_bytes.split(b"("))
|
| 105 |
+
text_bytes = b"\\)".join(text_bytes.split(b")"))
|
| 106 |
+
self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,)))
|
| 107 |
+
|
| 108 |
+
if TYPE_CHECKING:
|
| 109 |
+
from . import Image
|
| 110 |
+
|
| 111 |
+
def image(
|
| 112 |
+
self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None
|
| 113 |
+
) -> None:
|
| 114 |
+
"""Draw a PIL image, centered in the given box."""
|
| 115 |
+
# default resolution depends on mode
|
| 116 |
+
if not dpi:
|
| 117 |
+
if im.mode == "1":
|
| 118 |
+
dpi = 200 # fax
|
| 119 |
+
else:
|
| 120 |
+
dpi = 100 # grayscale
|
| 121 |
+
# image size (on paper)
|
| 122 |
+
x = im.size[0] * 72 / dpi
|
| 123 |
+
y = im.size[1] * 72 / dpi
|
| 124 |
+
# max allowed size
|
| 125 |
+
xmax = float(box[2] - box[0])
|
| 126 |
+
ymax = float(box[3] - box[1])
|
| 127 |
+
if x > xmax:
|
| 128 |
+
y = y * xmax / x
|
| 129 |
+
x = xmax
|
| 130 |
+
if y > ymax:
|
| 131 |
+
x = x * ymax / y
|
| 132 |
+
y = ymax
|
| 133 |
+
dx = (xmax - x) / 2 + box[0]
|
| 134 |
+
dy = (ymax - y) / 2 + box[1]
|
| 135 |
+
self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy))
|
| 136 |
+
if (x, y) != im.size:
|
| 137 |
+
# EpsImagePlugin._save prints the image at (0,0,xsize,ysize)
|
| 138 |
+
sx = x / im.size[0]
|
| 139 |
+
sy = y / im.size[1]
|
| 140 |
+
self.fp.write(b"%f %f scale\n" % (sx, sy))
|
| 141 |
+
EpsImagePlugin._save(im, self.fp, "", 0)
|
| 142 |
+
self.fp.write(b"\ngrestore\n")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# --------------------------------------------------------------------
|
| 146 |
+
# PostScript driver
|
| 147 |
+
|
| 148 |
+
#
|
| 149 |
+
# EDROFF.PS -- PostScript driver for Edroff 2
|
| 150 |
+
#
|
| 151 |
+
# History:
|
| 152 |
+
# 94-01-25 fl: created (edroff 2.04)
|
| 153 |
+
#
|
| 154 |
+
# Copyright (c) Fredrik Lundh 1994.
|
| 155 |
+
#
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
EDROFF_PS = b"""\
|
| 159 |
+
/S { show } bind def
|
| 160 |
+
/P { moveto show } bind def
|
| 161 |
+
/M { moveto } bind def
|
| 162 |
+
/X { 0 rmoveto } bind def
|
| 163 |
+
/Y { 0 exch rmoveto } bind def
|
| 164 |
+
/E { findfont
|
| 165 |
+
dup maxlength dict begin
|
| 166 |
+
{
|
| 167 |
+
1 index /FID ne { def } { pop pop } ifelse
|
| 168 |
+
} forall
|
| 169 |
+
/Encoding exch def
|
| 170 |
+
dup /FontName exch def
|
| 171 |
+
currentdict end definefont pop
|
| 172 |
+
} bind def
|
| 173 |
+
/F { findfont exch scalefont dup setfont
|
| 174 |
+
[ exch /setfont cvx ] cvx bind def
|
| 175 |
+
} bind def
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
#
|
| 179 |
+
# VDI.PS -- PostScript driver for VDI meta commands
|
| 180 |
+
#
|
| 181 |
+
# History:
|
| 182 |
+
# 94-01-25 fl: created (edroff 2.04)
|
| 183 |
+
#
|
| 184 |
+
# Copyright (c) Fredrik Lundh 1994.
|
| 185 |
+
#
|
| 186 |
+
|
| 187 |
+
VDI_PS = b"""\
|
| 188 |
+
/Vm { moveto } bind def
|
| 189 |
+
/Va { newpath arcn stroke } bind def
|
| 190 |
+
/Vl { moveto lineto stroke } bind def
|
| 191 |
+
/Vc { newpath 0 360 arc closepath } bind def
|
| 192 |
+
/Vr { exch dup 0 rlineto
|
| 193 |
+
exch dup 0 exch rlineto
|
| 194 |
+
exch neg 0 rlineto
|
| 195 |
+
0 exch neg rlineto
|
| 196 |
+
setgray fill } bind def
|
| 197 |
+
/Tm matrix def
|
| 198 |
+
/Ve { Tm currentmatrix pop
|
| 199 |
+
translate scale newpath 0 0 .5 0 360 arc closepath
|
| 200 |
+
Tm setmatrix
|
| 201 |
+
} bind def
|
| 202 |
+
/Vf { currentgray exch setgray fill setgray } bind def
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
#
|
| 206 |
+
# ERROR.PS -- Error handler
|
| 207 |
+
#
|
| 208 |
+
# History:
|
| 209 |
+
# 89-11-21 fl: created (pslist 1.10)
|
| 210 |
+
#
|
| 211 |
+
|
| 212 |
+
ERROR_PS = b"""\
|
| 213 |
+
/landscape false def
|
| 214 |
+
/errorBUF 200 string def
|
| 215 |
+
/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def
|
| 216 |
+
errordict begin /handleerror {
|
| 217 |
+
initmatrix /Courier findfont 10 scalefont setfont
|
| 218 |
+
newpath 72 720 moveto $error begin /newerror false def
|
| 219 |
+
(PostScript Error) show errorNL errorNL
|
| 220 |
+
(Error: ) show
|
| 221 |
+
/errorname load errorBUF cvs show errorNL errorNL
|
| 222 |
+
(Command: ) show
|
| 223 |
+
/command load dup type /stringtype ne { errorBUF cvs } if show
|
| 224 |
+
errorNL errorNL
|
| 225 |
+
(VMstatus: ) show
|
| 226 |
+
vmstatus errorBUF cvs show ( bytes available, ) show
|
| 227 |
+
errorBUF cvs show ( bytes used at level ) show
|
| 228 |
+
errorBUF cvs show errorNL errorNL
|
| 229 |
+
(Operand stargck: ) show errorNL /ostargck load {
|
| 230 |
+
dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
|
| 231 |
+
} forall errorNL
|
| 232 |
+
(Execution stargck: ) show errorNL /estargck load {
|
| 233 |
+
dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
|
| 234 |
+
} forall
|
| 235 |
+
end showpage
|
| 236 |
+
} def end
|
| 237 |
+
"""
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PaletteFile.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# stuff to read simple, teragon-style palette files
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 97-08-23 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import IO
|
| 18 |
+
|
| 19 |
+
from ._binary import o8
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PaletteFile:
|
| 23 |
+
"""File handler for Teragon-style palette files."""
|
| 24 |
+
|
| 25 |
+
rawmode = "RGB"
|
| 26 |
+
|
| 27 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 28 |
+
palette = [o8(i) * 3 for i in range(256)]
|
| 29 |
+
|
| 30 |
+
while True:
|
| 31 |
+
s = fp.readline()
|
| 32 |
+
|
| 33 |
+
if not s:
|
| 34 |
+
break
|
| 35 |
+
if s.startswith(b"#"):
|
| 36 |
+
continue
|
| 37 |
+
if len(s) > 100:
|
| 38 |
+
msg = "bad palette file"
|
| 39 |
+
raise SyntaxError(msg)
|
| 40 |
+
|
| 41 |
+
v = [int(x) for x in s.split()]
|
| 42 |
+
try:
|
| 43 |
+
[i, r, g, b] = v
|
| 44 |
+
except ValueError:
|
| 45 |
+
[i, r] = v
|
| 46 |
+
g = b = r
|
| 47 |
+
|
| 48 |
+
if 0 <= i <= 255:
|
| 49 |
+
palette[i] = o8(r) + o8(g) + o8(b)
|
| 50 |
+
|
| 51 |
+
self.palette = b"".join(palette)
|
| 52 |
+
|
| 53 |
+
def getpalette(self) -> tuple[bytes, str]:
|
| 54 |
+
return self.palette, self.rawmode
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
|
| 6 |
+
##
|
| 7 |
+
# Image plugin for Palm pixmap images (output only).
|
| 8 |
+
##
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import IO
|
| 12 |
+
|
| 13 |
+
from . import Image, ImageFile
|
| 14 |
+
from ._binary import o8
|
| 15 |
+
from ._binary import o16be as o16b
|
| 16 |
+
|
| 17 |
+
# fmt: off
|
| 18 |
+
_Palm8BitColormapValues = (
|
| 19 |
+
(255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
|
| 20 |
+
(255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
|
| 21 |
+
(255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
|
| 22 |
+
(255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),
|
| 23 |
+
(255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),
|
| 24 |
+
(204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),
|
| 25 |
+
(204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),
|
| 26 |
+
(204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),
|
| 27 |
+
(204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),
|
| 28 |
+
(153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),
|
| 29 |
+
(153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),
|
| 30 |
+
(153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),
|
| 31 |
+
(153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),
|
| 32 |
+
(153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),
|
| 33 |
+
(102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),
|
| 34 |
+
(102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
|
| 35 |
+
(102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
|
| 36 |
+
(102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
|
| 37 |
+
(51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
|
| 38 |
+
(51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
|
| 39 |
+
(51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
|
| 40 |
+
(51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
|
| 41 |
+
(51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
|
| 42 |
+
(0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
|
| 43 |
+
(0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
|
| 44 |
+
(0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
|
| 45 |
+
(0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
|
| 46 |
+
(255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
|
| 47 |
+
(255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
|
| 48 |
+
(255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
|
| 49 |
+
(255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),
|
| 50 |
+
(255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),
|
| 51 |
+
(204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),
|
| 52 |
+
(204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),
|
| 53 |
+
(204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),
|
| 54 |
+
(204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),
|
| 55 |
+
(153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),
|
| 56 |
+
(153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),
|
| 57 |
+
(153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),
|
| 58 |
+
(153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),
|
| 59 |
+
(153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),
|
| 60 |
+
(102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),
|
| 61 |
+
(102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
|
| 62 |
+
(102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
|
| 63 |
+
(102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
|
| 64 |
+
(51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
|
| 65 |
+
(51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
|
| 66 |
+
(51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
|
| 67 |
+
(51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
|
| 68 |
+
(51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
|
| 69 |
+
(0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
|
| 70 |
+
(0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
|
| 71 |
+
(0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
|
| 72 |
+
(0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
|
| 73 |
+
(34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
|
| 74 |
+
(136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
|
| 75 |
+
(238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
|
| 76 |
+
(0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
|
| 77 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 78 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 79 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 80 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 81 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 82 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
|
| 83 |
+
# fmt: on
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# so build a prototype image to be used for palette resampling
|
| 87 |
+
def build_prototype_image() -> Image.Image:
|
| 88 |
+
image = Image.new("L", (1, len(_Palm8BitColormapValues)))
|
| 89 |
+
image.putdata(list(range(len(_Palm8BitColormapValues))))
|
| 90 |
+
palettedata: tuple[int, ...] = ()
|
| 91 |
+
for colormapValue in _Palm8BitColormapValues:
|
| 92 |
+
palettedata += colormapValue
|
| 93 |
+
palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))
|
| 94 |
+
image.putpalette(palettedata)
|
| 95 |
+
return image
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
Palm8BitColormapImage = build_prototype_image()
|
| 99 |
+
|
| 100 |
+
# OK, we now have in Palm8BitColormapImage,
|
| 101 |
+
# a "P"-mode image with the right palette
|
| 102 |
+
#
|
| 103 |
+
# --------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
|
| 106 |
+
|
| 107 |
+
_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
#
|
| 111 |
+
# --------------------------------------------------------------------
|
| 112 |
+
|
| 113 |
+
##
|
| 114 |
+
# (Internal) Image save plugin for the Palm format.
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 118 |
+
if im.mode == "P":
|
| 119 |
+
rawmode = "P"
|
| 120 |
+
bpp = 8
|
| 121 |
+
version = 1
|
| 122 |
+
|
| 123 |
+
elif im.mode == "L":
|
| 124 |
+
if im.encoderinfo.get("bpp") in (1, 2, 4):
|
| 125 |
+
# this is 8-bit grayscale, so we shift it to get the high-order bits,
|
| 126 |
+
# and invert it because
|
| 127 |
+
# Palm does grayscale from white (0) to black (1)
|
| 128 |
+
bpp = im.encoderinfo["bpp"]
|
| 129 |
+
maxval = (1 << bpp) - 1
|
| 130 |
+
shift = 8 - bpp
|
| 131 |
+
im = im.point(lambda x: maxval - (x >> shift))
|
| 132 |
+
elif im.info.get("bpp") in (1, 2, 4):
|
| 133 |
+
# here we assume that even though the inherent mode is 8-bit grayscale,
|
| 134 |
+
# only the lower bpp bits are significant.
|
| 135 |
+
# We invert them to match the Palm.
|
| 136 |
+
bpp = im.info["bpp"]
|
| 137 |
+
maxval = (1 << bpp) - 1
|
| 138 |
+
im = im.point(lambda x: maxval - (x & maxval))
|
| 139 |
+
else:
|
| 140 |
+
msg = f"cannot write mode {im.mode} as Palm"
|
| 141 |
+
raise OSError(msg)
|
| 142 |
+
|
| 143 |
+
# we ignore the palette here
|
| 144 |
+
im._mode = "P"
|
| 145 |
+
rawmode = f"P;{bpp}"
|
| 146 |
+
version = 1
|
| 147 |
+
|
| 148 |
+
elif im.mode == "1":
|
| 149 |
+
# monochrome -- write it inverted, as is the Palm standard
|
| 150 |
+
rawmode = "1;I"
|
| 151 |
+
bpp = 1
|
| 152 |
+
version = 0
|
| 153 |
+
|
| 154 |
+
else:
|
| 155 |
+
msg = f"cannot write mode {im.mode} as Palm"
|
| 156 |
+
raise OSError(msg)
|
| 157 |
+
|
| 158 |
+
#
|
| 159 |
+
# make sure image data is available
|
| 160 |
+
im.load()
|
| 161 |
+
|
| 162 |
+
# write header
|
| 163 |
+
|
| 164 |
+
cols = im.size[0]
|
| 165 |
+
rows = im.size[1]
|
| 166 |
+
|
| 167 |
+
rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2
|
| 168 |
+
transparent_index = 0
|
| 169 |
+
compression_type = _COMPRESSION_TYPES["none"]
|
| 170 |
+
|
| 171 |
+
flags = 0
|
| 172 |
+
if im.mode == "P":
|
| 173 |
+
flags |= _FLAGS["custom-colormap"]
|
| 174 |
+
colormap = im.im.getpalette()
|
| 175 |
+
colors = len(colormap) // 3
|
| 176 |
+
colormapsize = 4 * colors + 2
|
| 177 |
+
else:
|
| 178 |
+
colormapsize = 0
|
| 179 |
+
|
| 180 |
+
if "offset" in im.info:
|
| 181 |
+
offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4
|
| 182 |
+
else:
|
| 183 |
+
offset = 0
|
| 184 |
+
|
| 185 |
+
fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags))
|
| 186 |
+
fp.write(o8(bpp))
|
| 187 |
+
fp.write(o8(version))
|
| 188 |
+
fp.write(o16b(offset))
|
| 189 |
+
fp.write(o8(transparent_index))
|
| 190 |
+
fp.write(o8(compression_type))
|
| 191 |
+
fp.write(o16b(0)) # reserved by Palm
|
| 192 |
+
|
| 193 |
+
# now write colormap if necessary
|
| 194 |
+
|
| 195 |
+
if colormapsize:
|
| 196 |
+
fp.write(o16b(colors))
|
| 197 |
+
for i in range(colors):
|
| 198 |
+
fp.write(o8(i))
|
| 199 |
+
fp.write(colormap[3 * i : 3 * i + 3])
|
| 200 |
+
|
| 201 |
+
# now convert data to raw form
|
| 202 |
+
ImageFile._save(
|
| 203 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if hasattr(fp, "flush"):
|
| 207 |
+
fp.flush()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
#
|
| 211 |
+
# --------------------------------------------------------------------
|
| 212 |
+
|
| 213 |
+
Image.register_save("Palm", _save)
|
| 214 |
+
|
| 215 |
+
Image.register_extension("Palm", ".palm")
|
| 216 |
+
|
| 217 |
+
Image.register_mime("Palm", "image/palm")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PcdImagePlugin.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PCD file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-05-10 fl Created
|
| 9 |
+
# 96-05-27 fl Added draft mode (128x192, 256x384)
|
| 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, ImageFile
|
| 19 |
+
|
| 20 |
+
##
|
| 21 |
+
# Image plugin for PhotoCD images. This plugin only reads the 768x512
|
| 22 |
+
# image from the file; higher resolutions are encoded in a proprietary
|
| 23 |
+
# encoding.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PcdImageFile(ImageFile.ImageFile):
|
| 27 |
+
format = "PCD"
|
| 28 |
+
format_description = "Kodak PhotoCD"
|
| 29 |
+
|
| 30 |
+
def _open(self) -> None:
|
| 31 |
+
# rough
|
| 32 |
+
assert self.fp is not None
|
| 33 |
+
|
| 34 |
+
self.fp.seek(2048)
|
| 35 |
+
s = self.fp.read(1539)
|
| 36 |
+
|
| 37 |
+
if not s.startswith(b"PCD_"):
|
| 38 |
+
msg = "not a PCD file"
|
| 39 |
+
raise SyntaxError(msg)
|
| 40 |
+
|
| 41 |
+
orientation = s[1538] & 3
|
| 42 |
+
self.tile_post_rotate = None
|
| 43 |
+
if orientation == 1:
|
| 44 |
+
self.tile_post_rotate = 90
|
| 45 |
+
elif orientation == 3:
|
| 46 |
+
self.tile_post_rotate = 270
|
| 47 |
+
|
| 48 |
+
self._mode = "RGB"
|
| 49 |
+
self._size = (512, 768) if orientation in (1, 3) else (768, 512)
|
| 50 |
+
self.tile = [ImageFile._Tile("pcd", (0, 0, 768, 512), 96 * 2048)]
|
| 51 |
+
|
| 52 |
+
def load_prepare(self) -> None:
|
| 53 |
+
if self._im is None and self.tile_post_rotate:
|
| 54 |
+
self.im = Image.core.new(self.mode, (768, 512))
|
| 55 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 56 |
+
|
| 57 |
+
def load_end(self) -> None:
|
| 58 |
+
if self.tile_post_rotate:
|
| 59 |
+
# Handle rotated PCDs
|
| 60 |
+
self.im = self.rotate(self.tile_post_rotate, expand=True).im
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
#
|
| 64 |
+
# registry
|
| 65 |
+
|
| 66 |
+
Image.register_open(PcdImageFile.format, PcdImageFile)
|
| 67 |
+
|
| 68 |
+
Image.register_extension(PcdImageFile.format, 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# THIS IS WORK IN PROGRESS
|
| 3 |
+
#
|
| 4 |
+
# The Python Imaging Library
|
| 5 |
+
# $Id$
|
| 6 |
+
#
|
| 7 |
+
# portable compiled font file parser
|
| 8 |
+
#
|
| 9 |
+
# history:
|
| 10 |
+
# 1997-08-19 fl created
|
| 11 |
+
# 2003-09-13 fl fixed loading of unicode fonts
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 14 |
+
# Copyright (c) 1997-2003 by Fredrik Lundh.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import io
|
| 21 |
+
|
| 22 |
+
from . import FontFile, Image
|
| 23 |
+
from ._binary import i8
|
| 24 |
+
from ._binary import i16be as b16
|
| 25 |
+
from ._binary import i16le as l16
|
| 26 |
+
from ._binary import i32be as b32
|
| 27 |
+
from ._binary import i32le as l32
|
| 28 |
+
|
| 29 |
+
TYPE_CHECKING = False
|
| 30 |
+
if TYPE_CHECKING:
|
| 31 |
+
from collections.abc import Callable
|
| 32 |
+
from typing import BinaryIO
|
| 33 |
+
|
| 34 |
+
# --------------------------------------------------------------------
|
| 35 |
+
# declarations
|
| 36 |
+
|
| 37 |
+
PCF_MAGIC = 0x70636601 # "\x01fcp"
|
| 38 |
+
|
| 39 |
+
PCF_PROPERTIES = 1 << 0
|
| 40 |
+
PCF_ACCELERATORS = 1 << 1
|
| 41 |
+
PCF_METRICS = 1 << 2
|
| 42 |
+
PCF_BITMAPS = 1 << 3
|
| 43 |
+
PCF_INK_METRICS = 1 << 4
|
| 44 |
+
PCF_BDF_ENCODINGS = 1 << 5
|
| 45 |
+
PCF_SWIDTHS = 1 << 6
|
| 46 |
+
PCF_GLYPH_NAMES = 1 << 7
|
| 47 |
+
PCF_BDF_ACCELERATORS = 1 << 8
|
| 48 |
+
|
| 49 |
+
BYTES_PER_ROW: list[Callable[[int], int]] = [
|
| 50 |
+
lambda bits: ((bits + 7) >> 3),
|
| 51 |
+
lambda bits: ((bits + 15) >> 3) & ~1,
|
| 52 |
+
lambda bits: ((bits + 31) >> 3) & ~3,
|
| 53 |
+
lambda bits: ((bits + 63) >> 3) & ~7,
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sz(s: bytes, o: int) -> bytes:
|
| 58 |
+
return s[o : s.index(b"\0", o)]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class PcfFontFile(FontFile.FontFile):
|
| 62 |
+
"""Font file plugin for the X11 PCF format."""
|
| 63 |
+
|
| 64 |
+
name = "name"
|
| 65 |
+
|
| 66 |
+
def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
|
| 67 |
+
self.charset_encoding = charset_encoding
|
| 68 |
+
|
| 69 |
+
magic = l32(fp.read(4))
|
| 70 |
+
if magic != PCF_MAGIC:
|
| 71 |
+
msg = "not a PCF file"
|
| 72 |
+
raise SyntaxError(msg)
|
| 73 |
+
|
| 74 |
+
super().__init__()
|
| 75 |
+
|
| 76 |
+
count = l32(fp.read(4))
|
| 77 |
+
self.toc = {}
|
| 78 |
+
for i in range(count):
|
| 79 |
+
type = l32(fp.read(4))
|
| 80 |
+
self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
|
| 81 |
+
|
| 82 |
+
self.fp = fp
|
| 83 |
+
|
| 84 |
+
self.info = self._load_properties()
|
| 85 |
+
|
| 86 |
+
metrics = self._load_metrics()
|
| 87 |
+
bitmaps = self._load_bitmaps(metrics)
|
| 88 |
+
encoding = self._load_encoding()
|
| 89 |
+
|
| 90 |
+
#
|
| 91 |
+
# create glyph structure
|
| 92 |
+
|
| 93 |
+
for ch, ix in enumerate(encoding):
|
| 94 |
+
if ix is not None:
|
| 95 |
+
(
|
| 96 |
+
xsize,
|
| 97 |
+
ysize,
|
| 98 |
+
left,
|
| 99 |
+
right,
|
| 100 |
+
width,
|
| 101 |
+
ascent,
|
| 102 |
+
descent,
|
| 103 |
+
attributes,
|
| 104 |
+
) = metrics[ix]
|
| 105 |
+
self.glyph[ch] = (
|
| 106 |
+
(width, 0),
|
| 107 |
+
(left, descent - ysize, xsize + left, descent),
|
| 108 |
+
(0, 0, xsize, ysize),
|
| 109 |
+
bitmaps[ix],
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def _getformat(
|
| 113 |
+
self, tag: int
|
| 114 |
+
) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
|
| 115 |
+
format, size, offset = self.toc[tag]
|
| 116 |
+
|
| 117 |
+
fp = self.fp
|
| 118 |
+
fp.seek(offset)
|
| 119 |
+
|
| 120 |
+
format = l32(fp.read(4))
|
| 121 |
+
|
| 122 |
+
if format & 4:
|
| 123 |
+
i16, i32 = b16, b32
|
| 124 |
+
else:
|
| 125 |
+
i16, i32 = l16, l32
|
| 126 |
+
|
| 127 |
+
return fp, format, i16, i32
|
| 128 |
+
|
| 129 |
+
def _load_properties(self) -> dict[bytes, bytes | int]:
|
| 130 |
+
#
|
| 131 |
+
# font properties
|
| 132 |
+
|
| 133 |
+
properties = {}
|
| 134 |
+
|
| 135 |
+
fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
|
| 136 |
+
|
| 137 |
+
nprops = i32(fp.read(4))
|
| 138 |
+
|
| 139 |
+
# read property description
|
| 140 |
+
p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
|
| 141 |
+
|
| 142 |
+
if nprops & 3:
|
| 143 |
+
fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
|
| 144 |
+
|
| 145 |
+
data = fp.read(i32(fp.read(4)))
|
| 146 |
+
|
| 147 |
+
for k, s, v in p:
|
| 148 |
+
property_value: bytes | int = sz(data, v) if s else v
|
| 149 |
+
properties[sz(data, k)] = property_value
|
| 150 |
+
|
| 151 |
+
return properties
|
| 152 |
+
|
| 153 |
+
def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
|
| 154 |
+
#
|
| 155 |
+
# font metrics
|
| 156 |
+
|
| 157 |
+
metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
|
| 158 |
+
|
| 159 |
+
fp, format, i16, i32 = self._getformat(PCF_METRICS)
|
| 160 |
+
|
| 161 |
+
append = metrics.append
|
| 162 |
+
|
| 163 |
+
if (format & 0xFF00) == 0x100:
|
| 164 |
+
# "compressed" metrics
|
| 165 |
+
for i in range(i16(fp.read(2))):
|
| 166 |
+
left = i8(fp.read(1)) - 128
|
| 167 |
+
right = i8(fp.read(1)) - 128
|
| 168 |
+
width = i8(fp.read(1)) - 128
|
| 169 |
+
ascent = i8(fp.read(1)) - 128
|
| 170 |
+
descent = i8(fp.read(1)) - 128
|
| 171 |
+
xsize = right - left
|
| 172 |
+
ysize = ascent + descent
|
| 173 |
+
append((xsize, ysize, left, right, width, ascent, descent, 0))
|
| 174 |
+
|
| 175 |
+
else:
|
| 176 |
+
# "jumbo" metrics
|
| 177 |
+
for i in range(i32(fp.read(4))):
|
| 178 |
+
left = i16(fp.read(2))
|
| 179 |
+
right = i16(fp.read(2))
|
| 180 |
+
width = i16(fp.read(2))
|
| 181 |
+
ascent = i16(fp.read(2))
|
| 182 |
+
descent = i16(fp.read(2))
|
| 183 |
+
attributes = i16(fp.read(2))
|
| 184 |
+
xsize = right - left
|
| 185 |
+
ysize = ascent + descent
|
| 186 |
+
append((xsize, ysize, left, right, width, ascent, descent, attributes))
|
| 187 |
+
|
| 188 |
+
return metrics
|
| 189 |
+
|
| 190 |
+
def _load_bitmaps(
|
| 191 |
+
self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
|
| 192 |
+
) -> list[Image.Image]:
|
| 193 |
+
#
|
| 194 |
+
# bitmap data
|
| 195 |
+
|
| 196 |
+
fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
|
| 197 |
+
|
| 198 |
+
nbitmaps = i32(fp.read(4))
|
| 199 |
+
|
| 200 |
+
if nbitmaps != len(metrics):
|
| 201 |
+
msg = "Wrong number of bitmaps"
|
| 202 |
+
raise OSError(msg)
|
| 203 |
+
|
| 204 |
+
offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
|
| 205 |
+
|
| 206 |
+
bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
|
| 207 |
+
|
| 208 |
+
# byteorder = format & 4 # non-zero => MSB
|
| 209 |
+
bitorder = format & 8 # non-zero => MSB
|
| 210 |
+
padindex = format & 3
|
| 211 |
+
|
| 212 |
+
bitmapsize = bitmap_sizes[padindex]
|
| 213 |
+
offsets.append(bitmapsize)
|
| 214 |
+
|
| 215 |
+
data = fp.read(bitmapsize)
|
| 216 |
+
|
| 217 |
+
pad = BYTES_PER_ROW[padindex]
|
| 218 |
+
mode = "1;R"
|
| 219 |
+
if bitorder:
|
| 220 |
+
mode = "1"
|
| 221 |
+
|
| 222 |
+
bitmaps = []
|
| 223 |
+
for i in range(nbitmaps):
|
| 224 |
+
xsize, ysize = metrics[i][:2]
|
| 225 |
+
b, e = offsets[i : i + 2]
|
| 226 |
+
bitmaps.append(
|
| 227 |
+
Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
return bitmaps
|
| 231 |
+
|
| 232 |
+
def _load_encoding(self) -> list[int | None]:
|
| 233 |
+
fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
|
| 234 |
+
|
| 235 |
+
first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
|
| 236 |
+
first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
|
| 237 |
+
|
| 238 |
+
i16(fp.read(2)) # default
|
| 239 |
+
|
| 240 |
+
nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
|
| 241 |
+
|
| 242 |
+
# map character code to bitmap index
|
| 243 |
+
encoding: list[int | None] = [None] * min(256, nencoding)
|
| 244 |
+
|
| 245 |
+
encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
|
| 246 |
+
|
| 247 |
+
for i in range(first_col, len(encoding)):
|
| 248 |
+
try:
|
| 249 |
+
encoding_offset = encoding_offsets[
|
| 250 |
+
ord(bytearray([i]).decode(self.charset_encoding))
|
| 251 |
+
]
|
| 252 |
+
if encoding_offset != 0xFFFF:
|
| 253 |
+
encoding[i] = encoding_offset
|
| 254 |
+
except UnicodeDecodeError:
|
| 255 |
+
# character is not supported in selected encoding
|
| 256 |
+
pass
|
| 257 |
+
|
| 258 |
+
return encoding
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PCX file handling
|
| 6 |
+
#
|
| 7 |
+
# This format was originally used by ZSoft's popular PaintBrush
|
| 8 |
+
# program for the IBM PC. It is also supported by many MS-DOS and
|
| 9 |
+
# Windows applications, including the Windows PaintBrush program in
|
| 10 |
+
# Windows 3.
|
| 11 |
+
#
|
| 12 |
+
# history:
|
| 13 |
+
# 1995-09-01 fl Created
|
| 14 |
+
# 1996-05-20 fl Fixed RGB support
|
| 15 |
+
# 1997-01-03 fl Fixed 2-bit and 4-bit support
|
| 16 |
+
# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)
|
| 17 |
+
# 1999-02-07 fl Added write support
|
| 18 |
+
# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust
|
| 19 |
+
# 2002-07-30 fl Seek from to current position, not beginning of file
|
| 20 |
+
# 2003-06-03 fl Extract DPI settings (info["dpi"])
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 23 |
+
# Copyright (c) 1995-2003 by Fredrik Lundh.
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import io
|
| 30 |
+
import logging
|
| 31 |
+
from typing import IO
|
| 32 |
+
|
| 33 |
+
from . import Image, ImageFile, ImagePalette
|
| 34 |
+
from ._binary import i16le as i16
|
| 35 |
+
from ._binary import o8
|
| 36 |
+
from ._binary import o16le as o16
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _accept(prefix: bytes) -> bool:
|
| 42 |
+
return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
##
|
| 46 |
+
# Image plugin for Paintbrush images.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PcxImageFile(ImageFile.ImageFile):
|
| 50 |
+
format = "PCX"
|
| 51 |
+
format_description = "Paintbrush"
|
| 52 |
+
|
| 53 |
+
def _open(self) -> None:
|
| 54 |
+
# header
|
| 55 |
+
assert self.fp is not None
|
| 56 |
+
|
| 57 |
+
s = self.fp.read(68)
|
| 58 |
+
if not _accept(s):
|
| 59 |
+
msg = "not a PCX file"
|
| 60 |
+
raise SyntaxError(msg)
|
| 61 |
+
|
| 62 |
+
# image
|
| 63 |
+
bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
|
| 64 |
+
if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
|
| 65 |
+
msg = "bad PCX image size"
|
| 66 |
+
raise SyntaxError(msg)
|
| 67 |
+
logger.debug("BBox: %s %s %s %s", *bbox)
|
| 68 |
+
|
| 69 |
+
offset = self.fp.tell() + 60
|
| 70 |
+
|
| 71 |
+
# format
|
| 72 |
+
version = s[1]
|
| 73 |
+
bits = s[3]
|
| 74 |
+
planes = s[65]
|
| 75 |
+
provided_stride = i16(s, 66)
|
| 76 |
+
logger.debug(
|
| 77 |
+
"PCX version %s, bits %s, planes %s, stride %s",
|
| 78 |
+
version,
|
| 79 |
+
bits,
|
| 80 |
+
planes,
|
| 81 |
+
provided_stride,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self.info["dpi"] = i16(s, 12), i16(s, 14)
|
| 85 |
+
|
| 86 |
+
if bits == 1 and planes == 1:
|
| 87 |
+
mode = rawmode = "1"
|
| 88 |
+
|
| 89 |
+
elif bits == 1 and planes in (2, 4):
|
| 90 |
+
mode = "P"
|
| 91 |
+
rawmode = f"P;{planes}L"
|
| 92 |
+
self.palette = ImagePalette.raw("RGB", s[16:64])
|
| 93 |
+
|
| 94 |
+
elif version == 5 and bits == 8 and planes == 1:
|
| 95 |
+
mode = rawmode = "L"
|
| 96 |
+
# FIXME: hey, this doesn't work with the incremental loader !!!
|
| 97 |
+
self.fp.seek(-769, io.SEEK_END)
|
| 98 |
+
s = self.fp.read(769)
|
| 99 |
+
if len(s) == 769 and s[0] == 12:
|
| 100 |
+
# check if the palette is linear grayscale
|
| 101 |
+
for i in range(256):
|
| 102 |
+
if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
|
| 103 |
+
mode = rawmode = "P"
|
| 104 |
+
break
|
| 105 |
+
if mode == "P":
|
| 106 |
+
self.palette = ImagePalette.raw("RGB", s[1:])
|
| 107 |
+
|
| 108 |
+
elif version == 5 and bits == 8 and planes == 3:
|
| 109 |
+
mode = "RGB"
|
| 110 |
+
rawmode = "RGB;L"
|
| 111 |
+
|
| 112 |
+
else:
|
| 113 |
+
msg = "unknown PCX mode"
|
| 114 |
+
raise OSError(msg)
|
| 115 |
+
|
| 116 |
+
self._mode = mode
|
| 117 |
+
self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
| 118 |
+
|
| 119 |
+
# Don't trust the passed in stride.
|
| 120 |
+
# Calculate the approximate position for ourselves.
|
| 121 |
+
# CVE-2020-35653
|
| 122 |
+
stride = (self._size[0] * bits + 7) // 8
|
| 123 |
+
|
| 124 |
+
# While the specification states that this must be even,
|
| 125 |
+
# not all images follow this
|
| 126 |
+
if provided_stride != stride:
|
| 127 |
+
stride += stride % 2
|
| 128 |
+
|
| 129 |
+
bbox = (0, 0) + self.size
|
| 130 |
+
logger.debug("size: %sx%s", *self.size)
|
| 131 |
+
|
| 132 |
+
self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# --------------------------------------------------------------------
|
| 136 |
+
# save PCX files
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
SAVE = {
|
| 140 |
+
# mode: (version, bits, planes, raw mode)
|
| 141 |
+
"1": (2, 1, 1, "1"),
|
| 142 |
+
"L": (5, 8, 1, "L"),
|
| 143 |
+
"P": (5, 8, 1, "P"),
|
| 144 |
+
"RGB": (5, 8, 3, "RGB;L"),
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 149 |
+
try:
|
| 150 |
+
version, bits, planes, rawmode = SAVE[im.mode]
|
| 151 |
+
except KeyError as e:
|
| 152 |
+
msg = f"Cannot save {im.mode} images as PCX"
|
| 153 |
+
raise ValueError(msg) from e
|
| 154 |
+
|
| 155 |
+
# bytes per plane
|
| 156 |
+
stride = (im.size[0] * bits + 7) // 8
|
| 157 |
+
# stride should be even
|
| 158 |
+
stride += stride % 2
|
| 159 |
+
# Stride needs to be kept in sync with the PcxEncode.c version.
|
| 160 |
+
# Ideally it should be passed in in the state, but the bytes value
|
| 161 |
+
# gets overwritten.
|
| 162 |
+
|
| 163 |
+
logger.debug(
|
| 164 |
+
"PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
|
| 165 |
+
im.size[0],
|
| 166 |
+
bits,
|
| 167 |
+
stride,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# under windows, we could determine the current screen size with
|
| 171 |
+
# "Image.core.display_mode()[1]", but I think that's overkill...
|
| 172 |
+
|
| 173 |
+
screen = im.size
|
| 174 |
+
|
| 175 |
+
dpi = 100, 100
|
| 176 |
+
|
| 177 |
+
# PCX header
|
| 178 |
+
fp.write(
|
| 179 |
+
o8(10)
|
| 180 |
+
+ o8(version)
|
| 181 |
+
+ o8(1)
|
| 182 |
+
+ o8(bits)
|
| 183 |
+
+ o16(0)
|
| 184 |
+
+ o16(0)
|
| 185 |
+
+ o16(im.size[0] - 1)
|
| 186 |
+
+ o16(im.size[1] - 1)
|
| 187 |
+
+ o16(dpi[0])
|
| 188 |
+
+ o16(dpi[1])
|
| 189 |
+
+ b"\0" * 24
|
| 190 |
+
+ b"\xff" * 24
|
| 191 |
+
+ b"\0"
|
| 192 |
+
+ o8(planes)
|
| 193 |
+
+ o16(stride)
|
| 194 |
+
+ o16(1)
|
| 195 |
+
+ o16(screen[0])
|
| 196 |
+
+ o16(screen[1])
|
| 197 |
+
+ b"\0" * 54
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
assert fp.tell() == 128
|
| 201 |
+
|
| 202 |
+
ImageFile._save(
|
| 203 |
+
im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if im.mode == "P":
|
| 207 |
+
# colour palette
|
| 208 |
+
fp.write(o8(12))
|
| 209 |
+
palette = im.im.getpalette("RGB", "RGB")
|
| 210 |
+
palette += b"\x00" * (768 - len(palette))
|
| 211 |
+
fp.write(palette) # 768 bytes
|
| 212 |
+
elif im.mode == "L":
|
| 213 |
+
# grayscale palette
|
| 214 |
+
fp.write(o8(12))
|
| 215 |
+
for i in range(256):
|
| 216 |
+
fp.write(o8(i) * 3)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# --------------------------------------------------------------------
|
| 220 |
+
# registry
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
|
| 224 |
+
Image.register_save(PcxImageFile.format, _save)
|
| 225 |
+
|
| 226 |
+
Image.register_extension(PcxImageFile.format, ".pcx")
|
| 227 |
+
|
| 228 |
+
Image.register_mime(PcxImageFile.format, "image/x-pcx")
|
workspace/outputs/audit_venv/lib/python3.11/site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l Created
|
| 9 |
+
# 1997-01-18 fl Fixed header
|
| 10 |
+
# 2004-02-21 fl Fixes for 1/L/CMYK images, etc.
|
| 11 |
+
# 2004-02-24 fl Fixes for 1 and P images.
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved.
|
| 14 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
|
| 19 |
+
##
|
| 20 |
+
# Image plugin for PDF images (output only).
|
| 21 |
+
##
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import io
|
| 25 |
+
import math
|
| 26 |
+
import os
|
| 27 |
+
import time
|
| 28 |
+
from typing import IO, Any
|
| 29 |
+
|
| 30 |
+
from . import Image, ImageFile, ImageSequence, PdfParser, features
|
| 31 |
+
|
| 32 |
+
#
|
| 33 |
+
# --------------------------------------------------------------------
|
| 34 |
+
|
| 35 |
+
# object ids:
|
| 36 |
+
# 1. catalogue
|
| 37 |
+
# 2. pages
|
| 38 |
+
# 3. image
|
| 39 |
+
# 4. page
|
| 40 |
+
# 5. page contents
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 44 |
+
_save(im, fp, filename, save_all=True)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
##
|
| 48 |
+
# (Internal) Image save plugin for the PDF format.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _write_image(
|
| 52 |
+
im: Image.Image,
|
| 53 |
+
filename: str | bytes,
|
| 54 |
+
existing_pdf: PdfParser.PdfParser,
|
| 55 |
+
image_refs: list[PdfParser.IndirectReference],
|
| 56 |
+
) -> tuple[PdfParser.IndirectReference, str]:
|
| 57 |
+
# FIXME: Should replace ASCIIHexDecode with RunLengthDecode
|
| 58 |
+
# (packbits) or LZWDecode (tiff/lzw compression). Note that
|
| 59 |
+
# PDF 1.2 also supports Flatedecode (zip compression).
|
| 60 |
+
|
| 61 |
+
params = None
|
| 62 |
+
decode = None
|
| 63 |
+
|
| 64 |
+
#
|
| 65 |
+
# Get image characteristics
|
| 66 |
+
|
| 67 |
+
width, height = im.size
|
| 68 |
+
|
| 69 |
+
dict_obj: dict[str, Any] = {"BitsPerComponent": 8}
|
| 70 |
+
if im.mode == "1":
|
| 71 |
+
if features.check("libtiff"):
|
| 72 |
+
decode_filter = "CCITTFaxDecode"
|
| 73 |
+
dict_obj["BitsPerComponent"] = 1
|
| 74 |
+
params = PdfParser.PdfArray(
|
| 75 |
+
[
|
| 76 |
+
PdfParser.PdfDict(
|
| 77 |
+
{
|
| 78 |
+
"K": -1,
|
| 79 |
+
"BlackIs1": True,
|
| 80 |
+
"Columns": width,
|
| 81 |
+
"Rows": height,
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
]
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
decode_filter = "DCTDecode"
|
| 88 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
|
| 89 |
+
procset = "ImageB" # grayscale
|
| 90 |
+
elif im.mode == "L":
|
| 91 |
+
decode_filter = "DCTDecode"
|
| 92 |
+
# params = f"<< /Predictor 15 /Columns {width-2} >>"
|
| 93 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
|
| 94 |
+
procset = "ImageB" # grayscale
|
| 95 |
+
elif im.mode == "LA":
|
| 96 |
+
decode_filter = "JPXDecode"
|
| 97 |
+
# params = f"<< /Predictor 15 /Columns {width-2} >>"
|
| 98 |
+
procset = "ImageB" # grayscale
|
| 99 |
+
dict_obj["SMaskInData"] = 1
|
| 100 |
+
elif im.mode == "P":
|
| 101 |
+
decode_filter = "ASCIIHexDecode"
|
| 102 |
+
palette = im.getpalette()
|
| 103 |
+
assert palette is not None
|
| 104 |
+
dict_obj["ColorSpace"] = [
|
| 105 |
+
PdfParser.PdfName("Indexed"),
|
| 106 |
+
PdfParser.PdfName("DeviceRGB"),
|
| 107 |
+
len(palette) // 3 - 1,
|
| 108 |
+
PdfParser.PdfBinary(palette),
|
| 109 |
+
]
|
| 110 |
+
procset = "ImageI" # indexed color
|
| 111 |
+
|
| 112 |
+
if "transparency" in im.info:
|
| 113 |
+
smask = im.convert("LA").getchannel("A")
|
| 114 |
+
smask.encoderinfo = {}
|
| 115 |
+
|
| 116 |
+
image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]
|
| 117 |
+
dict_obj["SMask"] = image_ref
|
| 118 |
+
elif im.mode == "RGB":
|
| 119 |
+
decode_filter = "DCTDecode"
|
| 120 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")
|
| 121 |
+
procset = "ImageC" # color images
|
| 122 |
+
elif im.mode == "RGBA":
|
| 123 |
+
decode_filter = "JPXDecode"
|
| 124 |
+
procset = "ImageC" # color images
|
| 125 |
+
dict_obj["SMaskInData"] = 1
|
| 126 |
+
elif im.mode == "CMYK":
|
| 127 |
+
decode_filter = "DCTDecode"
|
| 128 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")
|
| 129 |
+
procset = "ImageC" # color images
|
| 130 |
+
decode = [1, 0, 1, 0, 1, 0, 1, 0]
|
| 131 |
+
else:
|
| 132 |
+
msg = f"cannot save mode {im.mode}"
|
| 133 |
+
raise ValueError(msg)
|
| 134 |
+
|
| 135 |
+
#
|
| 136 |
+
# image
|
| 137 |
+
|
| 138 |
+
op = io.BytesIO()
|
| 139 |
+
|
| 140 |
+
if decode_filter == "ASCIIHexDecode":
|
| 141 |
+
ImageFile._save(im, op, [ImageFile._Tile("hex", (0, 0) + im.size, 0, im.mode)])
|
| 142 |
+
elif decode_filter == "CCITTFaxDecode":
|
| 143 |
+
im.save(
|
| 144 |
+
op,
|
| 145 |
+
"TIFF",
|
| 146 |
+
compression="group4",
|
| 147 |
+
# use a single strip
|
| 148 |
+
strip_size=math.ceil(width / 8) * height,
|
| 149 |
+
)
|
| 150 |
+
elif decode_filter == "DCTDecode":
|
| 151 |
+
Image.SAVE["JPEG"](im, op, filename)
|
| 152 |
+
elif decode_filter == "JPXDecode":
|
| 153 |
+
del dict_obj["BitsPerComponent"]
|
| 154 |
+
Image.SAVE["JPEG2000"](im, op, filename)
|
| 155 |
+
else:
|
| 156 |
+
msg = f"unsupported PDF filter ({decode_filter})"
|
| 157 |
+
raise ValueError(msg)
|
| 158 |
+
|
| 159 |
+
stream = op.getvalue()
|
| 160 |
+
filter: PdfParser.PdfArray | PdfParser.PdfName
|
| 161 |
+
if decode_filter == "CCITTFaxDecode":
|
| 162 |
+
stream = stream[8:]
|
| 163 |
+
filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)])
|
| 164 |
+
else:
|
| 165 |
+
filter = PdfParser.PdfName(decode_filter)
|
| 166 |
+
|
| 167 |
+
image_ref = image_refs.pop(0)
|
| 168 |
+
existing_pdf.write_obj(
|
| 169 |
+
image_ref,
|
| 170 |
+
stream=stream,
|
| 171 |
+
Type=PdfParser.PdfName("XObject"),
|
| 172 |
+
Subtype=PdfParser.PdfName("Image"),
|
| 173 |
+
Width=width, # * 72.0 / x_resolution,
|
| 174 |
+
Height=height, # * 72.0 / y_resolution,
|
| 175 |
+
Filter=filter,
|
| 176 |
+
Decode=decode,
|
| 177 |
+
DecodeParms=params,
|
| 178 |
+
**dict_obj,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
return image_ref, procset
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _save(
|
| 185 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
|
| 186 |
+
) -> None:
|
| 187 |
+
is_appending = im.encoderinfo.get("append", False)
|
| 188 |
+
filename_str = filename.decode() if isinstance(filename, bytes) else filename
|
| 189 |
+
if is_appending:
|
| 190 |
+
existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="r+b")
|
| 191 |
+
else:
|
| 192 |
+
existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="w+b")
|
| 193 |
+
|
| 194 |
+
dpi = im.encoderinfo.get("dpi")
|
| 195 |
+
if dpi:
|
| 196 |
+
x_resolution = dpi[0]
|
| 197 |
+
y_resolution = dpi[1]
|
| 198 |
+
else:
|
| 199 |
+
x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0)
|
| 200 |
+
|
| 201 |
+
info = {
|
| 202 |
+
"title": (
|
| 203 |
+
None if is_appending else os.path.splitext(os.path.basename(filename))[0]
|
| 204 |
+
),
|
| 205 |
+
"author": None,
|
| 206 |
+
"subject": None,
|
| 207 |
+
"keywords": None,
|
| 208 |
+
"creator": None,
|
| 209 |
+
"producer": None,
|
| 210 |
+
"creationDate": None if is_appending else time.gmtime(),
|
| 211 |
+
"modDate": None if is_appending else time.gmtime(),
|
| 212 |
+
}
|
| 213 |
+
for k, default in info.items():
|
| 214 |
+
v = im.encoderinfo.get(k) if k in im.encoderinfo else default
|
| 215 |
+
if v:
|
| 216 |
+
existing_pdf.info[k[0].upper() + k[1:]] = v
|
| 217 |
+
|
| 218 |
+
#
|
| 219 |
+
# make sure image data is available
|
| 220 |
+
im.load()
|
| 221 |
+
|
| 222 |
+
existing_pdf.start_writing()
|
| 223 |
+
existing_pdf.write_header()
|
| 224 |
+
existing_pdf.write_comment("created by Pillow PDF driver")
|
| 225 |
+
|
| 226 |
+
#
|
| 227 |
+
# pages
|
| 228 |
+
ims = [im]
|
| 229 |
+
if save_all:
|
| 230 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 231 |
+
for append_im in append_images:
|
| 232 |
+
append_im.encoderinfo = im.encoderinfo.copy()
|
| 233 |
+
ims.append(append_im)
|
| 234 |
+
number_of_pages = 0
|
| 235 |
+
image_refs = []
|
| 236 |
+
page_refs = []
|
| 237 |
+
contents_refs = []
|
| 238 |
+
for im in ims:
|
| 239 |
+
im_number_of_pages = 1
|
| 240 |
+
if save_all:
|
| 241 |
+
im_number_of_pages = getattr(im, "n_frames", 1)
|
| 242 |
+
number_of_pages += im_number_of_pages
|
| 243 |
+
for i in range(im_number_of_pages):
|
| 244 |
+
image_refs.append(existing_pdf.next_object_id(0))
|
| 245 |
+
if im.mode == "P" and "transparency" in im.info:
|
| 246 |
+
image_refs.append(existing_pdf.next_object_id(0))
|
| 247 |
+
|
| 248 |
+
page_refs.append(existing_pdf.next_object_id(0))
|
| 249 |
+
contents_refs.append(existing_pdf.next_object_id(0))
|
| 250 |
+
existing_pdf.pages.append(page_refs[-1])
|
| 251 |
+
|
| 252 |
+
#
|
| 253 |
+
# catalog and list of pages
|
| 254 |
+
existing_pdf.write_catalog()
|
| 255 |
+
|
| 256 |
+
page_number = 0
|
| 257 |
+
for im_sequence in ims:
|
| 258 |
+
im_pages: ImageSequence.Iterator | list[Image.Image] = (
|
| 259 |
+
ImageSequence.Iterator(im_sequence) if save_all else [im_sequence]
|
| 260 |
+
)
|
| 261 |
+
for im in im_pages:
|
| 262 |
+
image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)
|
| 263 |
+
|
| 264 |
+
#
|
| 265 |
+
# page
|
| 266 |
+
|
| 267 |
+
existing_pdf.write_page(
|
| 268 |
+
page_refs[page_number],
|
| 269 |
+
Resources=PdfParser.PdfDict(
|
| 270 |
+
ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],
|
| 271 |
+
XObject=PdfParser.PdfDict(image=image_ref),
|
| 272 |
+
),
|
| 273 |
+
MediaBox=[
|
| 274 |
+
0,
|
| 275 |
+
0,
|
| 276 |
+
im.width * 72.0 / x_resolution,
|
| 277 |
+
im.height * 72.0 / y_resolution,
|
| 278 |
+
],
|
| 279 |
+
Contents=contents_refs[page_number],
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
#
|
| 283 |
+
# page contents
|
| 284 |
+
|
| 285 |
+
page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (
|
| 286 |
+
im.width * 72.0 / x_resolution,
|
| 287 |
+
im.height * 72.0 / y_resolution,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
existing_pdf.write_obj(contents_refs[page_number], stream=page_contents)
|
| 291 |
+
|
| 292 |
+
page_number += 1
|
| 293 |
+
|
| 294 |
+
#
|
| 295 |
+
# trailer
|
| 296 |
+
existing_pdf.write_xref_and_trailer()
|
| 297 |
+
if hasattr(fp, "flush"):
|
| 298 |
+
fp.flush()
|
| 299 |
+
existing_pdf.close()
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
#
|
| 303 |
+
# --------------------------------------------------------------------
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
Image.register_save("PDF", _save)
|
| 307 |
+
Image.register_save_all("PDF", _save_all)
|
| 308 |
+
|
| 309 |
+
Image.register_extension("PDF", ".pdf")
|
| 310 |
+
|
| 311 |
+
Image.register_mime("PDF", "application/pdf")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PdfParser.py
ADDED
|
@@ -0,0 +1,1075 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import calendar
|
| 4 |
+
import codecs
|
| 5 |
+
import collections
|
| 6 |
+
import mmap
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
import zlib
|
| 11 |
+
from typing import Any, NamedTuple
|
| 12 |
+
|
| 13 |
+
TYPE_CHECKING = False
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from typing import IO
|
| 16 |
+
|
| 17 |
+
_DictBase = collections.UserDict[str | bytes, Any]
|
| 18 |
+
else:
|
| 19 |
+
_DictBase = collections.UserDict
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set
|
| 23 |
+
# on page 656
|
| 24 |
+
def encode_text(s: str) -> bytes:
|
| 25 |
+
return codecs.BOM_UTF16_BE + s.encode("utf_16_be")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
PDFDocEncoding = {
|
| 29 |
+
0x16: "\u0017",
|
| 30 |
+
0x18: "\u02d8",
|
| 31 |
+
0x19: "\u02c7",
|
| 32 |
+
0x1A: "\u02c6",
|
| 33 |
+
0x1B: "\u02d9",
|
| 34 |
+
0x1C: "\u02dd",
|
| 35 |
+
0x1D: "\u02db",
|
| 36 |
+
0x1E: "\u02da",
|
| 37 |
+
0x1F: "\u02dc",
|
| 38 |
+
0x80: "\u2022",
|
| 39 |
+
0x81: "\u2020",
|
| 40 |
+
0x82: "\u2021",
|
| 41 |
+
0x83: "\u2026",
|
| 42 |
+
0x84: "\u2014",
|
| 43 |
+
0x85: "\u2013",
|
| 44 |
+
0x86: "\u0192",
|
| 45 |
+
0x87: "\u2044",
|
| 46 |
+
0x88: "\u2039",
|
| 47 |
+
0x89: "\u203a",
|
| 48 |
+
0x8A: "\u2212",
|
| 49 |
+
0x8B: "\u2030",
|
| 50 |
+
0x8C: "\u201e",
|
| 51 |
+
0x8D: "\u201c",
|
| 52 |
+
0x8E: "\u201d",
|
| 53 |
+
0x8F: "\u2018",
|
| 54 |
+
0x90: "\u2019",
|
| 55 |
+
0x91: "\u201a",
|
| 56 |
+
0x92: "\u2122",
|
| 57 |
+
0x93: "\ufb01",
|
| 58 |
+
0x94: "\ufb02",
|
| 59 |
+
0x95: "\u0141",
|
| 60 |
+
0x96: "\u0152",
|
| 61 |
+
0x97: "\u0160",
|
| 62 |
+
0x98: "\u0178",
|
| 63 |
+
0x99: "\u017d",
|
| 64 |
+
0x9A: "\u0131",
|
| 65 |
+
0x9B: "\u0142",
|
| 66 |
+
0x9C: "\u0153",
|
| 67 |
+
0x9D: "\u0161",
|
| 68 |
+
0x9E: "\u017e",
|
| 69 |
+
0xA0: "\u20ac",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def decode_text(b: bytes) -> str:
|
| 74 |
+
if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:
|
| 75 |
+
return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be")
|
| 76 |
+
else:
|
| 77 |
+
return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class PdfFormatError(RuntimeError):
|
| 81 |
+
"""An error that probably indicates a syntactic or semantic error in the
|
| 82 |
+
PDF file structure"""
|
| 83 |
+
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def check_format_condition(condition: bool, error_message: str) -> None:
|
| 88 |
+
if not condition:
|
| 89 |
+
raise PdfFormatError(error_message)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class IndirectReferenceTuple(NamedTuple):
|
| 93 |
+
object_id: int
|
| 94 |
+
generation: int
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class IndirectReference(IndirectReferenceTuple):
|
| 98 |
+
def __str__(self) -> str:
|
| 99 |
+
return f"{self.object_id} {self.generation} R"
|
| 100 |
+
|
| 101 |
+
def __bytes__(self) -> bytes:
|
| 102 |
+
return self.__str__().encode("us-ascii")
|
| 103 |
+
|
| 104 |
+
def __eq__(self, other: object) -> bool:
|
| 105 |
+
if self.__class__ is not other.__class__:
|
| 106 |
+
return False
|
| 107 |
+
assert isinstance(other, IndirectReference)
|
| 108 |
+
return other.object_id == self.object_id and other.generation == self.generation
|
| 109 |
+
|
| 110 |
+
def __ne__(self, other: object) -> bool:
|
| 111 |
+
return not (self == other)
|
| 112 |
+
|
| 113 |
+
def __hash__(self) -> int:
|
| 114 |
+
return hash((self.object_id, self.generation))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class IndirectObjectDef(IndirectReference):
|
| 118 |
+
def __str__(self) -> str:
|
| 119 |
+
return f"{self.object_id} {self.generation} obj"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class XrefTable:
|
| 123 |
+
def __init__(self) -> None:
|
| 124 |
+
self.existing_entries: dict[int, tuple[int, int]] = (
|
| 125 |
+
{}
|
| 126 |
+
) # object ID => (offset, generation)
|
| 127 |
+
self.new_entries: dict[int, tuple[int, int]] = (
|
| 128 |
+
{}
|
| 129 |
+
) # object ID => (offset, generation)
|
| 130 |
+
self.deleted_entries = {0: 65536} # object ID => generation
|
| 131 |
+
self.reading_finished = False
|
| 132 |
+
|
| 133 |
+
def __setitem__(self, key: int, value: tuple[int, int]) -> None:
|
| 134 |
+
if self.reading_finished:
|
| 135 |
+
self.new_entries[key] = value
|
| 136 |
+
else:
|
| 137 |
+
self.existing_entries[key] = value
|
| 138 |
+
if key in self.deleted_entries:
|
| 139 |
+
del self.deleted_entries[key]
|
| 140 |
+
|
| 141 |
+
def __getitem__(self, key: int) -> tuple[int, int]:
|
| 142 |
+
try:
|
| 143 |
+
return self.new_entries[key]
|
| 144 |
+
except KeyError:
|
| 145 |
+
return self.existing_entries[key]
|
| 146 |
+
|
| 147 |
+
def __delitem__(self, key: int) -> None:
|
| 148 |
+
if key in self.new_entries:
|
| 149 |
+
generation = self.new_entries[key][1] + 1
|
| 150 |
+
del self.new_entries[key]
|
| 151 |
+
self.deleted_entries[key] = generation
|
| 152 |
+
elif key in self.existing_entries:
|
| 153 |
+
generation = self.existing_entries[key][1] + 1
|
| 154 |
+
self.deleted_entries[key] = generation
|
| 155 |
+
elif key in self.deleted_entries:
|
| 156 |
+
generation = self.deleted_entries[key]
|
| 157 |
+
else:
|
| 158 |
+
msg = f"object ID {key} cannot be deleted because it doesn't exist"
|
| 159 |
+
raise IndexError(msg)
|
| 160 |
+
|
| 161 |
+
def __contains__(self, key: int) -> bool:
|
| 162 |
+
return key in self.existing_entries or key in self.new_entries
|
| 163 |
+
|
| 164 |
+
def __len__(self) -> int:
|
| 165 |
+
return len(
|
| 166 |
+
set(self.existing_entries.keys())
|
| 167 |
+
| set(self.new_entries.keys())
|
| 168 |
+
| set(self.deleted_entries.keys())
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def keys(self) -> set[int]:
|
| 172 |
+
return (
|
| 173 |
+
set(self.existing_entries.keys()) - set(self.deleted_entries.keys())
|
| 174 |
+
) | set(self.new_entries.keys())
|
| 175 |
+
|
| 176 |
+
def write(self, f: IO[bytes]) -> int:
|
| 177 |
+
keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys()))
|
| 178 |
+
deleted_keys = sorted(set(self.deleted_entries.keys()))
|
| 179 |
+
startxref = f.tell()
|
| 180 |
+
f.write(b"xref\n")
|
| 181 |
+
while keys:
|
| 182 |
+
# find a contiguous sequence of object IDs
|
| 183 |
+
prev: int | None = None
|
| 184 |
+
for index, key in enumerate(keys):
|
| 185 |
+
if prev is None or prev + 1 == key:
|
| 186 |
+
prev = key
|
| 187 |
+
else:
|
| 188 |
+
contiguous_keys = keys[:index]
|
| 189 |
+
keys = keys[index:]
|
| 190 |
+
break
|
| 191 |
+
else:
|
| 192 |
+
contiguous_keys = keys
|
| 193 |
+
keys = []
|
| 194 |
+
f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys)))
|
| 195 |
+
for object_id in contiguous_keys:
|
| 196 |
+
if object_id in self.new_entries:
|
| 197 |
+
f.write(b"%010d %05d n \n" % self.new_entries[object_id])
|
| 198 |
+
else:
|
| 199 |
+
this_deleted_object_id = deleted_keys.pop(0)
|
| 200 |
+
check_format_condition(
|
| 201 |
+
object_id == this_deleted_object_id,
|
| 202 |
+
f"expected the next deleted object ID to be {object_id}, "
|
| 203 |
+
f"instead found {this_deleted_object_id}",
|
| 204 |
+
)
|
| 205 |
+
try:
|
| 206 |
+
next_in_linked_list = deleted_keys[0]
|
| 207 |
+
except IndexError:
|
| 208 |
+
next_in_linked_list = 0
|
| 209 |
+
f.write(
|
| 210 |
+
b"%010d %05d f \n"
|
| 211 |
+
% (next_in_linked_list, self.deleted_entries[object_id])
|
| 212 |
+
)
|
| 213 |
+
return startxref
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class PdfName:
|
| 217 |
+
name: bytes
|
| 218 |
+
|
| 219 |
+
def __init__(self, name: PdfName | bytes | str) -> None:
|
| 220 |
+
if isinstance(name, PdfName):
|
| 221 |
+
self.name = name.name
|
| 222 |
+
elif isinstance(name, bytes):
|
| 223 |
+
self.name = name
|
| 224 |
+
else:
|
| 225 |
+
self.name = name.encode("us-ascii")
|
| 226 |
+
|
| 227 |
+
def name_as_str(self) -> str:
|
| 228 |
+
return self.name.decode("us-ascii")
|
| 229 |
+
|
| 230 |
+
def __eq__(self, other: object) -> bool:
|
| 231 |
+
return (
|
| 232 |
+
isinstance(other, PdfName) and other.name == self.name
|
| 233 |
+
) or other == self.name
|
| 234 |
+
|
| 235 |
+
def __hash__(self) -> int:
|
| 236 |
+
return hash(self.name)
|
| 237 |
+
|
| 238 |
+
def __repr__(self) -> str:
|
| 239 |
+
return f"{self.__class__.__name__}({repr(self.name)})"
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def from_pdf_stream(cls, data: bytes) -> PdfName:
|
| 243 |
+
return cls(PdfParser.interpret_name(data))
|
| 244 |
+
|
| 245 |
+
allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"}
|
| 246 |
+
|
| 247 |
+
def __bytes__(self) -> bytes:
|
| 248 |
+
result = bytearray(b"/")
|
| 249 |
+
for b in self.name:
|
| 250 |
+
if b in self.allowed_chars:
|
| 251 |
+
result.append(b)
|
| 252 |
+
else:
|
| 253 |
+
result.extend(b"#%02X" % b)
|
| 254 |
+
return bytes(result)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class PdfArray(list[Any]):
|
| 258 |
+
def __bytes__(self) -> bytes:
|
| 259 |
+
return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]"
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class PdfDict(_DictBase):
|
| 263 |
+
def __setattr__(self, key: str, value: Any) -> None:
|
| 264 |
+
if key == "data":
|
| 265 |
+
collections.UserDict.__setattr__(self, key, value)
|
| 266 |
+
else:
|
| 267 |
+
self[key.encode("us-ascii")] = value
|
| 268 |
+
|
| 269 |
+
def __getattr__(self, key: str) -> str | time.struct_time:
|
| 270 |
+
try:
|
| 271 |
+
value = self[key.encode("us-ascii")]
|
| 272 |
+
except KeyError as e:
|
| 273 |
+
raise AttributeError(key) from e
|
| 274 |
+
if isinstance(value, bytes):
|
| 275 |
+
value = decode_text(value)
|
| 276 |
+
if key.endswith("Date"):
|
| 277 |
+
if value.startswith("D:"):
|
| 278 |
+
value = value[2:]
|
| 279 |
+
|
| 280 |
+
relationship = "Z"
|
| 281 |
+
if len(value) > 17:
|
| 282 |
+
relationship = value[14]
|
| 283 |
+
offset = int(value[15:17]) * 60
|
| 284 |
+
if len(value) > 20:
|
| 285 |
+
offset += int(value[18:20])
|
| 286 |
+
|
| 287 |
+
format = "%Y%m%d%H%M%S"[: len(value) - 2]
|
| 288 |
+
value = time.strptime(value[: len(format) + 2], format)
|
| 289 |
+
if relationship in ["+", "-"]:
|
| 290 |
+
offset *= 60
|
| 291 |
+
if relationship == "+":
|
| 292 |
+
offset *= -1
|
| 293 |
+
value = time.gmtime(calendar.timegm(value) + offset)
|
| 294 |
+
return value
|
| 295 |
+
|
| 296 |
+
def __bytes__(self) -> bytes:
|
| 297 |
+
out = bytearray(b"<<")
|
| 298 |
+
for key, value in self.items():
|
| 299 |
+
if value is None:
|
| 300 |
+
continue
|
| 301 |
+
value = pdf_repr(value)
|
| 302 |
+
out.extend(b"\n")
|
| 303 |
+
out.extend(bytes(PdfName(key)))
|
| 304 |
+
out.extend(b" ")
|
| 305 |
+
out.extend(value)
|
| 306 |
+
out.extend(b"\n>>")
|
| 307 |
+
return bytes(out)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class PdfBinary:
|
| 311 |
+
def __init__(self, data: list[int] | bytes) -> None:
|
| 312 |
+
self.data = data
|
| 313 |
+
|
| 314 |
+
def __bytes__(self) -> bytes:
|
| 315 |
+
return b"<%s>" % b"".join(b"%02X" % b for b in self.data)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class PdfStream:
|
| 319 |
+
def __init__(self, dictionary: PdfDict, buf: bytes) -> None:
|
| 320 |
+
self.dictionary = dictionary
|
| 321 |
+
self.buf = buf
|
| 322 |
+
|
| 323 |
+
def decode(self) -> bytes:
|
| 324 |
+
try:
|
| 325 |
+
filter = self.dictionary[b"Filter"]
|
| 326 |
+
except KeyError:
|
| 327 |
+
return self.buf
|
| 328 |
+
if filter == b"FlateDecode":
|
| 329 |
+
try:
|
| 330 |
+
expected_length = self.dictionary[b"DL"]
|
| 331 |
+
except KeyError:
|
| 332 |
+
expected_length = self.dictionary[b"Length"]
|
| 333 |
+
return zlib.decompress(self.buf, bufsize=int(expected_length))
|
| 334 |
+
else:
|
| 335 |
+
msg = f"stream filter {repr(filter)} unknown/unsupported"
|
| 336 |
+
raise NotImplementedError(msg)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def pdf_repr(x: Any) -> bytes:
|
| 340 |
+
if x is True:
|
| 341 |
+
return b"true"
|
| 342 |
+
elif x is False:
|
| 343 |
+
return b"false"
|
| 344 |
+
elif x is None:
|
| 345 |
+
return b"null"
|
| 346 |
+
elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):
|
| 347 |
+
return bytes(x)
|
| 348 |
+
elif isinstance(x, (int, float)):
|
| 349 |
+
return str(x).encode("us-ascii")
|
| 350 |
+
elif isinstance(x, time.struct_time):
|
| 351 |
+
return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"
|
| 352 |
+
elif isinstance(x, dict):
|
| 353 |
+
return bytes(PdfDict(x))
|
| 354 |
+
elif isinstance(x, list):
|
| 355 |
+
return bytes(PdfArray(x))
|
| 356 |
+
elif isinstance(x, str):
|
| 357 |
+
return pdf_repr(encode_text(x))
|
| 358 |
+
elif isinstance(x, bytes):
|
| 359 |
+
# XXX escape more chars? handle binary garbage
|
| 360 |
+
x = x.replace(b"\\", b"\\\\")
|
| 361 |
+
x = x.replace(b"(", b"\\(")
|
| 362 |
+
x = x.replace(b")", b"\\)")
|
| 363 |
+
return b"(" + x + b")"
|
| 364 |
+
else:
|
| 365 |
+
return bytes(x)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class PdfParser:
|
| 369 |
+
"""Based on
|
| 370 |
+
https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
|
| 371 |
+
Supports PDF up to 1.4
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
def __init__(
|
| 375 |
+
self,
|
| 376 |
+
filename: str | None = None,
|
| 377 |
+
f: IO[bytes] | None = None,
|
| 378 |
+
buf: bytes | bytearray | None = None,
|
| 379 |
+
start_offset: int = 0,
|
| 380 |
+
mode: str = "rb",
|
| 381 |
+
) -> None:
|
| 382 |
+
if buf and f:
|
| 383 |
+
msg = "specify buf or f or filename, but not both buf and f"
|
| 384 |
+
raise RuntimeError(msg)
|
| 385 |
+
self.filename = filename
|
| 386 |
+
self.buf: bytes | bytearray | mmap.mmap | None = buf
|
| 387 |
+
self.f = f
|
| 388 |
+
self.start_offset = start_offset
|
| 389 |
+
self.should_close_buf = False
|
| 390 |
+
self.should_close_file = False
|
| 391 |
+
if filename is not None and f is None:
|
| 392 |
+
self.f = f = open(filename, mode)
|
| 393 |
+
self.should_close_file = True
|
| 394 |
+
if f is not None:
|
| 395 |
+
self.buf = self.get_buf_from_file(f)
|
| 396 |
+
self.should_close_buf = True
|
| 397 |
+
if not filename and hasattr(f, "name"):
|
| 398 |
+
self.filename = f.name
|
| 399 |
+
self.cached_objects: dict[IndirectReference, Any] = {}
|
| 400 |
+
self.root_ref: IndirectReference | None
|
| 401 |
+
self.info_ref: IndirectReference | None
|
| 402 |
+
self.pages_ref: IndirectReference | None
|
| 403 |
+
self.last_xref_section_offset: int | None
|
| 404 |
+
if self.buf:
|
| 405 |
+
self.read_pdf_info()
|
| 406 |
+
else:
|
| 407 |
+
self.file_size_total = self.file_size_this = 0
|
| 408 |
+
self.root = PdfDict()
|
| 409 |
+
self.root_ref = None
|
| 410 |
+
self.info = PdfDict()
|
| 411 |
+
self.info_ref = None
|
| 412 |
+
self.page_tree_root = PdfDict()
|
| 413 |
+
self.pages: list[IndirectReference] = []
|
| 414 |
+
self.orig_pages: list[IndirectReference] = []
|
| 415 |
+
self.pages_ref = None
|
| 416 |
+
self.last_xref_section_offset = None
|
| 417 |
+
self.trailer_dict: dict[bytes, Any] = {}
|
| 418 |
+
self.xref_table = XrefTable()
|
| 419 |
+
self.xref_table.reading_finished = True
|
| 420 |
+
if f:
|
| 421 |
+
self.seek_end()
|
| 422 |
+
|
| 423 |
+
def __enter__(self) -> PdfParser:
|
| 424 |
+
return self
|
| 425 |
+
|
| 426 |
+
def __exit__(self, *args: object) -> None:
|
| 427 |
+
self.close()
|
| 428 |
+
|
| 429 |
+
def start_writing(self) -> None:
|
| 430 |
+
self.close_buf()
|
| 431 |
+
self.seek_end()
|
| 432 |
+
|
| 433 |
+
def close_buf(self) -> None:
|
| 434 |
+
if isinstance(self.buf, mmap.mmap):
|
| 435 |
+
self.buf.close()
|
| 436 |
+
self.buf = None
|
| 437 |
+
|
| 438 |
+
def close(self) -> None:
|
| 439 |
+
if self.should_close_buf:
|
| 440 |
+
self.close_buf()
|
| 441 |
+
if self.f is not None and self.should_close_file:
|
| 442 |
+
self.f.close()
|
| 443 |
+
self.f = None
|
| 444 |
+
|
| 445 |
+
def seek_end(self) -> None:
|
| 446 |
+
assert self.f is not None
|
| 447 |
+
self.f.seek(0, os.SEEK_END)
|
| 448 |
+
|
| 449 |
+
def write_header(self) -> None:
|
| 450 |
+
assert self.f is not None
|
| 451 |
+
self.f.write(b"%PDF-1.4\n")
|
| 452 |
+
|
| 453 |
+
def write_comment(self, s: str) -> None:
|
| 454 |
+
assert self.f is not None
|
| 455 |
+
self.f.write(f"% {s}\n".encode())
|
| 456 |
+
|
| 457 |
+
def write_catalog(self) -> IndirectReference:
|
| 458 |
+
assert self.f is not None
|
| 459 |
+
self.del_root()
|
| 460 |
+
self.root_ref = self.next_object_id(self.f.tell())
|
| 461 |
+
self.pages_ref = self.next_object_id(0)
|
| 462 |
+
self.rewrite_pages()
|
| 463 |
+
self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref)
|
| 464 |
+
self.write_obj(
|
| 465 |
+
self.pages_ref,
|
| 466 |
+
Type=PdfName(b"Pages"),
|
| 467 |
+
Count=len(self.pages),
|
| 468 |
+
Kids=self.pages,
|
| 469 |
+
)
|
| 470 |
+
return self.root_ref
|
| 471 |
+
|
| 472 |
+
def rewrite_pages(self) -> None:
|
| 473 |
+
pages_tree_nodes_to_delete = []
|
| 474 |
+
for i, page_ref in enumerate(self.orig_pages):
|
| 475 |
+
page_info = self.cached_objects[page_ref]
|
| 476 |
+
del self.xref_table[page_ref.object_id]
|
| 477 |
+
pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")])
|
| 478 |
+
if page_ref not in self.pages:
|
| 479 |
+
# the page has been deleted
|
| 480 |
+
continue
|
| 481 |
+
# make dict keys into strings for passing to write_page
|
| 482 |
+
stringified_page_info = {}
|
| 483 |
+
for key, value in page_info.items():
|
| 484 |
+
# key should be a PdfName
|
| 485 |
+
stringified_page_info[key.name_as_str()] = value
|
| 486 |
+
stringified_page_info["Parent"] = self.pages_ref
|
| 487 |
+
new_page_ref = self.write_page(None, **stringified_page_info)
|
| 488 |
+
for j, cur_page_ref in enumerate(self.pages):
|
| 489 |
+
if cur_page_ref == page_ref:
|
| 490 |
+
# replace the page reference with the new one
|
| 491 |
+
self.pages[j] = new_page_ref
|
| 492 |
+
# delete redundant Pages tree nodes from xref table
|
| 493 |
+
for pages_tree_node_ref in pages_tree_nodes_to_delete:
|
| 494 |
+
while pages_tree_node_ref:
|
| 495 |
+
pages_tree_node = self.cached_objects[pages_tree_node_ref]
|
| 496 |
+
if pages_tree_node_ref.object_id in self.xref_table:
|
| 497 |
+
del self.xref_table[pages_tree_node_ref.object_id]
|
| 498 |
+
pages_tree_node_ref = pages_tree_node.get(b"Parent", None)
|
| 499 |
+
self.orig_pages = []
|
| 500 |
+
|
| 501 |
+
def write_xref_and_trailer(
|
| 502 |
+
self, new_root_ref: IndirectReference | None = None
|
| 503 |
+
) -> None:
|
| 504 |
+
assert self.f is not None
|
| 505 |
+
if new_root_ref:
|
| 506 |
+
self.del_root()
|
| 507 |
+
self.root_ref = new_root_ref
|
| 508 |
+
if self.info:
|
| 509 |
+
self.info_ref = self.write_obj(None, self.info)
|
| 510 |
+
start_xref = self.xref_table.write(self.f)
|
| 511 |
+
num_entries = len(self.xref_table)
|
| 512 |
+
trailer_dict: dict[str | bytes, Any] = {
|
| 513 |
+
b"Root": self.root_ref,
|
| 514 |
+
b"Size": num_entries,
|
| 515 |
+
}
|
| 516 |
+
if self.last_xref_section_offset is not None:
|
| 517 |
+
trailer_dict[b"Prev"] = self.last_xref_section_offset
|
| 518 |
+
if self.info:
|
| 519 |
+
trailer_dict[b"Info"] = self.info_ref
|
| 520 |
+
self.last_xref_section_offset = start_xref
|
| 521 |
+
self.f.write(
|
| 522 |
+
b"trailer\n"
|
| 523 |
+
+ bytes(PdfDict(trailer_dict))
|
| 524 |
+
+ b"\nstartxref\n%d\n%%%%EOF" % start_xref
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
def write_page(
|
| 528 |
+
self, ref: int | IndirectReference | None, *objs: Any, **dict_obj: Any
|
| 529 |
+
) -> IndirectReference:
|
| 530 |
+
obj_ref = self.pages[ref] if isinstance(ref, int) else ref
|
| 531 |
+
if "Type" not in dict_obj:
|
| 532 |
+
dict_obj["Type"] = PdfName(b"Page")
|
| 533 |
+
if "Parent" not in dict_obj:
|
| 534 |
+
dict_obj["Parent"] = self.pages_ref
|
| 535 |
+
return self.write_obj(obj_ref, *objs, **dict_obj)
|
| 536 |
+
|
| 537 |
+
def write_obj(
|
| 538 |
+
self, ref: IndirectReference | None, *objs: Any, **dict_obj: Any
|
| 539 |
+
) -> IndirectReference:
|
| 540 |
+
assert self.f is not None
|
| 541 |
+
f = self.f
|
| 542 |
+
if ref is None:
|
| 543 |
+
ref = self.next_object_id(f.tell())
|
| 544 |
+
else:
|
| 545 |
+
self.xref_table[ref.object_id] = (f.tell(), ref.generation)
|
| 546 |
+
f.write(bytes(IndirectObjectDef(*ref)))
|
| 547 |
+
stream = dict_obj.pop("stream", None)
|
| 548 |
+
if stream is not None:
|
| 549 |
+
dict_obj["Length"] = len(stream)
|
| 550 |
+
if dict_obj:
|
| 551 |
+
f.write(pdf_repr(dict_obj))
|
| 552 |
+
for obj in objs:
|
| 553 |
+
f.write(pdf_repr(obj))
|
| 554 |
+
if stream is not None:
|
| 555 |
+
f.write(b"stream\n")
|
| 556 |
+
f.write(stream)
|
| 557 |
+
f.write(b"\nendstream\n")
|
| 558 |
+
f.write(b"endobj\n")
|
| 559 |
+
return ref
|
| 560 |
+
|
| 561 |
+
def del_root(self) -> None:
|
| 562 |
+
if self.root_ref is None:
|
| 563 |
+
return
|
| 564 |
+
del self.xref_table[self.root_ref.object_id]
|
| 565 |
+
del self.xref_table[self.root[b"Pages"].object_id]
|
| 566 |
+
|
| 567 |
+
@staticmethod
|
| 568 |
+
def get_buf_from_file(f: IO[bytes]) -> bytes | mmap.mmap:
|
| 569 |
+
if hasattr(f, "getbuffer"):
|
| 570 |
+
return f.getbuffer()
|
| 571 |
+
elif hasattr(f, "getvalue"):
|
| 572 |
+
return f.getvalue()
|
| 573 |
+
else:
|
| 574 |
+
try:
|
| 575 |
+
return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
|
| 576 |
+
except ValueError: # cannot mmap an empty file
|
| 577 |
+
return b""
|
| 578 |
+
|
| 579 |
+
def read_pdf_info(self) -> None:
|
| 580 |
+
assert self.buf is not None
|
| 581 |
+
self.file_size_total = len(self.buf)
|
| 582 |
+
self.file_size_this = self.file_size_total - self.start_offset
|
| 583 |
+
self.read_trailer()
|
| 584 |
+
check_format_condition(
|
| 585 |
+
self.trailer_dict.get(b"Root") is not None, "Root is missing"
|
| 586 |
+
)
|
| 587 |
+
self.root_ref = self.trailer_dict[b"Root"]
|
| 588 |
+
assert self.root_ref is not None
|
| 589 |
+
self.info_ref = self.trailer_dict.get(b"Info", None)
|
| 590 |
+
self.root = PdfDict(self.read_indirect(self.root_ref))
|
| 591 |
+
if self.info_ref is None:
|
| 592 |
+
self.info = PdfDict()
|
| 593 |
+
else:
|
| 594 |
+
self.info = PdfDict(self.read_indirect(self.info_ref))
|
| 595 |
+
check_format_condition(b"Type" in self.root, "/Type missing in Root")
|
| 596 |
+
check_format_condition(
|
| 597 |
+
self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog"
|
| 598 |
+
)
|
| 599 |
+
check_format_condition(
|
| 600 |
+
self.root.get(b"Pages") is not None, "/Pages missing in Root"
|
| 601 |
+
)
|
| 602 |
+
check_format_condition(
|
| 603 |
+
isinstance(self.root[b"Pages"], IndirectReference),
|
| 604 |
+
"/Pages in Root is not an indirect reference",
|
| 605 |
+
)
|
| 606 |
+
self.pages_ref = self.root[b"Pages"]
|
| 607 |
+
assert self.pages_ref is not None
|
| 608 |
+
self.page_tree_root = self.read_indirect(self.pages_ref)
|
| 609 |
+
self.pages = self.linearize_page_tree(self.page_tree_root)
|
| 610 |
+
# save the original list of page references
|
| 611 |
+
# in case the user modifies, adds or deletes some pages
|
| 612 |
+
# and we need to rewrite the pages and their list
|
| 613 |
+
self.orig_pages = self.pages[:]
|
| 614 |
+
|
| 615 |
+
def next_object_id(self, offset: int | None = None) -> IndirectReference:
|
| 616 |
+
try:
|
| 617 |
+
# TODO: support reuse of deleted objects
|
| 618 |
+
reference = IndirectReference(max(self.xref_table.keys()) + 1, 0)
|
| 619 |
+
except ValueError:
|
| 620 |
+
reference = IndirectReference(1, 0)
|
| 621 |
+
if offset is not None:
|
| 622 |
+
self.xref_table[reference.object_id] = (offset, 0)
|
| 623 |
+
return reference
|
| 624 |
+
|
| 625 |
+
delimiter = rb"[][()<>{}/%]"
|
| 626 |
+
delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]"
|
| 627 |
+
whitespace = rb"[\000\011\012\014\015\040]"
|
| 628 |
+
whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]"
|
| 629 |
+
whitespace_optional = whitespace + b"*"
|
| 630 |
+
whitespace_mandatory = whitespace + b"+"
|
| 631 |
+
# No "\012" aka "\n" or "\015" aka "\r":
|
| 632 |
+
whitespace_optional_no_nl = rb"[\000\011\014\040]*"
|
| 633 |
+
newline_only = rb"[\r\n]+"
|
| 634 |
+
newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl
|
| 635 |
+
re_trailer_end = re.compile(
|
| 636 |
+
whitespace_mandatory
|
| 637 |
+
+ rb"trailer"
|
| 638 |
+
+ whitespace_optional
|
| 639 |
+
+ rb"<<(.*>>)"
|
| 640 |
+
+ newline
|
| 641 |
+
+ rb"startxref"
|
| 642 |
+
+ newline
|
| 643 |
+
+ rb"([0-9]+)"
|
| 644 |
+
+ newline
|
| 645 |
+
+ rb"%%EOF"
|
| 646 |
+
+ whitespace_optional
|
| 647 |
+
+ rb"$",
|
| 648 |
+
re.DOTALL,
|
| 649 |
+
)
|
| 650 |
+
re_trailer_prev = re.compile(
|
| 651 |
+
whitespace_optional
|
| 652 |
+
+ rb"trailer"
|
| 653 |
+
+ whitespace_optional
|
| 654 |
+
+ rb"<<(.*?>>)"
|
| 655 |
+
+ newline
|
| 656 |
+
+ rb"startxref"
|
| 657 |
+
+ newline
|
| 658 |
+
+ rb"([0-9]+)"
|
| 659 |
+
+ newline
|
| 660 |
+
+ rb"%%EOF"
|
| 661 |
+
+ whitespace_optional,
|
| 662 |
+
re.DOTALL,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
def read_trailer(self) -> None:
|
| 666 |
+
assert self.buf is not None
|
| 667 |
+
search_start_offset = len(self.buf) - 16384
|
| 668 |
+
if search_start_offset < self.start_offset:
|
| 669 |
+
search_start_offset = self.start_offset
|
| 670 |
+
m = self.re_trailer_end.search(self.buf, search_start_offset)
|
| 671 |
+
check_format_condition(m is not None, "trailer end not found")
|
| 672 |
+
# make sure we found the LAST trailer
|
| 673 |
+
last_match = m
|
| 674 |
+
while m:
|
| 675 |
+
last_match = m
|
| 676 |
+
m = self.re_trailer_end.search(self.buf, m.start() + 16)
|
| 677 |
+
if not m:
|
| 678 |
+
m = last_match
|
| 679 |
+
assert m is not None
|
| 680 |
+
trailer_data = m.group(1)
|
| 681 |
+
self.last_xref_section_offset = int(m.group(2))
|
| 682 |
+
self.trailer_dict = self.interpret_trailer(trailer_data)
|
| 683 |
+
self.xref_table = XrefTable()
|
| 684 |
+
self.read_xref_table(xref_section_offset=self.last_xref_section_offset)
|
| 685 |
+
if b"Prev" in self.trailer_dict:
|
| 686 |
+
self.read_prev_trailer(self.trailer_dict[b"Prev"])
|
| 687 |
+
|
| 688 |
+
def read_prev_trailer(self, xref_section_offset: int) -> None:
|
| 689 |
+
assert self.buf is not None
|
| 690 |
+
trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)
|
| 691 |
+
m = self.re_trailer_prev.search(
|
| 692 |
+
self.buf[trailer_offset : trailer_offset + 16384]
|
| 693 |
+
)
|
| 694 |
+
check_format_condition(m is not None, "previous trailer not found")
|
| 695 |
+
assert m is not None
|
| 696 |
+
trailer_data = m.group(1)
|
| 697 |
+
check_format_condition(
|
| 698 |
+
int(m.group(2)) == xref_section_offset,
|
| 699 |
+
"xref section offset in previous trailer doesn't match what was expected",
|
| 700 |
+
)
|
| 701 |
+
trailer_dict = self.interpret_trailer(trailer_data)
|
| 702 |
+
if b"Prev" in trailer_dict:
|
| 703 |
+
self.read_prev_trailer(trailer_dict[b"Prev"])
|
| 704 |
+
|
| 705 |
+
re_whitespace_optional = re.compile(whitespace_optional)
|
| 706 |
+
re_name = re.compile(
|
| 707 |
+
whitespace_optional
|
| 708 |
+
+ rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?="
|
| 709 |
+
+ delimiter_or_ws
|
| 710 |
+
+ rb")"
|
| 711 |
+
)
|
| 712 |
+
re_dict_start = re.compile(whitespace_optional + rb"<<")
|
| 713 |
+
re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional)
|
| 714 |
+
|
| 715 |
+
@classmethod
|
| 716 |
+
def interpret_trailer(cls, trailer_data: bytes) -> dict[bytes, Any]:
|
| 717 |
+
trailer = {}
|
| 718 |
+
offset = 0
|
| 719 |
+
while True:
|
| 720 |
+
m = cls.re_name.match(trailer_data, offset)
|
| 721 |
+
if not m:
|
| 722 |
+
m = cls.re_dict_end.match(trailer_data, offset)
|
| 723 |
+
check_format_condition(
|
| 724 |
+
m is not None and m.end() == len(trailer_data),
|
| 725 |
+
"name not found in trailer, remaining data: "
|
| 726 |
+
+ repr(trailer_data[offset:]),
|
| 727 |
+
)
|
| 728 |
+
break
|
| 729 |
+
key = cls.interpret_name(m.group(1))
|
| 730 |
+
assert isinstance(key, bytes)
|
| 731 |
+
value, value_offset = cls.get_value(trailer_data, m.end())
|
| 732 |
+
trailer[key] = value
|
| 733 |
+
if value_offset is None:
|
| 734 |
+
break
|
| 735 |
+
offset = value_offset
|
| 736 |
+
check_format_condition(
|
| 737 |
+
b"Size" in trailer and isinstance(trailer[b"Size"], int),
|
| 738 |
+
"/Size not in trailer or not an integer",
|
| 739 |
+
)
|
| 740 |
+
check_format_condition(
|
| 741 |
+
b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference),
|
| 742 |
+
"/Root not in trailer or not an indirect reference",
|
| 743 |
+
)
|
| 744 |
+
return trailer
|
| 745 |
+
|
| 746 |
+
re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?")
|
| 747 |
+
|
| 748 |
+
@classmethod
|
| 749 |
+
def interpret_name(cls, raw: bytes, as_text: bool = False) -> str | bytes:
|
| 750 |
+
name = b""
|
| 751 |
+
for m in cls.re_hashes_in_name.finditer(raw):
|
| 752 |
+
if m.group(3):
|
| 753 |
+
name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii"))
|
| 754 |
+
else:
|
| 755 |
+
name += m.group(1)
|
| 756 |
+
if as_text:
|
| 757 |
+
return name.decode("utf-8")
|
| 758 |
+
else:
|
| 759 |
+
return bytes(name)
|
| 760 |
+
|
| 761 |
+
re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")")
|
| 762 |
+
re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")")
|
| 763 |
+
re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")")
|
| 764 |
+
re_int = re.compile(
|
| 765 |
+
whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")"
|
| 766 |
+
)
|
| 767 |
+
re_real = re.compile(
|
| 768 |
+
whitespace_optional
|
| 769 |
+
+ rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?="
|
| 770 |
+
+ delimiter_or_ws
|
| 771 |
+
+ rb")"
|
| 772 |
+
)
|
| 773 |
+
re_array_start = re.compile(whitespace_optional + rb"\[")
|
| 774 |
+
re_array_end = re.compile(whitespace_optional + rb"]")
|
| 775 |
+
re_string_hex = re.compile(
|
| 776 |
+
whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>"
|
| 777 |
+
)
|
| 778 |
+
re_string_lit = re.compile(whitespace_optional + rb"\(")
|
| 779 |
+
re_indirect_reference = re.compile(
|
| 780 |
+
whitespace_optional
|
| 781 |
+
+ rb"([-+]?[0-9]+)"
|
| 782 |
+
+ whitespace_mandatory
|
| 783 |
+
+ rb"([-+]?[0-9]+)"
|
| 784 |
+
+ whitespace_mandatory
|
| 785 |
+
+ rb"R(?="
|
| 786 |
+
+ delimiter_or_ws
|
| 787 |
+
+ rb")"
|
| 788 |
+
)
|
| 789 |
+
re_indirect_def_start = re.compile(
|
| 790 |
+
whitespace_optional
|
| 791 |
+
+ rb"([-+]?[0-9]+)"
|
| 792 |
+
+ whitespace_mandatory
|
| 793 |
+
+ rb"([-+]?[0-9]+)"
|
| 794 |
+
+ whitespace_mandatory
|
| 795 |
+
+ rb"obj(?="
|
| 796 |
+
+ delimiter_or_ws
|
| 797 |
+
+ rb")"
|
| 798 |
+
)
|
| 799 |
+
re_indirect_def_end = re.compile(
|
| 800 |
+
whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")"
|
| 801 |
+
)
|
| 802 |
+
re_comment = re.compile(
|
| 803 |
+
rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*"
|
| 804 |
+
)
|
| 805 |
+
re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n")
|
| 806 |
+
re_stream_end = re.compile(
|
| 807 |
+
whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")"
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
@classmethod
|
| 811 |
+
def get_value(
|
| 812 |
+
cls,
|
| 813 |
+
data: bytes | bytearray | mmap.mmap,
|
| 814 |
+
offset: int,
|
| 815 |
+
expect_indirect: IndirectReference | None = None,
|
| 816 |
+
max_nesting: int = -1,
|
| 817 |
+
) -> tuple[Any, int | None]:
|
| 818 |
+
if max_nesting == 0:
|
| 819 |
+
return None, None
|
| 820 |
+
m = cls.re_comment.match(data, offset)
|
| 821 |
+
if m:
|
| 822 |
+
offset = m.end()
|
| 823 |
+
m = cls.re_indirect_def_start.match(data, offset)
|
| 824 |
+
if m:
|
| 825 |
+
check_format_condition(
|
| 826 |
+
int(m.group(1)) > 0,
|
| 827 |
+
"indirect object definition: object ID must be greater than 0",
|
| 828 |
+
)
|
| 829 |
+
check_format_condition(
|
| 830 |
+
int(m.group(2)) >= 0,
|
| 831 |
+
"indirect object definition: generation must be non-negative",
|
| 832 |
+
)
|
| 833 |
+
check_format_condition(
|
| 834 |
+
expect_indirect is None
|
| 835 |
+
or expect_indirect
|
| 836 |
+
== IndirectReference(int(m.group(1)), int(m.group(2))),
|
| 837 |
+
"indirect object definition different than expected",
|
| 838 |
+
)
|
| 839 |
+
object, object_offset = cls.get_value(
|
| 840 |
+
data, m.end(), max_nesting=max_nesting - 1
|
| 841 |
+
)
|
| 842 |
+
if object_offset is None:
|
| 843 |
+
return object, None
|
| 844 |
+
m = cls.re_indirect_def_end.match(data, object_offset)
|
| 845 |
+
check_format_condition(
|
| 846 |
+
m is not None, "indirect object definition end not found"
|
| 847 |
+
)
|
| 848 |
+
assert m is not None
|
| 849 |
+
return object, m.end()
|
| 850 |
+
check_format_condition(
|
| 851 |
+
not expect_indirect, "indirect object definition not found"
|
| 852 |
+
)
|
| 853 |
+
m = cls.re_indirect_reference.match(data, offset)
|
| 854 |
+
if m:
|
| 855 |
+
check_format_condition(
|
| 856 |
+
int(m.group(1)) > 0,
|
| 857 |
+
"indirect object reference: object ID must be greater than 0",
|
| 858 |
+
)
|
| 859 |
+
check_format_condition(
|
| 860 |
+
int(m.group(2)) >= 0,
|
| 861 |
+
"indirect object reference: generation must be non-negative",
|
| 862 |
+
)
|
| 863 |
+
return IndirectReference(int(m.group(1)), int(m.group(2))), m.end()
|
| 864 |
+
m = cls.re_dict_start.match(data, offset)
|
| 865 |
+
if m:
|
| 866 |
+
offset = m.end()
|
| 867 |
+
result: dict[Any, Any] = {}
|
| 868 |
+
m = cls.re_dict_end.match(data, offset)
|
| 869 |
+
current_offset: int | None = offset
|
| 870 |
+
while not m:
|
| 871 |
+
assert current_offset is not None
|
| 872 |
+
key, current_offset = cls.get_value(
|
| 873 |
+
data, current_offset, max_nesting=max_nesting - 1
|
| 874 |
+
)
|
| 875 |
+
if current_offset is None:
|
| 876 |
+
return result, None
|
| 877 |
+
value, current_offset = cls.get_value(
|
| 878 |
+
data, current_offset, max_nesting=max_nesting - 1
|
| 879 |
+
)
|
| 880 |
+
result[key] = value
|
| 881 |
+
if current_offset is None:
|
| 882 |
+
return result, None
|
| 883 |
+
m = cls.re_dict_end.match(data, current_offset)
|
| 884 |
+
current_offset = m.end()
|
| 885 |
+
m = cls.re_stream_start.match(data, current_offset)
|
| 886 |
+
if m:
|
| 887 |
+
stream_len = result.get(b"Length")
|
| 888 |
+
if stream_len is None or not isinstance(stream_len, int):
|
| 889 |
+
msg = f"bad or missing Length in stream dict ({stream_len})"
|
| 890 |
+
raise PdfFormatError(msg)
|
| 891 |
+
stream_data = data[m.end() : m.end() + stream_len]
|
| 892 |
+
m = cls.re_stream_end.match(data, m.end() + stream_len)
|
| 893 |
+
check_format_condition(m is not None, "stream end not found")
|
| 894 |
+
assert m is not None
|
| 895 |
+
current_offset = m.end()
|
| 896 |
+
return PdfStream(PdfDict(result), stream_data), current_offset
|
| 897 |
+
return PdfDict(result), current_offset
|
| 898 |
+
m = cls.re_array_start.match(data, offset)
|
| 899 |
+
if m:
|
| 900 |
+
offset = m.end()
|
| 901 |
+
results = []
|
| 902 |
+
m = cls.re_array_end.match(data, offset)
|
| 903 |
+
current_offset = offset
|
| 904 |
+
while not m:
|
| 905 |
+
assert current_offset is not None
|
| 906 |
+
value, current_offset = cls.get_value(
|
| 907 |
+
data, current_offset, max_nesting=max_nesting - 1
|
| 908 |
+
)
|
| 909 |
+
results.append(value)
|
| 910 |
+
if current_offset is None:
|
| 911 |
+
return results, None
|
| 912 |
+
m = cls.re_array_end.match(data, current_offset)
|
| 913 |
+
return results, m.end()
|
| 914 |
+
m = cls.re_null.match(data, offset)
|
| 915 |
+
if m:
|
| 916 |
+
return None, m.end()
|
| 917 |
+
m = cls.re_true.match(data, offset)
|
| 918 |
+
if m:
|
| 919 |
+
return True, m.end()
|
| 920 |
+
m = cls.re_false.match(data, offset)
|
| 921 |
+
if m:
|
| 922 |
+
return False, m.end()
|
| 923 |
+
m = cls.re_name.match(data, offset)
|
| 924 |
+
if m:
|
| 925 |
+
return PdfName(cls.interpret_name(m.group(1))), m.end()
|
| 926 |
+
m = cls.re_int.match(data, offset)
|
| 927 |
+
if m:
|
| 928 |
+
return int(m.group(1)), m.end()
|
| 929 |
+
m = cls.re_real.match(data, offset)
|
| 930 |
+
if m:
|
| 931 |
+
# XXX Decimal instead of float???
|
| 932 |
+
return float(m.group(1)), m.end()
|
| 933 |
+
m = cls.re_string_hex.match(data, offset)
|
| 934 |
+
if m:
|
| 935 |
+
# filter out whitespace
|
| 936 |
+
hex_string = bytearray(
|
| 937 |
+
b for b in m.group(1) if b in b"0123456789abcdefABCDEF"
|
| 938 |
+
)
|
| 939 |
+
if len(hex_string) % 2 == 1:
|
| 940 |
+
# append a 0 if the length is not even - yes, at the end
|
| 941 |
+
hex_string.append(ord(b"0"))
|
| 942 |
+
return bytearray.fromhex(hex_string.decode("us-ascii")), m.end()
|
| 943 |
+
m = cls.re_string_lit.match(data, offset)
|
| 944 |
+
if m:
|
| 945 |
+
return cls.get_literal_string(data, m.end())
|
| 946 |
+
# return None, offset # fallback (only for debugging)
|
| 947 |
+
msg = f"unrecognized object: {repr(data[offset : offset + 32])}"
|
| 948 |
+
raise PdfFormatError(msg)
|
| 949 |
+
|
| 950 |
+
re_lit_str_token = re.compile(
|
| 951 |
+
rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"
|
| 952 |
+
)
|
| 953 |
+
escaped_chars = {
|
| 954 |
+
b"n": b"\n",
|
| 955 |
+
b"r": b"\r",
|
| 956 |
+
b"t": b"\t",
|
| 957 |
+
b"b": b"\b",
|
| 958 |
+
b"f": b"\f",
|
| 959 |
+
b"(": b"(",
|
| 960 |
+
b")": b")",
|
| 961 |
+
b"\\": b"\\",
|
| 962 |
+
ord(b"n"): b"\n",
|
| 963 |
+
ord(b"r"): b"\r",
|
| 964 |
+
ord(b"t"): b"\t",
|
| 965 |
+
ord(b"b"): b"\b",
|
| 966 |
+
ord(b"f"): b"\f",
|
| 967 |
+
ord(b"("): b"(",
|
| 968 |
+
ord(b")"): b")",
|
| 969 |
+
ord(b"\\"): b"\\",
|
| 970 |
+
}
|
| 971 |
+
|
| 972 |
+
@classmethod
|
| 973 |
+
def get_literal_string(
|
| 974 |
+
cls, data: bytes | bytearray | mmap.mmap, offset: int
|
| 975 |
+
) -> tuple[bytes, int]:
|
| 976 |
+
nesting_depth = 0
|
| 977 |
+
result = bytearray()
|
| 978 |
+
for m in cls.re_lit_str_token.finditer(data, offset):
|
| 979 |
+
result.extend(data[offset : m.start()])
|
| 980 |
+
if m.group(1):
|
| 981 |
+
result.extend(cls.escaped_chars[m.group(1)[1]])
|
| 982 |
+
elif m.group(2):
|
| 983 |
+
result.append(int(m.group(2)[1:], 8))
|
| 984 |
+
elif m.group(3):
|
| 985 |
+
pass
|
| 986 |
+
elif m.group(5):
|
| 987 |
+
result.extend(b"\n")
|
| 988 |
+
elif m.group(6):
|
| 989 |
+
result.extend(b"(")
|
| 990 |
+
nesting_depth += 1
|
| 991 |
+
elif m.group(7):
|
| 992 |
+
if nesting_depth == 0:
|
| 993 |
+
return bytes(result), m.end()
|
| 994 |
+
result.extend(b")")
|
| 995 |
+
nesting_depth -= 1
|
| 996 |
+
offset = m.end()
|
| 997 |
+
msg = "unfinished literal string"
|
| 998 |
+
raise PdfFormatError(msg)
|
| 999 |
+
|
| 1000 |
+
re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline)
|
| 1001 |
+
re_xref_subsection_start = re.compile(
|
| 1002 |
+
whitespace_optional
|
| 1003 |
+
+ rb"([0-9]+)"
|
| 1004 |
+
+ whitespace_mandatory
|
| 1005 |
+
+ rb"([0-9]+)"
|
| 1006 |
+
+ whitespace_optional
|
| 1007 |
+
+ newline_only
|
| 1008 |
+
)
|
| 1009 |
+
re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)")
|
| 1010 |
+
|
| 1011 |
+
def read_xref_table(self, xref_section_offset: int) -> int:
|
| 1012 |
+
assert self.buf is not None
|
| 1013 |
+
subsection_found = False
|
| 1014 |
+
m = self.re_xref_section_start.match(
|
| 1015 |
+
self.buf, xref_section_offset + self.start_offset
|
| 1016 |
+
)
|
| 1017 |
+
check_format_condition(m is not None, "xref section start not found")
|
| 1018 |
+
assert m is not None
|
| 1019 |
+
offset = m.end()
|
| 1020 |
+
while True:
|
| 1021 |
+
m = self.re_xref_subsection_start.match(self.buf, offset)
|
| 1022 |
+
if not m:
|
| 1023 |
+
check_format_condition(
|
| 1024 |
+
subsection_found, "xref subsection start not found"
|
| 1025 |
+
)
|
| 1026 |
+
break
|
| 1027 |
+
subsection_found = True
|
| 1028 |
+
offset = m.end()
|
| 1029 |
+
first_object = int(m.group(1))
|
| 1030 |
+
num_objects = int(m.group(2))
|
| 1031 |
+
for i in range(first_object, first_object + num_objects):
|
| 1032 |
+
m = self.re_xref_entry.match(self.buf, offset)
|
| 1033 |
+
check_format_condition(m is not None, "xref entry not found")
|
| 1034 |
+
assert m is not None
|
| 1035 |
+
offset = m.end()
|
| 1036 |
+
is_free = m.group(3) == b"f"
|
| 1037 |
+
if not is_free:
|
| 1038 |
+
generation = int(m.group(2))
|
| 1039 |
+
new_entry = (int(m.group(1)), generation)
|
| 1040 |
+
if i not in self.xref_table:
|
| 1041 |
+
self.xref_table[i] = new_entry
|
| 1042 |
+
return offset
|
| 1043 |
+
|
| 1044 |
+
def read_indirect(self, ref: IndirectReference, max_nesting: int = -1) -> Any:
|
| 1045 |
+
offset, generation = self.xref_table[ref[0]]
|
| 1046 |
+
check_format_condition(
|
| 1047 |
+
generation == ref[1],
|
| 1048 |
+
f"expected to find generation {ref[1]} for object ID {ref[0]} in xref "
|
| 1049 |
+
f"table, instead found generation {generation} at offset {offset}",
|
| 1050 |
+
)
|
| 1051 |
+
assert self.buf is not None
|
| 1052 |
+
value = self.get_value(
|
| 1053 |
+
self.buf,
|
| 1054 |
+
offset + self.start_offset,
|
| 1055 |
+
expect_indirect=IndirectReference(*ref),
|
| 1056 |
+
max_nesting=max_nesting,
|
| 1057 |
+
)[0]
|
| 1058 |
+
self.cached_objects[ref] = value
|
| 1059 |
+
return value
|
| 1060 |
+
|
| 1061 |
+
def linearize_page_tree(
|
| 1062 |
+
self, node: PdfDict | None = None
|
| 1063 |
+
) -> list[IndirectReference]:
|
| 1064 |
+
page_node = node if node is not None else self.page_tree_root
|
| 1065 |
+
check_format_condition(
|
| 1066 |
+
page_node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages"
|
| 1067 |
+
)
|
| 1068 |
+
pages = []
|
| 1069 |
+
for kid in page_node[b"Kids"]:
|
| 1070 |
+
kid_object = self.read_indirect(kid)
|
| 1071 |
+
if kid_object[b"Type"] == b"Page":
|
| 1072 |
+
pages.append(kid)
|
| 1073 |
+
else:
|
| 1074 |
+
pages.extend(self.linearize_page_tree(node=kid_object))
|
| 1075 |
+
return pages
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PIXAR raster support for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 97-01-29 fl Created
|
| 9 |
+
#
|
| 10 |
+
# notes:
|
| 11 |
+
# This is incomplete; it is based on a few samples created with
|
| 12 |
+
# Photoshop 2.5 and 3.0, and a summary description provided by
|
| 13 |
+
# Greg Coats <gcoats@labiris.er.usgs.gov>. Hopefully, "L" and
|
| 14 |
+
# "RGBA" support will be added in future versions.
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 17 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 18 |
+
#
|
| 19 |
+
# See the README file for information on usage and redistribution.
|
| 20 |
+
#
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile
|
| 24 |
+
from ._binary import i16le as i16
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# helpers
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _accept(prefix: bytes) -> bool:
|
| 31 |
+
return prefix.startswith(b"\200\350\000\000")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
##
|
| 35 |
+
# Image plugin for PIXAR raster images.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PixarImageFile(ImageFile.ImageFile):
|
| 39 |
+
format = "PIXAR"
|
| 40 |
+
format_description = "PIXAR raster image"
|
| 41 |
+
|
| 42 |
+
def _open(self) -> None:
|
| 43 |
+
# assuming a 4-byte magic label
|
| 44 |
+
assert self.fp is not None
|
| 45 |
+
|
| 46 |
+
s = self.fp.read(4)
|
| 47 |
+
if not _accept(s):
|
| 48 |
+
msg = "not a PIXAR file"
|
| 49 |
+
raise SyntaxError(msg)
|
| 50 |
+
|
| 51 |
+
# read rest of header
|
| 52 |
+
s = s + self.fp.read(508)
|
| 53 |
+
|
| 54 |
+
self._size = i16(s, 418), i16(s, 416)
|
| 55 |
+
|
| 56 |
+
# get channel/depth descriptions
|
| 57 |
+
mode = i16(s, 424), i16(s, 426)
|
| 58 |
+
|
| 59 |
+
if mode == (14, 2):
|
| 60 |
+
self._mode = "RGB"
|
| 61 |
+
# FIXME: to be continued...
|
| 62 |
+
|
| 63 |
+
# create tile descriptor (assuming "dumped")
|
| 64 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1024, self.mode)]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
#
|
| 68 |
+
# --------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
Image.register_open(PixarImageFile.format, PixarImageFile, _accept)
|
| 71 |
+
|
| 72 |
+
Image.register_extension(PixarImageFile.format, ".pxr")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py
ADDED
|
@@ -0,0 +1,1564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 fractions import Fraction
|
| 43 |
+
from typing import IO, NamedTuple, cast
|
| 44 |
+
|
| 45 |
+
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
|
| 46 |
+
from ._binary import i16be as i16
|
| 47 |
+
from ._binary import i32be as i32
|
| 48 |
+
from ._binary import o8
|
| 49 |
+
from ._binary import o16be as o16
|
| 50 |
+
from ._binary import o32be as o32
|
| 51 |
+
from ._deprecate import deprecate
|
| 52 |
+
from ._util import DeferredError
|
| 53 |
+
|
| 54 |
+
TYPE_CHECKING = False
|
| 55 |
+
if TYPE_CHECKING:
|
| 56 |
+
from collections.abc import Callable
|
| 57 |
+
from typing import Any, NoReturn
|
| 58 |
+
|
| 59 |
+
from . import _imaging
|
| 60 |
+
|
| 61 |
+
logger = logging.getLogger(__name__)
|
| 62 |
+
|
| 63 |
+
is_cid = re.compile(rb"\w\w\w\w").match
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
_MAGIC = b"\211PNG\r\n\032\n"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_MODES = {
|
| 70 |
+
# supported bits/color combinations, and corresponding modes/rawmodes
|
| 71 |
+
# Grayscale
|
| 72 |
+
(1, 0): ("1", "1"),
|
| 73 |
+
(2, 0): ("L", "L;2"),
|
| 74 |
+
(4, 0): ("L", "L;4"),
|
| 75 |
+
(8, 0): ("L", "L"),
|
| 76 |
+
(16, 0): ("I;16", "I;16B"),
|
| 77 |
+
# Truecolour
|
| 78 |
+
(8, 2): ("RGB", "RGB"),
|
| 79 |
+
(16, 2): ("RGB", "RGB;16B"),
|
| 80 |
+
# Indexed-colour
|
| 81 |
+
(1, 3): ("P", "P;1"),
|
| 82 |
+
(2, 3): ("P", "P;2"),
|
| 83 |
+
(4, 3): ("P", "P;4"),
|
| 84 |
+
(8, 3): ("P", "P"),
|
| 85 |
+
# Grayscale with alpha
|
| 86 |
+
(8, 4): ("LA", "LA"),
|
| 87 |
+
(16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
|
| 88 |
+
# Truecolour with alpha
|
| 89 |
+
(8, 6): ("RGBA", "RGBA"),
|
| 90 |
+
(16, 6): ("RGBA", "RGBA;16B"),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
_simple_palette = re.compile(b"^\xff*\x00\xff*$")
|
| 95 |
+
|
| 96 |
+
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
|
| 97 |
+
"""
|
| 98 |
+
Maximum decompressed size for a iTXt or zTXt chunk.
|
| 99 |
+
Eliminates decompression bombs where compressed chunks can expand 1000x.
|
| 100 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 101 |
+
"""
|
| 102 |
+
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
|
| 103 |
+
"""
|
| 104 |
+
Set the maximum total text chunk size.
|
| 105 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# APNG frame disposal modes
|
| 110 |
+
class Disposal(IntEnum):
|
| 111 |
+
OP_NONE = 0
|
| 112 |
+
"""
|
| 113 |
+
No disposal is done on this frame before rendering the next frame.
|
| 114 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 115 |
+
"""
|
| 116 |
+
OP_BACKGROUND = 1
|
| 117 |
+
"""
|
| 118 |
+
This frame’s modified region is cleared to fully transparent black before rendering
|
| 119 |
+
the next frame.
|
| 120 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 121 |
+
"""
|
| 122 |
+
OP_PREVIOUS = 2
|
| 123 |
+
"""
|
| 124 |
+
This frame’s modified region is reverted to the previous frame’s contents before
|
| 125 |
+
rendering the next frame.
|
| 126 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# APNG frame blend modes
|
| 131 |
+
class Blend(IntEnum):
|
| 132 |
+
OP_SOURCE = 0
|
| 133 |
+
"""
|
| 134 |
+
All color components of this frame, including alpha, overwrite the previous output
|
| 135 |
+
image contents.
|
| 136 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 137 |
+
"""
|
| 138 |
+
OP_OVER = 1
|
| 139 |
+
"""
|
| 140 |
+
This frame should be alpha composited with the previous output image contents.
|
| 141 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _safe_zlib_decompress(s: bytes) -> bytes:
|
| 146 |
+
dobj = zlib.decompressobj()
|
| 147 |
+
plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
|
| 148 |
+
if dobj.unconsumed_tail:
|
| 149 |
+
msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"
|
| 150 |
+
raise ValueError(msg)
|
| 151 |
+
return plaintext
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _crc32(data: bytes, seed: int = 0) -> int:
|
| 155 |
+
return zlib.crc32(data, seed) & 0xFFFFFFFF
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# --------------------------------------------------------------------
|
| 159 |
+
# Support classes. Suitable for PNG and related formats like MNG etc.
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class ChunkStream:
|
| 163 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 164 |
+
self.fp: IO[bytes] | None = fp
|
| 165 |
+
self.queue: list[tuple[bytes, int, int]] | None = []
|
| 166 |
+
|
| 167 |
+
def read(self) -> tuple[bytes, int, int]:
|
| 168 |
+
"""Fetch a new chunk. Returns header information."""
|
| 169 |
+
cid = None
|
| 170 |
+
|
| 171 |
+
assert self.fp is not None
|
| 172 |
+
if self.queue:
|
| 173 |
+
cid, pos, length = self.queue.pop()
|
| 174 |
+
self.fp.seek(pos)
|
| 175 |
+
else:
|
| 176 |
+
s = self.fp.read(8)
|
| 177 |
+
cid = s[4:]
|
| 178 |
+
pos = self.fp.tell()
|
| 179 |
+
length = i32(s)
|
| 180 |
+
|
| 181 |
+
if not is_cid(cid):
|
| 182 |
+
if not ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 183 |
+
msg = f"broken PNG file (chunk {repr(cid)})"
|
| 184 |
+
raise SyntaxError(msg)
|
| 185 |
+
|
| 186 |
+
return cid, pos, length
|
| 187 |
+
|
| 188 |
+
def __enter__(self) -> ChunkStream:
|
| 189 |
+
return self
|
| 190 |
+
|
| 191 |
+
def __exit__(self, *args: object) -> None:
|
| 192 |
+
self.close()
|
| 193 |
+
|
| 194 |
+
def close(self) -> None:
|
| 195 |
+
self.queue = self.fp = None
|
| 196 |
+
|
| 197 |
+
def push(self, cid: bytes, pos: int, length: int) -> None:
|
| 198 |
+
assert self.queue is not None
|
| 199 |
+
self.queue.append((cid, pos, length))
|
| 200 |
+
|
| 201 |
+
def call(self, cid: bytes, pos: int, length: int) -> bytes:
|
| 202 |
+
"""Call the appropriate chunk handler"""
|
| 203 |
+
|
| 204 |
+
logger.debug("STREAM %r %s %s", cid, pos, length)
|
| 205 |
+
return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
|
| 206 |
+
|
| 207 |
+
def crc(self, cid: bytes, data: bytes) -> None:
|
| 208 |
+
"""Read and verify checksum"""
|
| 209 |
+
|
| 210 |
+
# Skip CRC checks for ancillary chunks if allowed to load truncated
|
| 211 |
+
# images
|
| 212 |
+
# 5th byte of first char is 1 [specs, section 5.4]
|
| 213 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
|
| 214 |
+
self.crc_skip(cid, data)
|
| 215 |
+
return
|
| 216 |
+
|
| 217 |
+
assert self.fp is not None
|
| 218 |
+
try:
|
| 219 |
+
crc1 = _crc32(data, _crc32(cid))
|
| 220 |
+
crc2 = i32(self.fp.read(4))
|
| 221 |
+
if crc1 != crc2:
|
| 222 |
+
msg = f"broken PNG file (bad header checksum in {repr(cid)})"
|
| 223 |
+
raise SyntaxError(msg)
|
| 224 |
+
except struct.error as e:
|
| 225 |
+
msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
|
| 226 |
+
raise SyntaxError(msg) from e
|
| 227 |
+
|
| 228 |
+
def crc_skip(self, cid: bytes, data: bytes) -> None:
|
| 229 |
+
"""Read checksum"""
|
| 230 |
+
|
| 231 |
+
assert self.fp is not None
|
| 232 |
+
self.fp.read(4)
|
| 233 |
+
|
| 234 |
+
def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
|
| 235 |
+
# Simple approach; just calculate checksum for all remaining
|
| 236 |
+
# blocks. Must be called directly after open.
|
| 237 |
+
|
| 238 |
+
cids = []
|
| 239 |
+
|
| 240 |
+
assert self.fp is not None
|
| 241 |
+
while True:
|
| 242 |
+
try:
|
| 243 |
+
cid, pos, length = self.read()
|
| 244 |
+
except struct.error as e:
|
| 245 |
+
msg = "truncated PNG file"
|
| 246 |
+
raise OSError(msg) from e
|
| 247 |
+
|
| 248 |
+
if cid == endchunk:
|
| 249 |
+
break
|
| 250 |
+
self.crc(cid, ImageFile._safe_read(self.fp, length))
|
| 251 |
+
cids.append(cid)
|
| 252 |
+
|
| 253 |
+
return cids
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class iTXt(str):
|
| 257 |
+
"""
|
| 258 |
+
Subclass of string to allow iTXt chunks to look like strings while
|
| 259 |
+
keeping their extra information
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
lang: str | bytes | None
|
| 264 |
+
tkey: str | bytes | None
|
| 265 |
+
|
| 266 |
+
@staticmethod
|
| 267 |
+
def __new__(
|
| 268 |
+
cls, text: str, lang: str | None = None, tkey: str | None = None
|
| 269 |
+
) -> iTXt:
|
| 270 |
+
"""
|
| 271 |
+
:param cls: the class to use when creating the instance
|
| 272 |
+
:param text: value for this key
|
| 273 |
+
:param lang: language code
|
| 274 |
+
:param tkey: UTF-8 version of the key name
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
self = str.__new__(cls, text)
|
| 278 |
+
self.lang = lang
|
| 279 |
+
self.tkey = tkey
|
| 280 |
+
return self
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class PngInfo:
|
| 284 |
+
"""
|
| 285 |
+
PNG chunk container (for use with save(pnginfo=))
|
| 286 |
+
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
def __init__(self) -> None:
|
| 290 |
+
self.chunks: list[tuple[bytes, bytes, bool]] = []
|
| 291 |
+
|
| 292 |
+
def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
|
| 293 |
+
"""Appends an arbitrary chunk. Use with caution.
|
| 294 |
+
|
| 295 |
+
:param cid: a byte string, 4 bytes long.
|
| 296 |
+
:param data: a byte string of the encoded data
|
| 297 |
+
:param after_idat: for use with private chunks. Whether the chunk
|
| 298 |
+
should be written after IDAT
|
| 299 |
+
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
self.chunks.append((cid, data, after_idat))
|
| 303 |
+
|
| 304 |
+
def add_itxt(
|
| 305 |
+
self,
|
| 306 |
+
key: str | bytes,
|
| 307 |
+
value: str | bytes,
|
| 308 |
+
lang: str | bytes = "",
|
| 309 |
+
tkey: str | bytes = "",
|
| 310 |
+
zip: bool = False,
|
| 311 |
+
) -> None:
|
| 312 |
+
"""Appends an iTXt chunk.
|
| 313 |
+
|
| 314 |
+
:param key: latin-1 encodable text key name
|
| 315 |
+
:param value: value for this key
|
| 316 |
+
:param lang: language code
|
| 317 |
+
:param tkey: UTF-8 version of the key name
|
| 318 |
+
:param zip: compression flag
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
if not isinstance(key, bytes):
|
| 323 |
+
key = key.encode("latin-1", "strict")
|
| 324 |
+
if not isinstance(value, bytes):
|
| 325 |
+
value = value.encode("utf-8", "strict")
|
| 326 |
+
if not isinstance(lang, bytes):
|
| 327 |
+
lang = lang.encode("utf-8", "strict")
|
| 328 |
+
if not isinstance(tkey, bytes):
|
| 329 |
+
tkey = tkey.encode("utf-8", "strict")
|
| 330 |
+
|
| 331 |
+
if zip:
|
| 332 |
+
self.add(
|
| 333 |
+
b"iTXt",
|
| 334 |
+
key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
|
| 335 |
+
)
|
| 336 |
+
else:
|
| 337 |
+
self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
|
| 338 |
+
|
| 339 |
+
def add_text(
|
| 340 |
+
self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
|
| 341 |
+
) -> None:
|
| 342 |
+
"""Appends a text chunk.
|
| 343 |
+
|
| 344 |
+
:param key: latin-1 encodable text key name
|
| 345 |
+
:param value: value for this key, text or an
|
| 346 |
+
:py:class:`PIL.PngImagePlugin.iTXt` instance
|
| 347 |
+
:param zip: compression flag
|
| 348 |
+
|
| 349 |
+
"""
|
| 350 |
+
if isinstance(value, iTXt):
|
| 351 |
+
return self.add_itxt(
|
| 352 |
+
key,
|
| 353 |
+
value,
|
| 354 |
+
value.lang if value.lang is not None else b"",
|
| 355 |
+
value.tkey if value.tkey is not None else b"",
|
| 356 |
+
zip=zip,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# The tEXt chunk stores latin-1 text
|
| 360 |
+
if not isinstance(value, bytes):
|
| 361 |
+
try:
|
| 362 |
+
value = value.encode("latin-1", "strict")
|
| 363 |
+
except UnicodeError:
|
| 364 |
+
return self.add_itxt(key, value, zip=zip)
|
| 365 |
+
|
| 366 |
+
if not isinstance(key, bytes):
|
| 367 |
+
key = key.encode("latin-1", "strict")
|
| 368 |
+
|
| 369 |
+
if zip:
|
| 370 |
+
self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
|
| 371 |
+
else:
|
| 372 |
+
self.add(b"tEXt", key + b"\0" + value)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# --------------------------------------------------------------------
|
| 376 |
+
# PNG image stream (IHDR/IEND)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class _RewindState(NamedTuple):
|
| 380 |
+
info: dict[str | tuple[int, int], Any]
|
| 381 |
+
tile: list[ImageFile._Tile]
|
| 382 |
+
seq_num: int | None
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class PngStream(ChunkStream):
|
| 386 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 387 |
+
super().__init__(fp)
|
| 388 |
+
|
| 389 |
+
# local copies of Image attributes
|
| 390 |
+
self.im_info: dict[str | tuple[int, int], Any] = {}
|
| 391 |
+
self.im_text: dict[str, str | iTXt] = {}
|
| 392 |
+
self.im_size = (0, 0)
|
| 393 |
+
self.im_mode = ""
|
| 394 |
+
self.im_tile: list[ImageFile._Tile] = []
|
| 395 |
+
self.im_palette: tuple[str, bytes] | None = None
|
| 396 |
+
self.im_custom_mimetype: str | None = None
|
| 397 |
+
self.im_n_frames: int | None = None
|
| 398 |
+
self._seq_num: int | None = None
|
| 399 |
+
self.rewind_state = _RewindState({}, [], None)
|
| 400 |
+
|
| 401 |
+
self.text_memory = 0
|
| 402 |
+
|
| 403 |
+
def check_text_memory(self, chunklen: int) -> None:
|
| 404 |
+
self.text_memory += chunklen
|
| 405 |
+
if self.text_memory > MAX_TEXT_MEMORY:
|
| 406 |
+
msg = (
|
| 407 |
+
"Too much memory used in text chunks: "
|
| 408 |
+
f"{self.text_memory}>MAX_TEXT_MEMORY"
|
| 409 |
+
)
|
| 410 |
+
raise ValueError(msg)
|
| 411 |
+
|
| 412 |
+
def save_rewind(self) -> None:
|
| 413 |
+
self.rewind_state = _RewindState(
|
| 414 |
+
self.im_info.copy(),
|
| 415 |
+
self.im_tile,
|
| 416 |
+
self._seq_num,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
def rewind(self) -> None:
|
| 420 |
+
self.im_info = self.rewind_state.info.copy()
|
| 421 |
+
self.im_tile = self.rewind_state.tile
|
| 422 |
+
self._seq_num = self.rewind_state.seq_num
|
| 423 |
+
|
| 424 |
+
def chunk_iCCP(self, pos: int, length: int) -> bytes:
|
| 425 |
+
# ICC profile
|
| 426 |
+
assert self.fp is not None
|
| 427 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 428 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 429 |
+
# Profile name 1-79 bytes (character string)
|
| 430 |
+
# Null separator 1 byte (null character)
|
| 431 |
+
# Compression method 1 byte (0)
|
| 432 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 433 |
+
i = s.find(b"\0")
|
| 434 |
+
logger.debug("iCCP profile name %r", s[:i])
|
| 435 |
+
comp_method = s[i + 1]
|
| 436 |
+
logger.debug("Compression method %s", comp_method)
|
| 437 |
+
if comp_method != 0:
|
| 438 |
+
msg = f"Unknown compression method {comp_method} in iCCP chunk"
|
| 439 |
+
raise SyntaxError(msg)
|
| 440 |
+
try:
|
| 441 |
+
icc_profile = _safe_zlib_decompress(s[i + 2 :])
|
| 442 |
+
except ValueError:
|
| 443 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 444 |
+
icc_profile = None
|
| 445 |
+
else:
|
| 446 |
+
raise
|
| 447 |
+
except zlib.error:
|
| 448 |
+
icc_profile = None # FIXME
|
| 449 |
+
self.im_info["icc_profile"] = icc_profile
|
| 450 |
+
return s
|
| 451 |
+
|
| 452 |
+
def chunk_IHDR(self, pos: int, length: int) -> bytes:
|
| 453 |
+
# image header
|
| 454 |
+
assert self.fp is not None
|
| 455 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 456 |
+
if length < 13:
|
| 457 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 458 |
+
return s
|
| 459 |
+
msg = "Truncated IHDR chunk"
|
| 460 |
+
raise ValueError(msg)
|
| 461 |
+
self.im_size = i32(s, 0), i32(s, 4)
|
| 462 |
+
try:
|
| 463 |
+
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
|
| 464 |
+
except Exception:
|
| 465 |
+
pass
|
| 466 |
+
if s[12]:
|
| 467 |
+
self.im_info["interlace"] = 1
|
| 468 |
+
if s[11]:
|
| 469 |
+
msg = "unknown filter category"
|
| 470 |
+
raise SyntaxError(msg)
|
| 471 |
+
return s
|
| 472 |
+
|
| 473 |
+
def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
|
| 474 |
+
# image data
|
| 475 |
+
if "bbox" in self.im_info:
|
| 476 |
+
tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]
|
| 477 |
+
else:
|
| 478 |
+
if self.im_n_frames is not None:
|
| 479 |
+
self.im_info["default_image"] = True
|
| 480 |
+
tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
|
| 481 |
+
self.im_tile = tile
|
| 482 |
+
self.im_idat = length
|
| 483 |
+
msg = "image data found"
|
| 484 |
+
raise EOFError(msg)
|
| 485 |
+
|
| 486 |
+
def chunk_IEND(self, pos: int, length: int) -> NoReturn:
|
| 487 |
+
msg = "end of PNG image"
|
| 488 |
+
raise EOFError(msg)
|
| 489 |
+
|
| 490 |
+
def chunk_PLTE(self, pos: int, length: int) -> bytes:
|
| 491 |
+
# palette
|
| 492 |
+
assert self.fp is not None
|
| 493 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 494 |
+
if self.im_mode == "P":
|
| 495 |
+
self.im_palette = "RGB", s
|
| 496 |
+
return s
|
| 497 |
+
|
| 498 |
+
def chunk_tRNS(self, pos: int, length: int) -> bytes:
|
| 499 |
+
# transparency
|
| 500 |
+
assert self.fp is not None
|
| 501 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 502 |
+
if self.im_mode == "P":
|
| 503 |
+
if _simple_palette.match(s):
|
| 504 |
+
# tRNS contains only one full-transparent entry,
|
| 505 |
+
# other entries are full opaque
|
| 506 |
+
i = s.find(b"\0")
|
| 507 |
+
if i >= 0:
|
| 508 |
+
self.im_info["transparency"] = i
|
| 509 |
+
else:
|
| 510 |
+
# otherwise, we have a byte string with one alpha value
|
| 511 |
+
# for each palette entry
|
| 512 |
+
self.im_info["transparency"] = s
|
| 513 |
+
elif self.im_mode == "1":
|
| 514 |
+
self.im_info["transparency"] = 255 if i16(s) else 0
|
| 515 |
+
elif self.im_mode in ("L", "I;16"):
|
| 516 |
+
self.im_info["transparency"] = i16(s)
|
| 517 |
+
elif self.im_mode == "RGB":
|
| 518 |
+
self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
|
| 519 |
+
return s
|
| 520 |
+
|
| 521 |
+
def chunk_gAMA(self, pos: int, length: int) -> bytes:
|
| 522 |
+
# gamma setting
|
| 523 |
+
assert self.fp is not None
|
| 524 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 525 |
+
self.im_info["gamma"] = i32(s) / 100000.0
|
| 526 |
+
return s
|
| 527 |
+
|
| 528 |
+
def chunk_cHRM(self, pos: int, length: int) -> bytes:
|
| 529 |
+
# chromaticity, 8 unsigned ints, actual value is scaled by 100,000
|
| 530 |
+
# WP x,y, Red x,y, Green x,y Blue x,y
|
| 531 |
+
|
| 532 |
+
assert self.fp is not None
|
| 533 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 534 |
+
raw_vals = struct.unpack(f">{len(s) // 4}I", s)
|
| 535 |
+
self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
|
| 536 |
+
return s
|
| 537 |
+
|
| 538 |
+
def chunk_sRGB(self, pos: int, length: int) -> bytes:
|
| 539 |
+
# srgb rendering intent, 1 byte
|
| 540 |
+
# 0 perceptual
|
| 541 |
+
# 1 relative colorimetric
|
| 542 |
+
# 2 saturation
|
| 543 |
+
# 3 absolute colorimetric
|
| 544 |
+
|
| 545 |
+
assert self.fp is not None
|
| 546 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 547 |
+
if length < 1:
|
| 548 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 549 |
+
return s
|
| 550 |
+
msg = "Truncated sRGB chunk"
|
| 551 |
+
raise ValueError(msg)
|
| 552 |
+
self.im_info["srgb"] = s[0]
|
| 553 |
+
return s
|
| 554 |
+
|
| 555 |
+
def chunk_pHYs(self, pos: int, length: int) -> bytes:
|
| 556 |
+
# pixels per unit
|
| 557 |
+
assert self.fp is not None
|
| 558 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 559 |
+
if length < 9:
|
| 560 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 561 |
+
return s
|
| 562 |
+
msg = "Truncated pHYs chunk"
|
| 563 |
+
raise ValueError(msg)
|
| 564 |
+
px, py = i32(s, 0), i32(s, 4)
|
| 565 |
+
unit = s[8]
|
| 566 |
+
if unit == 1: # meter
|
| 567 |
+
dpi = px * 0.0254, py * 0.0254
|
| 568 |
+
self.im_info["dpi"] = dpi
|
| 569 |
+
elif unit == 0:
|
| 570 |
+
self.im_info["aspect"] = px, py
|
| 571 |
+
return s
|
| 572 |
+
|
| 573 |
+
def chunk_tEXt(self, pos: int, length: int) -> bytes:
|
| 574 |
+
# text
|
| 575 |
+
assert self.fp is not None
|
| 576 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 577 |
+
try:
|
| 578 |
+
k, v = s.split(b"\0", 1)
|
| 579 |
+
except ValueError:
|
| 580 |
+
# fallback for broken tEXt tags
|
| 581 |
+
k = s
|
| 582 |
+
v = b""
|
| 583 |
+
if k:
|
| 584 |
+
k_str = k.decode("latin-1", "strict")
|
| 585 |
+
v_str = v.decode("latin-1", "replace")
|
| 586 |
+
|
| 587 |
+
self.im_info[k_str] = v if k == b"exif" else v_str
|
| 588 |
+
self.im_text[k_str] = v_str
|
| 589 |
+
self.check_text_memory(len(v_str))
|
| 590 |
+
|
| 591 |
+
return s
|
| 592 |
+
|
| 593 |
+
def chunk_zTXt(self, pos: int, length: int) -> bytes:
|
| 594 |
+
# compressed text
|
| 595 |
+
assert self.fp is not None
|
| 596 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 597 |
+
try:
|
| 598 |
+
k, v = s.split(b"\0", 1)
|
| 599 |
+
except ValueError:
|
| 600 |
+
k = s
|
| 601 |
+
v = b""
|
| 602 |
+
if v:
|
| 603 |
+
comp_method = v[0]
|
| 604 |
+
else:
|
| 605 |
+
comp_method = 0
|
| 606 |
+
if comp_method != 0:
|
| 607 |
+
msg = f"Unknown compression method {comp_method} in zTXt chunk"
|
| 608 |
+
raise SyntaxError(msg)
|
| 609 |
+
try:
|
| 610 |
+
v = _safe_zlib_decompress(v[1:])
|
| 611 |
+
except ValueError:
|
| 612 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 613 |
+
v = b""
|
| 614 |
+
else:
|
| 615 |
+
raise
|
| 616 |
+
except zlib.error:
|
| 617 |
+
v = b""
|
| 618 |
+
|
| 619 |
+
if k:
|
| 620 |
+
k_str = k.decode("latin-1", "strict")
|
| 621 |
+
v_str = v.decode("latin-1", "replace")
|
| 622 |
+
|
| 623 |
+
self.im_info[k_str] = self.im_text[k_str] = v_str
|
| 624 |
+
self.check_text_memory(len(v_str))
|
| 625 |
+
|
| 626 |
+
return s
|
| 627 |
+
|
| 628 |
+
def chunk_iTXt(self, pos: int, length: int) -> bytes:
|
| 629 |
+
# international text
|
| 630 |
+
assert self.fp is not None
|
| 631 |
+
r = s = ImageFile._safe_read(self.fp, length)
|
| 632 |
+
try:
|
| 633 |
+
k, r = r.split(b"\0", 1)
|
| 634 |
+
except ValueError:
|
| 635 |
+
return s
|
| 636 |
+
if len(r) < 2:
|
| 637 |
+
return s
|
| 638 |
+
cf, cm, r = r[0], r[1], r[2:]
|
| 639 |
+
try:
|
| 640 |
+
lang, tk, v = r.split(b"\0", 2)
|
| 641 |
+
except ValueError:
|
| 642 |
+
return s
|
| 643 |
+
if cf != 0:
|
| 644 |
+
if cm == 0:
|
| 645 |
+
try:
|
| 646 |
+
v = _safe_zlib_decompress(v)
|
| 647 |
+
except ValueError:
|
| 648 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 649 |
+
return s
|
| 650 |
+
else:
|
| 651 |
+
raise
|
| 652 |
+
except zlib.error:
|
| 653 |
+
return s
|
| 654 |
+
else:
|
| 655 |
+
return s
|
| 656 |
+
if k == b"XML:com.adobe.xmp":
|
| 657 |
+
self.im_info["xmp"] = v
|
| 658 |
+
try:
|
| 659 |
+
k_str = k.decode("latin-1", "strict")
|
| 660 |
+
lang_str = lang.decode("utf-8", "strict")
|
| 661 |
+
tk_str = tk.decode("utf-8", "strict")
|
| 662 |
+
v_str = v.decode("utf-8", "strict")
|
| 663 |
+
except UnicodeError:
|
| 664 |
+
return s
|
| 665 |
+
|
| 666 |
+
self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)
|
| 667 |
+
self.check_text_memory(len(v_str))
|
| 668 |
+
|
| 669 |
+
return s
|
| 670 |
+
|
| 671 |
+
def chunk_eXIf(self, pos: int, length: int) -> bytes:
|
| 672 |
+
assert self.fp is not None
|
| 673 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 674 |
+
self.im_info["exif"] = b"Exif\x00\x00" + s
|
| 675 |
+
return s
|
| 676 |
+
|
| 677 |
+
# APNG chunks
|
| 678 |
+
def chunk_acTL(self, pos: int, length: int) -> bytes:
|
| 679 |
+
assert self.fp is not None
|
| 680 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 681 |
+
if length < 8:
|
| 682 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 683 |
+
return s
|
| 684 |
+
msg = "APNG contains truncated acTL chunk"
|
| 685 |
+
raise ValueError(msg)
|
| 686 |
+
if self.im_n_frames is not None:
|
| 687 |
+
self.im_n_frames = None
|
| 688 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 689 |
+
return s
|
| 690 |
+
n_frames = i32(s)
|
| 691 |
+
if n_frames == 0 or n_frames > 0x80000000:
|
| 692 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 693 |
+
return s
|
| 694 |
+
self.im_n_frames = n_frames
|
| 695 |
+
self.im_info["loop"] = i32(s, 4)
|
| 696 |
+
self.im_custom_mimetype = "image/apng"
|
| 697 |
+
return s
|
| 698 |
+
|
| 699 |
+
def chunk_fcTL(self, pos: int, length: int) -> bytes:
|
| 700 |
+
assert self.fp is not None
|
| 701 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 702 |
+
if length < 26:
|
| 703 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 704 |
+
return s
|
| 705 |
+
msg = "APNG contains truncated fcTL chunk"
|
| 706 |
+
raise ValueError(msg)
|
| 707 |
+
seq = i32(s)
|
| 708 |
+
if (self._seq_num is None and seq != 0) or (
|
| 709 |
+
self._seq_num is not None and self._seq_num != seq - 1
|
| 710 |
+
):
|
| 711 |
+
msg = "APNG contains frame sequence errors"
|
| 712 |
+
raise SyntaxError(msg)
|
| 713 |
+
self._seq_num = seq
|
| 714 |
+
width, height = i32(s, 4), i32(s, 8)
|
| 715 |
+
px, py = i32(s, 12), i32(s, 16)
|
| 716 |
+
im_w, im_h = self.im_size
|
| 717 |
+
if px + width > im_w or py + height > im_h:
|
| 718 |
+
msg = "APNG contains invalid frames"
|
| 719 |
+
raise SyntaxError(msg)
|
| 720 |
+
self.im_info["bbox"] = (px, py, px + width, py + height)
|
| 721 |
+
delay_num, delay_den = i16(s, 20), i16(s, 22)
|
| 722 |
+
if delay_den == 0:
|
| 723 |
+
delay_den = 100
|
| 724 |
+
self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
|
| 725 |
+
self.im_info["disposal"] = s[24]
|
| 726 |
+
self.im_info["blend"] = s[25]
|
| 727 |
+
return s
|
| 728 |
+
|
| 729 |
+
def chunk_fdAT(self, pos: int, length: int) -> bytes:
|
| 730 |
+
assert self.fp is not None
|
| 731 |
+
if length < 4:
|
| 732 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 733 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 734 |
+
return s
|
| 735 |
+
msg = "APNG contains truncated fDAT chunk"
|
| 736 |
+
raise ValueError(msg)
|
| 737 |
+
s = ImageFile._safe_read(self.fp, 4)
|
| 738 |
+
seq = i32(s)
|
| 739 |
+
if self._seq_num != seq - 1:
|
| 740 |
+
msg = "APNG contains frame sequence errors"
|
| 741 |
+
raise SyntaxError(msg)
|
| 742 |
+
self._seq_num = seq
|
| 743 |
+
return self.chunk_IDAT(pos + 4, length - 4)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
# --------------------------------------------------------------------
|
| 747 |
+
# PNG reader
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def _accept(prefix: bytes) -> bool:
|
| 751 |
+
return prefix.startswith(_MAGIC)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
##
|
| 755 |
+
# Image plugin for PNG images.
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
class PngImageFile(ImageFile.ImageFile):
|
| 759 |
+
format = "PNG"
|
| 760 |
+
format_description = "Portable network graphics"
|
| 761 |
+
|
| 762 |
+
def _open(self) -> None:
|
| 763 |
+
assert self.fp is not None
|
| 764 |
+
if not _accept(self.fp.read(8)):
|
| 765 |
+
msg = "not a PNG file"
|
| 766 |
+
raise SyntaxError(msg)
|
| 767 |
+
self._fp = self.fp
|
| 768 |
+
self.__frame = 0
|
| 769 |
+
|
| 770 |
+
#
|
| 771 |
+
# Parse headers up to the first IDAT or fDAT chunk
|
| 772 |
+
|
| 773 |
+
self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
|
| 774 |
+
self.png: PngStream | None = PngStream(self.fp)
|
| 775 |
+
|
| 776 |
+
while True:
|
| 777 |
+
#
|
| 778 |
+
# get next chunk
|
| 779 |
+
|
| 780 |
+
cid, pos, length = self.png.read()
|
| 781 |
+
|
| 782 |
+
try:
|
| 783 |
+
s = self.png.call(cid, pos, length)
|
| 784 |
+
except EOFError:
|
| 785 |
+
break
|
| 786 |
+
except AttributeError:
|
| 787 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 788 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 789 |
+
if cid[1:2].islower():
|
| 790 |
+
self.private_chunks.append((cid, s))
|
| 791 |
+
|
| 792 |
+
self.png.crc(cid, s)
|
| 793 |
+
|
| 794 |
+
#
|
| 795 |
+
# Copy relevant attributes from the PngStream. An alternative
|
| 796 |
+
# would be to let the PngStream class modify these attributes
|
| 797 |
+
# directly, but that introduces circular references which are
|
| 798 |
+
# difficult to break if things go wrong in the decoder...
|
| 799 |
+
# (believe me, I've tried ;-)
|
| 800 |
+
|
| 801 |
+
self._mode = self.png.im_mode
|
| 802 |
+
self._size = self.png.im_size
|
| 803 |
+
self.info = self.png.im_info
|
| 804 |
+
self._text: dict[str, str | iTXt] | None = None
|
| 805 |
+
self.tile = self.png.im_tile
|
| 806 |
+
self.custom_mimetype = self.png.im_custom_mimetype
|
| 807 |
+
self.n_frames = self.png.im_n_frames or 1
|
| 808 |
+
self.default_image = self.info.get("default_image", False)
|
| 809 |
+
|
| 810 |
+
if self.png.im_palette:
|
| 811 |
+
rawmode, data = self.png.im_palette
|
| 812 |
+
self.palette = ImagePalette.raw(rawmode, data)
|
| 813 |
+
|
| 814 |
+
if cid == b"fdAT":
|
| 815 |
+
self.__prepare_idat = length - 4
|
| 816 |
+
else:
|
| 817 |
+
self.__prepare_idat = length # used by load_prepare()
|
| 818 |
+
|
| 819 |
+
if self.png.im_n_frames is not None:
|
| 820 |
+
self._close_exclusive_fp_after_loading = False
|
| 821 |
+
self.png.save_rewind()
|
| 822 |
+
self.__rewind_idat = self.__prepare_idat
|
| 823 |
+
self.__rewind = self._fp.tell()
|
| 824 |
+
if self.default_image:
|
| 825 |
+
# IDAT chunk contains default image and not first animation frame
|
| 826 |
+
self.n_frames += 1
|
| 827 |
+
self._seek(0)
|
| 828 |
+
self.is_animated = self.n_frames > 1
|
| 829 |
+
|
| 830 |
+
@property
|
| 831 |
+
def text(self) -> dict[str, str | iTXt]:
|
| 832 |
+
# experimental
|
| 833 |
+
if self._text is None:
|
| 834 |
+
# iTxt, tEXt and zTXt chunks may appear at the end of the file
|
| 835 |
+
# So load the file to ensure that they are read
|
| 836 |
+
if self.is_animated:
|
| 837 |
+
frame = self.__frame
|
| 838 |
+
# for APNG, seek to the final frame before loading
|
| 839 |
+
self.seek(self.n_frames - 1)
|
| 840 |
+
self.load()
|
| 841 |
+
if self.is_animated:
|
| 842 |
+
self.seek(frame)
|
| 843 |
+
assert self._text is not None
|
| 844 |
+
return self._text
|
| 845 |
+
|
| 846 |
+
def verify(self) -> None:
|
| 847 |
+
"""Verify PNG file"""
|
| 848 |
+
|
| 849 |
+
if self.fp is None:
|
| 850 |
+
msg = "verify must be called directly after open"
|
| 851 |
+
raise RuntimeError(msg)
|
| 852 |
+
|
| 853 |
+
# back up to beginning of IDAT block
|
| 854 |
+
self.fp.seek(self.tile[0][2] - 8)
|
| 855 |
+
|
| 856 |
+
assert self.png is not None
|
| 857 |
+
self.png.verify()
|
| 858 |
+
self.png.close()
|
| 859 |
+
|
| 860 |
+
super().verify()
|
| 861 |
+
|
| 862 |
+
def seek(self, frame: int) -> None:
|
| 863 |
+
if not self._seek_check(frame):
|
| 864 |
+
return
|
| 865 |
+
if frame < self.__frame:
|
| 866 |
+
self._seek(0, True)
|
| 867 |
+
|
| 868 |
+
last_frame = self.__frame
|
| 869 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 870 |
+
try:
|
| 871 |
+
self._seek(f)
|
| 872 |
+
except EOFError as e:
|
| 873 |
+
self.seek(last_frame)
|
| 874 |
+
msg = "no more images in APNG file"
|
| 875 |
+
raise EOFError(msg) from e
|
| 876 |
+
|
| 877 |
+
def _seek(self, frame: int, rewind: bool = False) -> None:
|
| 878 |
+
assert self.png is not None
|
| 879 |
+
if isinstance(self._fp, DeferredError):
|
| 880 |
+
raise self._fp.ex
|
| 881 |
+
|
| 882 |
+
self.dispose: _imaging.ImagingCore | None
|
| 883 |
+
dispose_extent = None
|
| 884 |
+
if frame == 0:
|
| 885 |
+
if rewind:
|
| 886 |
+
self._fp.seek(self.__rewind)
|
| 887 |
+
self.png.rewind()
|
| 888 |
+
self.__prepare_idat = self.__rewind_idat
|
| 889 |
+
self._im = None
|
| 890 |
+
self.info = self.png.im_info
|
| 891 |
+
self.tile = self.png.im_tile
|
| 892 |
+
self.fp = self._fp
|
| 893 |
+
self._prev_im = None
|
| 894 |
+
self.dispose = None
|
| 895 |
+
self.default_image = self.info.get("default_image", False)
|
| 896 |
+
self.dispose_op = self.info.get("disposal")
|
| 897 |
+
self.blend_op = self.info.get("blend")
|
| 898 |
+
dispose_extent = self.info.get("bbox")
|
| 899 |
+
self.__frame = 0
|
| 900 |
+
else:
|
| 901 |
+
if frame != self.__frame + 1:
|
| 902 |
+
msg = f"cannot seek to frame {frame}"
|
| 903 |
+
raise ValueError(msg)
|
| 904 |
+
|
| 905 |
+
# ensure previous frame was loaded
|
| 906 |
+
self.load()
|
| 907 |
+
|
| 908 |
+
if self.dispose:
|
| 909 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
| 910 |
+
self._prev_im = self.im.copy()
|
| 911 |
+
|
| 912 |
+
self.fp = self._fp
|
| 913 |
+
|
| 914 |
+
# advance to the next frame
|
| 915 |
+
if self.__prepare_idat:
|
| 916 |
+
ImageFile._safe_read(self.fp, self.__prepare_idat)
|
| 917 |
+
self.__prepare_idat = 0
|
| 918 |
+
frame_start = False
|
| 919 |
+
while True:
|
| 920 |
+
self.fp.read(4) # CRC
|
| 921 |
+
|
| 922 |
+
try:
|
| 923 |
+
cid, pos, length = self.png.read()
|
| 924 |
+
except (struct.error, SyntaxError):
|
| 925 |
+
break
|
| 926 |
+
|
| 927 |
+
if cid == b"IEND":
|
| 928 |
+
msg = "No more images in APNG file"
|
| 929 |
+
raise EOFError(msg)
|
| 930 |
+
if cid == b"fcTL":
|
| 931 |
+
if frame_start:
|
| 932 |
+
# there must be at least one fdAT chunk between fcTL chunks
|
| 933 |
+
msg = "APNG missing frame data"
|
| 934 |
+
raise SyntaxError(msg)
|
| 935 |
+
frame_start = True
|
| 936 |
+
|
| 937 |
+
try:
|
| 938 |
+
self.png.call(cid, pos, length)
|
| 939 |
+
except UnicodeDecodeError:
|
| 940 |
+
break
|
| 941 |
+
except EOFError:
|
| 942 |
+
if cid == b"fdAT":
|
| 943 |
+
length -= 4
|
| 944 |
+
if frame_start:
|
| 945 |
+
self.__prepare_idat = length
|
| 946 |
+
break
|
| 947 |
+
ImageFile._safe_read(self.fp, length)
|
| 948 |
+
except AttributeError:
|
| 949 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 950 |
+
ImageFile._safe_read(self.fp, length)
|
| 951 |
+
|
| 952 |
+
self.__frame = frame
|
| 953 |
+
self.tile = self.png.im_tile
|
| 954 |
+
self.dispose_op = self.info.get("disposal")
|
| 955 |
+
self.blend_op = self.info.get("blend")
|
| 956 |
+
dispose_extent = self.info.get("bbox")
|
| 957 |
+
|
| 958 |
+
if not self.tile:
|
| 959 |
+
msg = "image not found in APNG frame"
|
| 960 |
+
raise EOFError(msg)
|
| 961 |
+
if dispose_extent:
|
| 962 |
+
self.dispose_extent: tuple[float, float, float, float] = dispose_extent
|
| 963 |
+
|
| 964 |
+
# setup frame disposal (actual disposal done when needed in the next _seek())
|
| 965 |
+
if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
|
| 966 |
+
self.dispose_op = Disposal.OP_BACKGROUND
|
| 967 |
+
|
| 968 |
+
self.dispose = None
|
| 969 |
+
if self.dispose_op == Disposal.OP_PREVIOUS:
|
| 970 |
+
if self._prev_im:
|
| 971 |
+
self.dispose = self._prev_im.copy()
|
| 972 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 973 |
+
elif self.dispose_op == Disposal.OP_BACKGROUND:
|
| 974 |
+
self.dispose = Image.core.fill(self.mode, self.size)
|
| 975 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 976 |
+
|
| 977 |
+
def tell(self) -> int:
|
| 978 |
+
return self.__frame
|
| 979 |
+
|
| 980 |
+
def load_prepare(self) -> None:
|
| 981 |
+
"""internal: prepare to read PNG file"""
|
| 982 |
+
|
| 983 |
+
if self.info.get("interlace"):
|
| 984 |
+
self.decoderconfig = self.decoderconfig + (1,)
|
| 985 |
+
|
| 986 |
+
self.__idat = self.__prepare_idat # used by load_read()
|
| 987 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 988 |
+
|
| 989 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 990 |
+
"""internal: read more image data"""
|
| 991 |
+
|
| 992 |
+
assert self.png is not None
|
| 993 |
+
assert self.fp is not None
|
| 994 |
+
while self.__idat == 0:
|
| 995 |
+
# end of chunk, skip forward to next one
|
| 996 |
+
|
| 997 |
+
self.fp.read(4) # CRC
|
| 998 |
+
|
| 999 |
+
cid, pos, length = self.png.read()
|
| 1000 |
+
|
| 1001 |
+
if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
|
| 1002 |
+
self.png.push(cid, pos, length)
|
| 1003 |
+
return b""
|
| 1004 |
+
|
| 1005 |
+
if cid == b"fdAT":
|
| 1006 |
+
try:
|
| 1007 |
+
self.png.call(cid, pos, length)
|
| 1008 |
+
except EOFError:
|
| 1009 |
+
pass
|
| 1010 |
+
self.__idat = length - 4 # sequence_num has already been read
|
| 1011 |
+
else:
|
| 1012 |
+
self.__idat = length # empty chunks are allowed
|
| 1013 |
+
|
| 1014 |
+
# read more data from this chunk
|
| 1015 |
+
if read_bytes <= 0:
|
| 1016 |
+
read_bytes = self.__idat
|
| 1017 |
+
else:
|
| 1018 |
+
read_bytes = min(read_bytes, self.__idat)
|
| 1019 |
+
|
| 1020 |
+
self.__idat = self.__idat - read_bytes
|
| 1021 |
+
|
| 1022 |
+
return self.fp.read(read_bytes)
|
| 1023 |
+
|
| 1024 |
+
def load_end(self) -> None:
|
| 1025 |
+
"""internal: finished reading image data"""
|
| 1026 |
+
assert self.png is not None
|
| 1027 |
+
assert self.fp is not None
|
| 1028 |
+
if self.__idat != 0:
|
| 1029 |
+
self.fp.read(self.__idat)
|
| 1030 |
+
while True:
|
| 1031 |
+
self.fp.read(4) # CRC
|
| 1032 |
+
|
| 1033 |
+
try:
|
| 1034 |
+
cid, pos, length = self.png.read()
|
| 1035 |
+
except (struct.error, SyntaxError):
|
| 1036 |
+
break
|
| 1037 |
+
|
| 1038 |
+
if cid == b"IEND":
|
| 1039 |
+
break
|
| 1040 |
+
elif cid == b"fcTL" and self.is_animated:
|
| 1041 |
+
# start of the next frame, stop reading
|
| 1042 |
+
self.__prepare_idat = 0
|
| 1043 |
+
self.png.push(cid, pos, length)
|
| 1044 |
+
break
|
| 1045 |
+
|
| 1046 |
+
try:
|
| 1047 |
+
self.png.call(cid, pos, length)
|
| 1048 |
+
except UnicodeDecodeError:
|
| 1049 |
+
break
|
| 1050 |
+
except EOFError:
|
| 1051 |
+
if cid == b"fdAT":
|
| 1052 |
+
length -= 4
|
| 1053 |
+
try:
|
| 1054 |
+
ImageFile._safe_read(self.fp, length)
|
| 1055 |
+
except OSError as e:
|
| 1056 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 1057 |
+
break
|
| 1058 |
+
else:
|
| 1059 |
+
raise e
|
| 1060 |
+
except AttributeError:
|
| 1061 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 1062 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 1063 |
+
if cid[1:2].islower():
|
| 1064 |
+
self.private_chunks.append((cid, s, True))
|
| 1065 |
+
self._text = self.png.im_text
|
| 1066 |
+
if not self.is_animated:
|
| 1067 |
+
self.png.close()
|
| 1068 |
+
self.png = None
|
| 1069 |
+
else:
|
| 1070 |
+
if self._prev_im and self.blend_op == Blend.OP_OVER:
|
| 1071 |
+
updated = self._crop(self.im, self.dispose_extent)
|
| 1072 |
+
if self.im.mode == "RGB" and "transparency" in self.info:
|
| 1073 |
+
mask = updated.convert_transparent(
|
| 1074 |
+
"RGBA", self.info["transparency"]
|
| 1075 |
+
)
|
| 1076 |
+
else:
|
| 1077 |
+
if self.im.mode == "P" and "transparency" in self.info:
|
| 1078 |
+
t = self.info["transparency"]
|
| 1079 |
+
if isinstance(t, bytes):
|
| 1080 |
+
updated.putpalettealphas(t)
|
| 1081 |
+
elif isinstance(t, int):
|
| 1082 |
+
updated.putpalettealpha(t)
|
| 1083 |
+
mask = updated.convert("RGBA")
|
| 1084 |
+
self._prev_im.paste(updated, self.dispose_extent, mask)
|
| 1085 |
+
self.im = self._prev_im
|
| 1086 |
+
|
| 1087 |
+
def _getexif(self) -> dict[int, Any] | None:
|
| 1088 |
+
if "exif" not in self.info:
|
| 1089 |
+
self.load()
|
| 1090 |
+
if "exif" not in self.info and "Raw profile type exif" not in self.info:
|
| 1091 |
+
return None
|
| 1092 |
+
return self.getexif()._get_merged_dict()
|
| 1093 |
+
|
| 1094 |
+
def getexif(self) -> Image.Exif:
|
| 1095 |
+
if "exif" not in self.info:
|
| 1096 |
+
self.load()
|
| 1097 |
+
|
| 1098 |
+
return super().getexif()
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
# --------------------------------------------------------------------
|
| 1102 |
+
# PNG writer
|
| 1103 |
+
|
| 1104 |
+
_OUTMODES = {
|
| 1105 |
+
# supported PIL modes, and corresponding rawmode, bit depth and color type
|
| 1106 |
+
"1": ("1", b"\x01", b"\x00"),
|
| 1107 |
+
"L;1": ("L;1", b"\x01", b"\x00"),
|
| 1108 |
+
"L;2": ("L;2", b"\x02", b"\x00"),
|
| 1109 |
+
"L;4": ("L;4", b"\x04", b"\x00"),
|
| 1110 |
+
"L": ("L", b"\x08", b"\x00"),
|
| 1111 |
+
"LA": ("LA", b"\x08", b"\x04"),
|
| 1112 |
+
"I": ("I;16B", b"\x10", b"\x00"),
|
| 1113 |
+
"I;16": ("I;16B", b"\x10", b"\x00"),
|
| 1114 |
+
"I;16B": ("I;16B", b"\x10", b"\x00"),
|
| 1115 |
+
"P;1": ("P;1", b"\x01", b"\x03"),
|
| 1116 |
+
"P;2": ("P;2", b"\x02", b"\x03"),
|
| 1117 |
+
"P;4": ("P;4", b"\x04", b"\x03"),
|
| 1118 |
+
"P": ("P", b"\x08", b"\x03"),
|
| 1119 |
+
"RGB": ("RGB", b"\x08", b"\x02"),
|
| 1120 |
+
"RGBA": ("RGBA", b"\x08", b"\x06"),
|
| 1121 |
+
}
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
|
| 1125 |
+
"""Write a PNG chunk (including CRC field)"""
|
| 1126 |
+
|
| 1127 |
+
byte_data = b"".join(data)
|
| 1128 |
+
|
| 1129 |
+
fp.write(o32(len(byte_data)) + cid)
|
| 1130 |
+
fp.write(byte_data)
|
| 1131 |
+
crc = _crc32(byte_data, _crc32(cid))
|
| 1132 |
+
fp.write(o32(crc))
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
class _idat:
|
| 1136 |
+
# wrap output from the encoder in IDAT chunks
|
| 1137 |
+
|
| 1138 |
+
def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:
|
| 1139 |
+
self.fp = fp
|
| 1140 |
+
self.chunk = chunk
|
| 1141 |
+
|
| 1142 |
+
def write(self, data: bytes) -> None:
|
| 1143 |
+
self.chunk(self.fp, b"IDAT", data)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
class _fdat:
|
| 1147 |
+
# wrap encoder output in fdAT chunks
|
| 1148 |
+
|
| 1149 |
+
def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:
|
| 1150 |
+
self.fp = fp
|
| 1151 |
+
self.chunk = chunk
|
| 1152 |
+
self.seq_num = seq_num
|
| 1153 |
+
|
| 1154 |
+
def write(self, data: bytes) -> None:
|
| 1155 |
+
self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
|
| 1156 |
+
self.seq_num += 1
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
def _apply_encoderinfo(im: Image.Image, encoderinfo: dict[str, Any]) -> None:
|
| 1160 |
+
im.encoderconfig = (
|
| 1161 |
+
encoderinfo.get("optimize", False),
|
| 1162 |
+
encoderinfo.get("compress_level", -1),
|
| 1163 |
+
encoderinfo.get("compress_type", -1),
|
| 1164 |
+
encoderinfo.get("dictionary", b""),
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
class _Frame(NamedTuple):
|
| 1169 |
+
im: Image.Image
|
| 1170 |
+
bbox: tuple[int, int, int, int] | None
|
| 1171 |
+
encoderinfo: dict[str, Any]
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def _write_multiple_frames(
|
| 1175 |
+
im: Image.Image,
|
| 1176 |
+
fp: IO[bytes],
|
| 1177 |
+
chunk: Callable[..., None],
|
| 1178 |
+
mode: str,
|
| 1179 |
+
rawmode: str,
|
| 1180 |
+
default_image: Image.Image | None,
|
| 1181 |
+
append_images: list[Image.Image],
|
| 1182 |
+
) -> Image.Image | None:
|
| 1183 |
+
duration = im.encoderinfo.get("duration")
|
| 1184 |
+
loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
|
| 1185 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
|
| 1186 |
+
blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
|
| 1187 |
+
|
| 1188 |
+
if default_image:
|
| 1189 |
+
chain = itertools.chain(append_images)
|
| 1190 |
+
else:
|
| 1191 |
+
chain = itertools.chain([im], append_images)
|
| 1192 |
+
|
| 1193 |
+
im_frames: list[_Frame] = []
|
| 1194 |
+
frame_count = 0
|
| 1195 |
+
for im_seq in chain:
|
| 1196 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1197 |
+
if im_frame.mode == mode:
|
| 1198 |
+
im_frame = im_frame.copy()
|
| 1199 |
+
else:
|
| 1200 |
+
im_frame = im_frame.convert(mode)
|
| 1201 |
+
encoderinfo = im.encoderinfo.copy()
|
| 1202 |
+
if isinstance(duration, (list, tuple)):
|
| 1203 |
+
encoderinfo["duration"] = duration[frame_count]
|
| 1204 |
+
elif duration is None and "duration" in im_frame.info:
|
| 1205 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
| 1206 |
+
if isinstance(disposal, (list, tuple)):
|
| 1207 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
| 1208 |
+
if isinstance(blend, (list, tuple)):
|
| 1209 |
+
encoderinfo["blend"] = blend[frame_count]
|
| 1210 |
+
frame_count += 1
|
| 1211 |
+
|
| 1212 |
+
if im_frames:
|
| 1213 |
+
previous = im_frames[-1]
|
| 1214 |
+
prev_disposal = previous.encoderinfo.get("disposal")
|
| 1215 |
+
prev_blend = previous.encoderinfo.get("blend")
|
| 1216 |
+
if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
|
| 1217 |
+
prev_disposal = Disposal.OP_BACKGROUND
|
| 1218 |
+
|
| 1219 |
+
if prev_disposal == Disposal.OP_BACKGROUND:
|
| 1220 |
+
base_im = previous.im.copy()
|
| 1221 |
+
dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
|
| 1222 |
+
bbox = previous.bbox
|
| 1223 |
+
if bbox:
|
| 1224 |
+
dispose = dispose.crop(bbox)
|
| 1225 |
+
else:
|
| 1226 |
+
bbox = (0, 0) + im.size
|
| 1227 |
+
base_im.paste(dispose, bbox)
|
| 1228 |
+
elif prev_disposal == Disposal.OP_PREVIOUS:
|
| 1229 |
+
base_im = im_frames[-2].im
|
| 1230 |
+
else:
|
| 1231 |
+
base_im = previous.im
|
| 1232 |
+
delta = ImageChops.subtract_modulo(
|
| 1233 |
+
im_frame.convert("RGBA"), base_im.convert("RGBA")
|
| 1234 |
+
)
|
| 1235 |
+
bbox = delta.getbbox(alpha_only=False)
|
| 1236 |
+
if (
|
| 1237 |
+
not bbox
|
| 1238 |
+
and prev_disposal == encoderinfo.get("disposal")
|
| 1239 |
+
and prev_blend == encoderinfo.get("blend")
|
| 1240 |
+
and "duration" in encoderinfo
|
| 1241 |
+
):
|
| 1242 |
+
previous.encoderinfo["duration"] += encoderinfo["duration"]
|
| 1243 |
+
continue
|
| 1244 |
+
else:
|
| 1245 |
+
bbox = None
|
| 1246 |
+
im_frames.append(_Frame(im_frame, bbox, encoderinfo))
|
| 1247 |
+
|
| 1248 |
+
if len(im_frames) == 1 and not default_image:
|
| 1249 |
+
return im_frames[0].im
|
| 1250 |
+
|
| 1251 |
+
# animation control
|
| 1252 |
+
chunk(
|
| 1253 |
+
fp,
|
| 1254 |
+
b"acTL",
|
| 1255 |
+
o32(len(im_frames)), # 0: num_frames
|
| 1256 |
+
o32(loop), # 4: num_plays
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
# default image IDAT (if it exists)
|
| 1260 |
+
if default_image:
|
| 1261 |
+
default_im = im if im.mode == mode else im.convert(mode)
|
| 1262 |
+
_apply_encoderinfo(default_im, im.encoderinfo)
|
| 1263 |
+
ImageFile._save(
|
| 1264 |
+
default_im,
|
| 1265 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1266 |
+
[ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
|
| 1267 |
+
)
|
| 1268 |
+
|
| 1269 |
+
seq_num = 0
|
| 1270 |
+
for frame, frame_data in enumerate(im_frames):
|
| 1271 |
+
im_frame = frame_data.im
|
| 1272 |
+
if not frame_data.bbox:
|
| 1273 |
+
bbox = (0, 0) + im_frame.size
|
| 1274 |
+
else:
|
| 1275 |
+
bbox = frame_data.bbox
|
| 1276 |
+
im_frame = im_frame.crop(bbox)
|
| 1277 |
+
size = im_frame.size
|
| 1278 |
+
encoderinfo = frame_data.encoderinfo
|
| 1279 |
+
frame_duration = encoderinfo.get("duration", 0)
|
| 1280 |
+
delay = Fraction(frame_duration / 1000).limit_denominator(65535)
|
| 1281 |
+
if delay.numerator > 65535:
|
| 1282 |
+
msg = "cannot write duration"
|
| 1283 |
+
raise ValueError(msg)
|
| 1284 |
+
frame_disposal = encoderinfo.get("disposal", disposal)
|
| 1285 |
+
frame_blend = encoderinfo.get("blend", blend)
|
| 1286 |
+
# frame control
|
| 1287 |
+
chunk(
|
| 1288 |
+
fp,
|
| 1289 |
+
b"fcTL",
|
| 1290 |
+
o32(seq_num), # sequence_number
|
| 1291 |
+
o32(size[0]), # width
|
| 1292 |
+
o32(size[1]), # height
|
| 1293 |
+
o32(bbox[0]), # x_offset
|
| 1294 |
+
o32(bbox[1]), # y_offset
|
| 1295 |
+
o16(delay.numerator), # delay_numerator
|
| 1296 |
+
o16(delay.denominator), # delay_denominator
|
| 1297 |
+
o8(frame_disposal), # dispose_op
|
| 1298 |
+
o8(frame_blend), # blend_op
|
| 1299 |
+
)
|
| 1300 |
+
seq_num += 1
|
| 1301 |
+
# frame data
|
| 1302 |
+
_apply_encoderinfo(im_frame, im.encoderinfo)
|
| 1303 |
+
if frame == 0 and not default_image:
|
| 1304 |
+
# first frame must be in IDAT chunks for backwards compatibility
|
| 1305 |
+
ImageFile._save(
|
| 1306 |
+
im_frame,
|
| 1307 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1308 |
+
[ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1309 |
+
)
|
| 1310 |
+
else:
|
| 1311 |
+
fdat_chunks = _fdat(fp, chunk, seq_num)
|
| 1312 |
+
ImageFile._save(
|
| 1313 |
+
im_frame,
|
| 1314 |
+
cast(IO[bytes], fdat_chunks),
|
| 1315 |
+
[ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1316 |
+
)
|
| 1317 |
+
seq_num = fdat_chunks.seq_num
|
| 1318 |
+
return None
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 1322 |
+
_save(im, fp, filename, save_all=True)
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
def _save(
|
| 1326 |
+
im: Image.Image,
|
| 1327 |
+
fp: IO[bytes],
|
| 1328 |
+
filename: str | bytes,
|
| 1329 |
+
chunk: Callable[..., None] = putchunk,
|
| 1330 |
+
save_all: bool = False,
|
| 1331 |
+
) -> None:
|
| 1332 |
+
# save an image to disk (called by the save method)
|
| 1333 |
+
|
| 1334 |
+
if save_all:
|
| 1335 |
+
default_image = im.encoderinfo.get(
|
| 1336 |
+
"default_image", im.info.get("default_image")
|
| 1337 |
+
)
|
| 1338 |
+
modes = set()
|
| 1339 |
+
sizes = set()
|
| 1340 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 1341 |
+
for im_seq in itertools.chain([im], append_images):
|
| 1342 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1343 |
+
modes.add(im_frame.mode)
|
| 1344 |
+
sizes.add(im_frame.size)
|
| 1345 |
+
for mode in ("RGBA", "RGB", "P"):
|
| 1346 |
+
if mode in modes:
|
| 1347 |
+
break
|
| 1348 |
+
else:
|
| 1349 |
+
mode = modes.pop()
|
| 1350 |
+
size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
|
| 1351 |
+
else:
|
| 1352 |
+
size = im.size
|
| 1353 |
+
mode = im.mode
|
| 1354 |
+
|
| 1355 |
+
outmode = mode
|
| 1356 |
+
if mode == "P":
|
| 1357 |
+
#
|
| 1358 |
+
# attempt to minimize storage requirements for palette images
|
| 1359 |
+
if "bits" in im.encoderinfo:
|
| 1360 |
+
# number of bits specified by user
|
| 1361 |
+
colors = min(1 << im.encoderinfo["bits"], 256)
|
| 1362 |
+
else:
|
| 1363 |
+
# check palette contents
|
| 1364 |
+
if im.palette:
|
| 1365 |
+
colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
|
| 1366 |
+
else:
|
| 1367 |
+
colors = 256
|
| 1368 |
+
|
| 1369 |
+
if colors <= 16:
|
| 1370 |
+
if colors <= 2:
|
| 1371 |
+
bits = 1
|
| 1372 |
+
elif colors <= 4:
|
| 1373 |
+
bits = 2
|
| 1374 |
+
else:
|
| 1375 |
+
bits = 4
|
| 1376 |
+
outmode += f";{bits}"
|
| 1377 |
+
|
| 1378 |
+
# get the corresponding PNG mode
|
| 1379 |
+
try:
|
| 1380 |
+
rawmode, bit_depth, color_type = _OUTMODES[outmode]
|
| 1381 |
+
except KeyError as e:
|
| 1382 |
+
msg = f"cannot write mode {mode} as PNG"
|
| 1383 |
+
raise OSError(msg) from e
|
| 1384 |
+
if outmode == "I":
|
| 1385 |
+
deprecate("Saving I mode images as PNG", 13, stacklevel=4)
|
| 1386 |
+
|
| 1387 |
+
#
|
| 1388 |
+
# write minimal PNG file
|
| 1389 |
+
|
| 1390 |
+
fp.write(_MAGIC)
|
| 1391 |
+
|
| 1392 |
+
chunk(
|
| 1393 |
+
fp,
|
| 1394 |
+
b"IHDR",
|
| 1395 |
+
o32(size[0]), # 0: size
|
| 1396 |
+
o32(size[1]),
|
| 1397 |
+
bit_depth,
|
| 1398 |
+
color_type,
|
| 1399 |
+
b"\0", # 10: compression
|
| 1400 |
+
b"\0", # 11: filter category
|
| 1401 |
+
b"\0", # 12: interlace flag
|
| 1402 |
+
)
|
| 1403 |
+
|
| 1404 |
+
chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
|
| 1405 |
+
|
| 1406 |
+
icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1407 |
+
if icc:
|
| 1408 |
+
# ICC profile
|
| 1409 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 1410 |
+
# Profile name 1-79 bytes (character string)
|
| 1411 |
+
# Null separator 1 byte (null character)
|
| 1412 |
+
# Compression method 1 byte (0)
|
| 1413 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 1414 |
+
name = b"ICC Profile"
|
| 1415 |
+
data = name + b"\0\0" + zlib.compress(icc)
|
| 1416 |
+
chunk(fp, b"iCCP", data)
|
| 1417 |
+
|
| 1418 |
+
# You must either have sRGB or iCCP.
|
| 1419 |
+
# Disallow sRGB chunks when an iCCP-chunk has been emitted.
|
| 1420 |
+
chunks.remove(b"sRGB")
|
| 1421 |
+
|
| 1422 |
+
info = im.encoderinfo.get("pnginfo")
|
| 1423 |
+
if info:
|
| 1424 |
+
chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
|
| 1425 |
+
for info_chunk in info.chunks:
|
| 1426 |
+
cid, data = info_chunk[:2]
|
| 1427 |
+
if cid in chunks:
|
| 1428 |
+
chunks.remove(cid)
|
| 1429 |
+
chunk(fp, cid, data)
|
| 1430 |
+
elif cid in chunks_multiple_allowed:
|
| 1431 |
+
chunk(fp, cid, data)
|
| 1432 |
+
elif cid[1:2].islower():
|
| 1433 |
+
# Private chunk
|
| 1434 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1435 |
+
if not after_idat:
|
| 1436 |
+
chunk(fp, cid, data)
|
| 1437 |
+
|
| 1438 |
+
if im.mode == "P":
|
| 1439 |
+
palette_byte_number = colors * 3
|
| 1440 |
+
palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
|
| 1441 |
+
while len(palette_bytes) < palette_byte_number:
|
| 1442 |
+
palette_bytes += b"\0"
|
| 1443 |
+
chunk(fp, b"PLTE", palette_bytes)
|
| 1444 |
+
|
| 1445 |
+
transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
|
| 1446 |
+
|
| 1447 |
+
if transparency or transparency == 0:
|
| 1448 |
+
if im.mode == "P":
|
| 1449 |
+
# limit to actual palette size
|
| 1450 |
+
alpha_bytes = colors
|
| 1451 |
+
if isinstance(transparency, bytes):
|
| 1452 |
+
chunk(fp, b"tRNS", transparency[:alpha_bytes])
|
| 1453 |
+
else:
|
| 1454 |
+
transparency = max(0, min(255, transparency))
|
| 1455 |
+
alpha = b"\xff" * transparency + b"\0"
|
| 1456 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1457 |
+
elif im.mode in ("1", "L", "I", "I;16"):
|
| 1458 |
+
transparency = max(0, min(65535, transparency))
|
| 1459 |
+
chunk(fp, b"tRNS", o16(transparency))
|
| 1460 |
+
elif im.mode == "RGB":
|
| 1461 |
+
red, green, blue = transparency
|
| 1462 |
+
chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
|
| 1463 |
+
else:
|
| 1464 |
+
if "transparency" in im.encoderinfo:
|
| 1465 |
+
# don't bother with transparency if it's an RGBA
|
| 1466 |
+
# and it's in the info dict. It's probably just stale.
|
| 1467 |
+
msg = "cannot use transparency for this mode"
|
| 1468 |
+
raise OSError(msg)
|
| 1469 |
+
else:
|
| 1470 |
+
if im.mode == "P" and im.im.getpalettemode() == "RGBA":
|
| 1471 |
+
alpha = im.im.getpalette("RGBA", "A")
|
| 1472 |
+
alpha_bytes = colors
|
| 1473 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1474 |
+
|
| 1475 |
+
dpi = im.encoderinfo.get("dpi")
|
| 1476 |
+
if dpi:
|
| 1477 |
+
chunk(
|
| 1478 |
+
fp,
|
| 1479 |
+
b"pHYs",
|
| 1480 |
+
o32(int(dpi[0] / 0.0254 + 0.5)),
|
| 1481 |
+
o32(int(dpi[1] / 0.0254 + 0.5)),
|
| 1482 |
+
b"\x01",
|
| 1483 |
+
)
|
| 1484 |
+
|
| 1485 |
+
if info:
|
| 1486 |
+
chunks = [b"bKGD", b"hIST"]
|
| 1487 |
+
for info_chunk in info.chunks:
|
| 1488 |
+
cid, data = info_chunk[:2]
|
| 1489 |
+
if cid in chunks:
|
| 1490 |
+
chunks.remove(cid)
|
| 1491 |
+
chunk(fp, cid, data)
|
| 1492 |
+
|
| 1493 |
+
exif = im.encoderinfo.get("exif")
|
| 1494 |
+
if exif:
|
| 1495 |
+
if isinstance(exif, Image.Exif):
|
| 1496 |
+
exif = exif.tobytes(8)
|
| 1497 |
+
if exif.startswith(b"Exif\x00\x00"):
|
| 1498 |
+
exif = exif[6:]
|
| 1499 |
+
chunk(fp, b"eXIf", exif)
|
| 1500 |
+
|
| 1501 |
+
single_im: Image.Image | None = im
|
| 1502 |
+
if save_all:
|
| 1503 |
+
single_im = _write_multiple_frames(
|
| 1504 |
+
im, fp, chunk, mode, rawmode, default_image, append_images
|
| 1505 |
+
)
|
| 1506 |
+
if single_im:
|
| 1507 |
+
_apply_encoderinfo(single_im, im.encoderinfo)
|
| 1508 |
+
ImageFile._save(
|
| 1509 |
+
single_im,
|
| 1510 |
+
cast(IO[bytes], _idat(fp, chunk)),
|
| 1511 |
+
[ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],
|
| 1512 |
+
)
|
| 1513 |
+
|
| 1514 |
+
if info:
|
| 1515 |
+
for info_chunk in info.chunks:
|
| 1516 |
+
cid, data = info_chunk[:2]
|
| 1517 |
+
if cid[1:2].islower():
|
| 1518 |
+
# Private chunk
|
| 1519 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1520 |
+
if after_idat:
|
| 1521 |
+
chunk(fp, cid, data)
|
| 1522 |
+
|
| 1523 |
+
chunk(fp, b"IEND", b"")
|
| 1524 |
+
|
| 1525 |
+
if hasattr(fp, "flush"):
|
| 1526 |
+
fp.flush()
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
# --------------------------------------------------------------------
|
| 1530 |
+
# PNG chunk converter
|
| 1531 |
+
|
| 1532 |
+
|
| 1533 |
+
def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:
|
| 1534 |
+
"""Return a list of PNG chunks representing this image."""
|
| 1535 |
+
from io import BytesIO
|
| 1536 |
+
|
| 1537 |
+
chunks = []
|
| 1538 |
+
|
| 1539 |
+
def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
|
| 1540 |
+
byte_data = b"".join(data)
|
| 1541 |
+
crc = o32(_crc32(byte_data, _crc32(cid)))
|
| 1542 |
+
chunks.append((cid, byte_data, crc))
|
| 1543 |
+
|
| 1544 |
+
fp = BytesIO()
|
| 1545 |
+
|
| 1546 |
+
try:
|
| 1547 |
+
im.encoderinfo = params
|
| 1548 |
+
_save(im, fp, "", append)
|
| 1549 |
+
finally:
|
| 1550 |
+
del im.encoderinfo
|
| 1551 |
+
|
| 1552 |
+
return chunks
|
| 1553 |
+
|
| 1554 |
+
|
| 1555 |
+
# --------------------------------------------------------------------
|
| 1556 |
+
# Registry
|
| 1557 |
+
|
| 1558 |
+
Image.register_open(PngImageFile.format, PngImageFile, _accept)
|
| 1559 |
+
Image.register_save(PngImageFile.format, _save)
|
| 1560 |
+
Image.register_save_all(PngImageFile.format, _save_all)
|
| 1561 |
+
|
| 1562 |
+
Image.register_extensions(PngImageFile.format, [".png", ".apng"])
|
| 1563 |
+
|
| 1564 |
+
Image.register_mime(PngImageFile.format, "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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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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Adobe PSD 2.5/3.0 file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-09-01 fl Created
|
| 9 |
+
# 1997-01-03 fl Read most PSD images
|
| 10 |
+
# 1997-01-18 fl Fixed P and CMYK support
|
| 11 |
+
# 2001-10-21 fl Added seek/tell support (for layers)
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2001 by Secret Labs AB.
|
| 14 |
+
# Copyright (c) 1995-2001 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import io
|
| 21 |
+
from functools import cached_property
|
| 22 |
+
from typing import IO
|
| 23 |
+
|
| 24 |
+
from . import Image, ImageFile, ImagePalette
|
| 25 |
+
from ._binary import i8
|
| 26 |
+
from ._binary import i16be as i16
|
| 27 |
+
from ._binary import i32be as i32
|
| 28 |
+
from ._binary import si16be as si16
|
| 29 |
+
from ._binary import si32be as si32
|
| 30 |
+
from ._util import DeferredError
|
| 31 |
+
|
| 32 |
+
MODES = {
|
| 33 |
+
# (photoshop mode, bits) -> (pil mode, required channels)
|
| 34 |
+
(0, 1): ("1", 1),
|
| 35 |
+
(0, 8): ("L", 1),
|
| 36 |
+
(1, 8): ("L", 1),
|
| 37 |
+
(2, 8): ("P", 1),
|
| 38 |
+
(3, 8): ("RGB", 3),
|
| 39 |
+
(4, 8): ("CMYK", 4),
|
| 40 |
+
(7, 8): ("L", 1), # FIXME: multilayer
|
| 41 |
+
(8, 8): ("L", 1), # duotone
|
| 42 |
+
(9, 8): ("LAB", 3),
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# --------------------------------------------------------------------.
|
| 47 |
+
# read PSD images
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _accept(prefix: bytes) -> bool:
|
| 51 |
+
return prefix.startswith(b"8BPS")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
##
|
| 55 |
+
# Image plugin for Photoshop images.
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PsdImageFile(ImageFile.ImageFile):
|
| 59 |
+
format = "PSD"
|
| 60 |
+
format_description = "Adobe Photoshop"
|
| 61 |
+
_close_exclusive_fp_after_loading = False
|
| 62 |
+
|
| 63 |
+
def _open(self) -> None:
|
| 64 |
+
assert self.fp is not None
|
| 65 |
+
read = self.fp.read
|
| 66 |
+
|
| 67 |
+
#
|
| 68 |
+
# header
|
| 69 |
+
|
| 70 |
+
s = read(26)
|
| 71 |
+
if not _accept(s) or i16(s, 4) != 1:
|
| 72 |
+
msg = "not a PSD file"
|
| 73 |
+
raise SyntaxError(msg)
|
| 74 |
+
|
| 75 |
+
psd_bits = i16(s, 22)
|
| 76 |
+
psd_channels = i16(s, 12)
|
| 77 |
+
psd_mode = i16(s, 24)
|
| 78 |
+
|
| 79 |
+
mode, channels = MODES[(psd_mode, psd_bits)]
|
| 80 |
+
|
| 81 |
+
if channels > psd_channels:
|
| 82 |
+
msg = "not enough channels"
|
| 83 |
+
raise OSError(msg)
|
| 84 |
+
if mode == "RGB" and psd_channels == 4:
|
| 85 |
+
mode = "RGBA"
|
| 86 |
+
channels = 4
|
| 87 |
+
|
| 88 |
+
self._mode = mode
|
| 89 |
+
self._size = i32(s, 18), i32(s, 14)
|
| 90 |
+
|
| 91 |
+
#
|
| 92 |
+
# color mode data
|
| 93 |
+
|
| 94 |
+
size = i32(read(4))
|
| 95 |
+
if size:
|
| 96 |
+
data = read(size)
|
| 97 |
+
if mode == "P" and size == 768:
|
| 98 |
+
self.palette = ImagePalette.raw("RGB;L", data)
|
| 99 |
+
|
| 100 |
+
#
|
| 101 |
+
# image resources
|
| 102 |
+
|
| 103 |
+
self.resources = []
|
| 104 |
+
|
| 105 |
+
size = i32(read(4))
|
| 106 |
+
if size:
|
| 107 |
+
# load resources
|
| 108 |
+
end = self.fp.tell() + size
|
| 109 |
+
while self.fp.tell() < end:
|
| 110 |
+
read(4) # signature
|
| 111 |
+
id = i16(read(2))
|
| 112 |
+
name = read(i8(read(1)))
|
| 113 |
+
if not (len(name) & 1):
|
| 114 |
+
read(1) # padding
|
| 115 |
+
data = read(i32(read(4)))
|
| 116 |
+
if len(data) & 1:
|
| 117 |
+
read(1) # padding
|
| 118 |
+
self.resources.append((id, name, data))
|
| 119 |
+
if id == 1039: # ICC profile
|
| 120 |
+
self.info["icc_profile"] = data
|
| 121 |
+
|
| 122 |
+
#
|
| 123 |
+
# layer and mask information
|
| 124 |
+
|
| 125 |
+
self._layers_position = None
|
| 126 |
+
|
| 127 |
+
size = i32(read(4))
|
| 128 |
+
if size:
|
| 129 |
+
end = self.fp.tell() + size
|
| 130 |
+
size = i32(read(4))
|
| 131 |
+
if size:
|
| 132 |
+
self._layers_position = self.fp.tell()
|
| 133 |
+
self._layers_size = size
|
| 134 |
+
self.fp.seek(end)
|
| 135 |
+
self._n_frames: int | None = None
|
| 136 |
+
|
| 137 |
+
#
|
| 138 |
+
# image descriptor
|
| 139 |
+
|
| 140 |
+
self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)
|
| 141 |
+
|
| 142 |
+
# keep the file open
|
| 143 |
+
self._fp = self.fp
|
| 144 |
+
self.frame = 1
|
| 145 |
+
self._min_frame = 1
|
| 146 |
+
|
| 147 |
+
@cached_property
|
| 148 |
+
def layers(
|
| 149 |
+
self,
|
| 150 |
+
) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
|
| 151 |
+
layers = []
|
| 152 |
+
if self._layers_position is not None:
|
| 153 |
+
if isinstance(self._fp, DeferredError):
|
| 154 |
+
raise self._fp.ex
|
| 155 |
+
self._fp.seek(self._layers_position)
|
| 156 |
+
_layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size))
|
| 157 |
+
layers = _layerinfo(_layer_data, self._layers_size)
|
| 158 |
+
self._n_frames = len(layers)
|
| 159 |
+
return layers
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def n_frames(self) -> int:
|
| 163 |
+
if self._n_frames is None:
|
| 164 |
+
self._n_frames = len(self.layers)
|
| 165 |
+
return self._n_frames
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def is_animated(self) -> bool:
|
| 169 |
+
return len(self.layers) > 1
|
| 170 |
+
|
| 171 |
+
def seek(self, layer: int) -> None:
|
| 172 |
+
if not self._seek_check(layer):
|
| 173 |
+
return
|
| 174 |
+
if isinstance(self._fp, DeferredError):
|
| 175 |
+
raise self._fp.ex
|
| 176 |
+
|
| 177 |
+
# seek to given layer (1..max)
|
| 178 |
+
_, mode, _, tile = self.layers[layer - 1]
|
| 179 |
+
self._mode = mode
|
| 180 |
+
self.tile = tile
|
| 181 |
+
self.frame = layer
|
| 182 |
+
self.fp = self._fp
|
| 183 |
+
|
| 184 |
+
def tell(self) -> int:
|
| 185 |
+
# return layer number (0=image, 1..max=layers)
|
| 186 |
+
return self.frame
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _layerinfo(
|
| 190 |
+
fp: IO[bytes], ct_bytes: int
|
| 191 |
+
) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
|
| 192 |
+
# read layerinfo block
|
| 193 |
+
layers = []
|
| 194 |
+
|
| 195 |
+
def read(size: int) -> bytes:
|
| 196 |
+
return ImageFile._safe_read(fp, size)
|
| 197 |
+
|
| 198 |
+
ct = si16(read(2))
|
| 199 |
+
|
| 200 |
+
# sanity check
|
| 201 |
+
if ct_bytes < (abs(ct) * 20):
|
| 202 |
+
msg = "Layer block too short for number of layers requested"
|
| 203 |
+
raise SyntaxError(msg)
|
| 204 |
+
|
| 205 |
+
for _ in range(abs(ct)):
|
| 206 |
+
# bounding box
|
| 207 |
+
y0 = si32(read(4))
|
| 208 |
+
x0 = si32(read(4))
|
| 209 |
+
y1 = si32(read(4))
|
| 210 |
+
x1 = si32(read(4))
|
| 211 |
+
|
| 212 |
+
# image info
|
| 213 |
+
bands = []
|
| 214 |
+
ct_types = i16(read(2))
|
| 215 |
+
if ct_types > 4:
|
| 216 |
+
fp.seek(ct_types * 6 + 12, io.SEEK_CUR)
|
| 217 |
+
size = i32(read(4))
|
| 218 |
+
fp.seek(size, io.SEEK_CUR)
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
for _ in range(ct_types):
|
| 222 |
+
type = i16(read(2))
|
| 223 |
+
|
| 224 |
+
if type == 65535:
|
| 225 |
+
b = "A"
|
| 226 |
+
else:
|
| 227 |
+
b = "RGBA"[type]
|
| 228 |
+
|
| 229 |
+
bands.append(b)
|
| 230 |
+
read(4) # size
|
| 231 |
+
|
| 232 |
+
# figure out the image mode
|
| 233 |
+
bands.sort()
|
| 234 |
+
if bands == ["R"]:
|
| 235 |
+
mode = "L"
|
| 236 |
+
elif bands == ["B", "G", "R"]:
|
| 237 |
+
mode = "RGB"
|
| 238 |
+
elif bands == ["A", "B", "G", "R"]:
|
| 239 |
+
mode = "RGBA"
|
| 240 |
+
else:
|
| 241 |
+
mode = "" # unknown
|
| 242 |
+
|
| 243 |
+
# skip over blend flags and extra information
|
| 244 |
+
read(12) # filler
|
| 245 |
+
name = ""
|
| 246 |
+
size = i32(read(4)) # length of the extra data field
|
| 247 |
+
if size:
|
| 248 |
+
data_end = fp.tell() + size
|
| 249 |
+
|
| 250 |
+
length = i32(read(4))
|
| 251 |
+
if length:
|
| 252 |
+
fp.seek(length - 16, io.SEEK_CUR)
|
| 253 |
+
|
| 254 |
+
length = i32(read(4))
|
| 255 |
+
if length:
|
| 256 |
+
fp.seek(length, io.SEEK_CUR)
|
| 257 |
+
|
| 258 |
+
length = i8(read(1))
|
| 259 |
+
if length:
|
| 260 |
+
# Don't know the proper encoding,
|
| 261 |
+
# Latin-1 should be a good guess
|
| 262 |
+
name = read(length).decode("latin-1", "replace")
|
| 263 |
+
|
| 264 |
+
fp.seek(data_end)
|
| 265 |
+
layers.append((name, mode, (x0, y0, x1, y1)))
|
| 266 |
+
|
| 267 |
+
# get tiles
|
| 268 |
+
layerinfo = []
|
| 269 |
+
for i, (name, mode, bbox) in enumerate(layers):
|
| 270 |
+
tile = []
|
| 271 |
+
for m in mode:
|
| 272 |
+
t = _maketile(fp, m, bbox, 1)
|
| 273 |
+
if t:
|
| 274 |
+
tile.extend(t)
|
| 275 |
+
layerinfo.append((name, mode, bbox, tile))
|
| 276 |
+
|
| 277 |
+
return layerinfo
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _maketile(
|
| 281 |
+
file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int
|
| 282 |
+
) -> list[ImageFile._Tile]:
|
| 283 |
+
tiles = []
|
| 284 |
+
read = file.read
|
| 285 |
+
|
| 286 |
+
compression = i16(read(2))
|
| 287 |
+
|
| 288 |
+
xsize = bbox[2] - bbox[0]
|
| 289 |
+
ysize = bbox[3] - bbox[1]
|
| 290 |
+
|
| 291 |
+
offset = file.tell()
|
| 292 |
+
|
| 293 |
+
if compression == 0:
|
| 294 |
+
#
|
| 295 |
+
# raw compression
|
| 296 |
+
for channel in range(channels):
|
| 297 |
+
layer = mode[channel]
|
| 298 |
+
if mode == "CMYK":
|
| 299 |
+
layer += ";I"
|
| 300 |
+
tiles.append(ImageFile._Tile("raw", bbox, offset, layer))
|
| 301 |
+
offset = offset + xsize * ysize
|
| 302 |
+
|
| 303 |
+
elif compression == 1:
|
| 304 |
+
#
|
| 305 |
+
# packbits compression
|
| 306 |
+
i = 0
|
| 307 |
+
bytecount = read(channels * ysize * 2)
|
| 308 |
+
offset = file.tell()
|
| 309 |
+
for channel in range(channels):
|
| 310 |
+
layer = mode[channel]
|
| 311 |
+
if mode == "CMYK":
|
| 312 |
+
layer += ";I"
|
| 313 |
+
tiles.append(ImageFile._Tile("packbits", bbox, offset, layer))
|
| 314 |
+
for y in range(ysize):
|
| 315 |
+
offset = offset + i16(bytecount, i)
|
| 316 |
+
i += 2
|
| 317 |
+
|
| 318 |
+
file.seek(offset)
|
| 319 |
+
|
| 320 |
+
if offset & 1:
|
| 321 |
+
read(1) # padding
|
| 322 |
+
|
| 323 |
+
return tiles
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# --------------------------------------------------------------------
|
| 327 |
+
# registry
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
Image.register_open(PsdImageFile.format, PsdImageFile, _accept)
|
| 331 |
+
|
| 332 |
+
Image.register_extension(PsdImageFile.format, ".psd")
|
| 333 |
+
|
| 334 |
+
Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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7 |
+
#
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from typing import IO
|
| 12 |
+
|
| 13 |
+
from . import Image, ImageFile
|
| 14 |
+
from ._binary import i32be as i32
|
| 15 |
+
from ._binary import o8
|
| 16 |
+
from ._binary import o32be as o32
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _accept(prefix: bytes) -> bool:
|
| 20 |
+
return prefix.startswith(b"qoif")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class QoiImageFile(ImageFile.ImageFile):
|
| 24 |
+
format = "QOI"
|
| 25 |
+
format_description = "Quite OK Image"
|
| 26 |
+
|
| 27 |
+
def _open(self) -> None:
|
| 28 |
+
assert self.fp is not None
|
| 29 |
+
if not _accept(self.fp.read(4)):
|
| 30 |
+
msg = "not a QOI file"
|
| 31 |
+
raise SyntaxError(msg)
|
| 32 |
+
|
| 33 |
+
self._size = i32(self.fp.read(4)), i32(self.fp.read(4))
|
| 34 |
+
|
| 35 |
+
channels = self.fp.read(1)[0]
|
| 36 |
+
self._mode = "RGB" if channels == 3 else "RGBA"
|
| 37 |
+
|
| 38 |
+
self.fp.seek(1, os.SEEK_CUR) # colorspace
|
| 39 |
+
self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell())]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class QoiDecoder(ImageFile.PyDecoder):
|
| 43 |
+
_pulls_fd = True
|
| 44 |
+
_previous_pixel: bytes | bytearray | None = None
|
| 45 |
+
_previously_seen_pixels: dict[int, bytes | bytearray] = {}
|
| 46 |
+
|
| 47 |
+
def _add_to_previous_pixels(self, value: bytes | bytearray) -> None:
|
| 48 |
+
self._previous_pixel = value
|
| 49 |
+
|
| 50 |
+
r, g, b, a = value
|
| 51 |
+
hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64
|
| 52 |
+
self._previously_seen_pixels[hash_value] = value
|
| 53 |
+
|
| 54 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 55 |
+
assert self.fd is not None
|
| 56 |
+
|
| 57 |
+
self._previously_seen_pixels = {}
|
| 58 |
+
self._previous_pixel = bytearray((0, 0, 0, 255))
|
| 59 |
+
|
| 60 |
+
data = bytearray()
|
| 61 |
+
bands = Image.getmodebands(self.mode)
|
| 62 |
+
dest_length = self.state.xsize * self.state.ysize * bands
|
| 63 |
+
while len(data) < dest_length:
|
| 64 |
+
byte = self.fd.read(1)[0]
|
| 65 |
+
value: bytes | bytearray
|
| 66 |
+
if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB
|
| 67 |
+
value = bytearray(self.fd.read(3)) + self._previous_pixel[3:]
|
| 68 |
+
elif byte == 0b11111111: # QOI_OP_RGBA
|
| 69 |
+
value = self.fd.read(4)
|
| 70 |
+
else:
|
| 71 |
+
op = byte >> 6
|
| 72 |
+
if op == 0: # QOI_OP_INDEX
|
| 73 |
+
op_index = byte & 0b00111111
|
| 74 |
+
value = self._previously_seen_pixels.get(
|
| 75 |
+
op_index, bytearray((0, 0, 0, 0))
|
| 76 |
+
)
|
| 77 |
+
elif op == 1 and self._previous_pixel: # QOI_OP_DIFF
|
| 78 |
+
value = bytearray(
|
| 79 |
+
(
|
| 80 |
+
(self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2)
|
| 81 |
+
% 256,
|
| 82 |
+
(self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2)
|
| 83 |
+
% 256,
|
| 84 |
+
(self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256,
|
| 85 |
+
self._previous_pixel[3],
|
| 86 |
+
)
|
| 87 |
+
)
|
| 88 |
+
elif op == 2 and self._previous_pixel: # QOI_OP_LUMA
|
| 89 |
+
second_byte = self.fd.read(1)[0]
|
| 90 |
+
diff_green = (byte & 0b00111111) - 32
|
| 91 |
+
diff_red = ((second_byte & 0b11110000) >> 4) - 8
|
| 92 |
+
diff_blue = (second_byte & 0b00001111) - 8
|
| 93 |
+
|
| 94 |
+
value = bytearray(
|
| 95 |
+
tuple(
|
| 96 |
+
(self._previous_pixel[i] + diff_green + diff) % 256
|
| 97 |
+
for i, diff in enumerate((diff_red, 0, diff_blue))
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
value += self._previous_pixel[3:]
|
| 101 |
+
elif op == 3 and self._previous_pixel: # QOI_OP_RUN
|
| 102 |
+
run_length = (byte & 0b00111111) + 1
|
| 103 |
+
value = self._previous_pixel
|
| 104 |
+
if bands == 3:
|
| 105 |
+
value = value[:3]
|
| 106 |
+
data += value * run_length
|
| 107 |
+
continue
|
| 108 |
+
self._add_to_previous_pixels(value)
|
| 109 |
+
|
| 110 |
+
if bands == 3:
|
| 111 |
+
value = value[:3]
|
| 112 |
+
data += value
|
| 113 |
+
self.set_as_raw(data)
|
| 114 |
+
return -1, 0
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 118 |
+
if im.mode == "RGB":
|
| 119 |
+
channels = 3
|
| 120 |
+
elif im.mode == "RGBA":
|
| 121 |
+
channels = 4
|
| 122 |
+
else:
|
| 123 |
+
msg = "Unsupported QOI image mode"
|
| 124 |
+
raise ValueError(msg)
|
| 125 |
+
|
| 126 |
+
colorspace = 0 if im.encoderinfo.get("colorspace") == "sRGB" else 1
|
| 127 |
+
|
| 128 |
+
fp.write(b"qoif")
|
| 129 |
+
fp.write(o32(im.size[0]))
|
| 130 |
+
fp.write(o32(im.size[1]))
|
| 131 |
+
fp.write(o8(channels))
|
| 132 |
+
fp.write(o8(colorspace))
|
| 133 |
+
|
| 134 |
+
ImageFile._save(im, fp, [ImageFile._Tile("qoi", (0, 0) + im.size)])
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class QoiEncoder(ImageFile.PyEncoder):
|
| 138 |
+
_pushes_fd = True
|
| 139 |
+
_previous_pixel: tuple[int, int, int, int] | None = None
|
| 140 |
+
_previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {}
|
| 141 |
+
_run = 0
|
| 142 |
+
|
| 143 |
+
def _write_run(self) -> bytes:
|
| 144 |
+
data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN
|
| 145 |
+
self._run = 0
|
| 146 |
+
return data
|
| 147 |
+
|
| 148 |
+
def _delta(self, left: int, right: int) -> int:
|
| 149 |
+
result = (left - right) & 255
|
| 150 |
+
if result >= 128:
|
| 151 |
+
result -= 256
|
| 152 |
+
return result
|
| 153 |
+
|
| 154 |
+
def encode(self, bufsize: int) -> tuple[int, int, bytes]:
|
| 155 |
+
assert self.im is not None
|
| 156 |
+
|
| 157 |
+
self._previously_seen_pixels = {0: (0, 0, 0, 0)}
|
| 158 |
+
self._previous_pixel = (0, 0, 0, 255)
|
| 159 |
+
|
| 160 |
+
data = bytearray()
|
| 161 |
+
w, h = self.im.size
|
| 162 |
+
bands = Image.getmodebands(self.mode)
|
| 163 |
+
|
| 164 |
+
for y in range(h):
|
| 165 |
+
for x in range(w):
|
| 166 |
+
pixel = self.im.getpixel((x, y))
|
| 167 |
+
if bands == 3:
|
| 168 |
+
pixel = (*pixel, 255)
|
| 169 |
+
|
| 170 |
+
if pixel == self._previous_pixel:
|
| 171 |
+
self._run += 1
|
| 172 |
+
if self._run == 62:
|
| 173 |
+
data += self._write_run()
|
| 174 |
+
else:
|
| 175 |
+
if self._run:
|
| 176 |
+
data += self._write_run()
|
| 177 |
+
|
| 178 |
+
r, g, b, a = pixel
|
| 179 |
+
hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64
|
| 180 |
+
if self._previously_seen_pixels.get(hash_value) == pixel:
|
| 181 |
+
data += o8(hash_value) # QOI_OP_INDEX
|
| 182 |
+
elif self._previous_pixel:
|
| 183 |
+
self._previously_seen_pixels[hash_value] = pixel
|
| 184 |
+
|
| 185 |
+
prev_r, prev_g, prev_b, prev_a = self._previous_pixel
|
| 186 |
+
if prev_a == a:
|
| 187 |
+
delta_r = self._delta(r, prev_r)
|
| 188 |
+
delta_g = self._delta(g, prev_g)
|
| 189 |
+
delta_b = self._delta(b, prev_b)
|
| 190 |
+
|
| 191 |
+
if (
|
| 192 |
+
-2 <= delta_r < 2
|
| 193 |
+
and -2 <= delta_g < 2
|
| 194 |
+
and -2 <= delta_b < 2
|
| 195 |
+
):
|
| 196 |
+
data += o8(
|
| 197 |
+
0b01000000
|
| 198 |
+
| (delta_r + 2) << 4
|
| 199 |
+
| (delta_g + 2) << 2
|
| 200 |
+
| (delta_b + 2)
|
| 201 |
+
) # QOI_OP_DIFF
|
| 202 |
+
else:
|
| 203 |
+
delta_gr = self._delta(delta_r, delta_g)
|
| 204 |
+
delta_gb = self._delta(delta_b, delta_g)
|
| 205 |
+
if (
|
| 206 |
+
-8 <= delta_gr < 8
|
| 207 |
+
and -32 <= delta_g < 32
|
| 208 |
+
and -8 <= delta_gb < 8
|
| 209 |
+
):
|
| 210 |
+
data += o8(
|
| 211 |
+
0b10000000 | (delta_g + 32)
|
| 212 |
+
) # QOI_OP_LUMA
|
| 213 |
+
data += o8((delta_gr + 8) << 4 | (delta_gb + 8))
|
| 214 |
+
else:
|
| 215 |
+
data += o8(0b11111110) # QOI_OP_RGB
|
| 216 |
+
data += bytes(pixel[:3])
|
| 217 |
+
else:
|
| 218 |
+
data += o8(0b11111111) # QOI_OP_RGBA
|
| 219 |
+
data += bytes(pixel)
|
| 220 |
+
|
| 221 |
+
self._previous_pixel = pixel
|
| 222 |
+
|
| 223 |
+
if self._run:
|
| 224 |
+
data += self._write_run()
|
| 225 |
+
data += bytes((0, 0, 0, 0, 0, 0, 0, 1)) # padding
|
| 226 |
+
|
| 227 |
+
return len(data), 0, data
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
Image.register_open(QoiImageFile.format, QoiImageFile, _accept)
|
| 231 |
+
Image.register_decoder("qoi", QoiDecoder)
|
| 232 |
+
Image.register_extension(QoiImageFile.format, ".qoi")
|
| 233 |
+
|
| 234 |
+
Image.register_save(QoiImageFile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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# SGI image file handling
|
| 6 |
+
#
|
| 7 |
+
# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
|
| 8 |
+
# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
|
| 9 |
+
#
|
| 10 |
+
#
|
| 11 |
+
# History:
|
| 12 |
+
# 2017-22-07 mb Add RLE decompression
|
| 13 |
+
# 2016-16-10 mb Add save method without compression
|
| 14 |
+
# 1995-09-10 fl Created
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) 2016 by Mickael Bonfill.
|
| 17 |
+
# Copyright (c) 2008 by Karsten Hiddemann.
|
| 18 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 19 |
+
# Copyright (c) 1995 by Fredrik Lundh.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
import struct
|
| 27 |
+
from typing import IO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageFile
|
| 30 |
+
from ._binary import i16be as i16
|
| 31 |
+
from ._binary import o8
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return len(prefix) >= 2 and i16(prefix) == 474
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
MODES = {
|
| 39 |
+
(1, 1, 1): "L",
|
| 40 |
+
(1, 2, 1): "L",
|
| 41 |
+
(2, 1, 1): "L;16B",
|
| 42 |
+
(2, 2, 1): "L;16B",
|
| 43 |
+
(1, 3, 3): "RGB",
|
| 44 |
+
(2, 3, 3): "RGB;16B",
|
| 45 |
+
(1, 3, 4): "RGBA",
|
| 46 |
+
(2, 3, 4): "RGBA;16B",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
##
|
| 51 |
+
# Image plugin for SGI images.
|
| 52 |
+
class SgiImageFile(ImageFile.ImageFile):
|
| 53 |
+
format = "SGI"
|
| 54 |
+
format_description = "SGI Image File Format"
|
| 55 |
+
|
| 56 |
+
def _open(self) -> None:
|
| 57 |
+
# HEAD
|
| 58 |
+
assert self.fp is not None
|
| 59 |
+
|
| 60 |
+
headlen = 512
|
| 61 |
+
s = self.fp.read(headlen)
|
| 62 |
+
|
| 63 |
+
if not _accept(s):
|
| 64 |
+
msg = "Not an SGI image file"
|
| 65 |
+
raise ValueError(msg)
|
| 66 |
+
|
| 67 |
+
# compression : verbatim or RLE
|
| 68 |
+
compression = s[2]
|
| 69 |
+
|
| 70 |
+
# bpc : 1 or 2 bytes (8bits or 16bits)
|
| 71 |
+
bpc = s[3]
|
| 72 |
+
|
| 73 |
+
# dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
|
| 74 |
+
dimension = i16(s, 4)
|
| 75 |
+
|
| 76 |
+
# xsize : width
|
| 77 |
+
xsize = i16(s, 6)
|
| 78 |
+
|
| 79 |
+
# ysize : height
|
| 80 |
+
ysize = i16(s, 8)
|
| 81 |
+
|
| 82 |
+
# zsize : channels count
|
| 83 |
+
zsize = i16(s, 10)
|
| 84 |
+
|
| 85 |
+
# determine mode from bits/zsize
|
| 86 |
+
try:
|
| 87 |
+
rawmode = MODES[(bpc, dimension, zsize)]
|
| 88 |
+
except KeyError:
|
| 89 |
+
msg = "Unsupported SGI image mode"
|
| 90 |
+
raise ValueError(msg)
|
| 91 |
+
|
| 92 |
+
self._size = xsize, ysize
|
| 93 |
+
self._mode = rawmode.split(";")[0]
|
| 94 |
+
if self.mode == "RGB":
|
| 95 |
+
self.custom_mimetype = "image/rgb"
|
| 96 |
+
|
| 97 |
+
# orientation -1 : scanlines begins at the bottom-left corner
|
| 98 |
+
orientation = -1
|
| 99 |
+
|
| 100 |
+
# decoder info
|
| 101 |
+
if compression == 0:
|
| 102 |
+
pagesize = xsize * ysize * bpc
|
| 103 |
+
if bpc == 2:
|
| 104 |
+
self.tile = [
|
| 105 |
+
ImageFile._Tile(
|
| 106 |
+
"SGI16",
|
| 107 |
+
(0, 0) + self.size,
|
| 108 |
+
headlen,
|
| 109 |
+
(self.mode, 0, orientation),
|
| 110 |
+
)
|
| 111 |
+
]
|
| 112 |
+
else:
|
| 113 |
+
self.tile = []
|
| 114 |
+
offset = headlen
|
| 115 |
+
for layer in self.mode:
|
| 116 |
+
self.tile.append(
|
| 117 |
+
ImageFile._Tile(
|
| 118 |
+
"raw", (0, 0) + self.size, offset, (layer, 0, orientation)
|
| 119 |
+
)
|
| 120 |
+
)
|
| 121 |
+
offset += pagesize
|
| 122 |
+
elif compression == 1:
|
| 123 |
+
self.tile = [
|
| 124 |
+
ImageFile._Tile(
|
| 125 |
+
"sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)
|
| 126 |
+
)
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 131 |
+
if im.mode not in {"RGB", "RGBA", "L"}:
|
| 132 |
+
msg = "Unsupported SGI image mode"
|
| 133 |
+
raise ValueError(msg)
|
| 134 |
+
|
| 135 |
+
# Get the keyword arguments
|
| 136 |
+
info = im.encoderinfo
|
| 137 |
+
|
| 138 |
+
# Byte-per-pixel precision, 1 = 8bits per pixel
|
| 139 |
+
bpc = info.get("bpc", 1)
|
| 140 |
+
|
| 141 |
+
if bpc not in (1, 2):
|
| 142 |
+
msg = "Unsupported number of bytes per pixel"
|
| 143 |
+
raise ValueError(msg)
|
| 144 |
+
|
| 145 |
+
# Flip the image, since the origin of SGI file is the bottom-left corner
|
| 146 |
+
orientation = -1
|
| 147 |
+
# Define the file as SGI File Format
|
| 148 |
+
magic_number = 474
|
| 149 |
+
# Run-Length Encoding Compression - Unsupported at this time
|
| 150 |
+
rle = 0
|
| 151 |
+
|
| 152 |
+
# X Dimension = width / Y Dimension = height
|
| 153 |
+
x, y = im.size
|
| 154 |
+
# Z Dimension: Number of channels
|
| 155 |
+
z = len(im.mode)
|
| 156 |
+
# Number of dimensions (x,y,z)
|
| 157 |
+
if im.mode == "L":
|
| 158 |
+
dimension = 1 if y == 1 else 2
|
| 159 |
+
else:
|
| 160 |
+
dimension = 3
|
| 161 |
+
|
| 162 |
+
# Minimum Byte value
|
| 163 |
+
pinmin = 0
|
| 164 |
+
# Maximum Byte value (255 = 8bits per pixel)
|
| 165 |
+
pinmax = 255
|
| 166 |
+
# Image name (79 characters max, truncated below in write)
|
| 167 |
+
img_name = os.path.splitext(os.path.basename(filename))[0]
|
| 168 |
+
if isinstance(img_name, str):
|
| 169 |
+
img_name = img_name.encode("ascii", "ignore")
|
| 170 |
+
# Standard representation of pixel in the file
|
| 171 |
+
colormap = 0
|
| 172 |
+
fp.write(struct.pack(">h", magic_number))
|
| 173 |
+
fp.write(o8(rle))
|
| 174 |
+
fp.write(o8(bpc))
|
| 175 |
+
fp.write(struct.pack(">H", dimension))
|
| 176 |
+
fp.write(struct.pack(">H", x))
|
| 177 |
+
fp.write(struct.pack(">H", y))
|
| 178 |
+
fp.write(struct.pack(">H", z))
|
| 179 |
+
fp.write(struct.pack(">l", pinmin))
|
| 180 |
+
fp.write(struct.pack(">l", pinmax))
|
| 181 |
+
fp.write(struct.pack("4s", b"")) # dummy
|
| 182 |
+
fp.write(struct.pack("79s", img_name)) # truncates to 79 chars
|
| 183 |
+
fp.write(struct.pack("s", b"")) # force null byte after img_name
|
| 184 |
+
fp.write(struct.pack(">l", colormap))
|
| 185 |
+
fp.write(struct.pack("404s", b"")) # dummy
|
| 186 |
+
|
| 187 |
+
rawmode = "L"
|
| 188 |
+
if bpc == 2:
|
| 189 |
+
rawmode = "L;16B"
|
| 190 |
+
|
| 191 |
+
for channel in im.split():
|
| 192 |
+
fp.write(channel.tobytes("raw", rawmode, 0, orientation))
|
| 193 |
+
|
| 194 |
+
if hasattr(fp, "flush"):
|
| 195 |
+
fp.flush()
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class SGI16Decoder(ImageFile.PyDecoder):
|
| 199 |
+
_pulls_fd = True
|
| 200 |
+
|
| 201 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 202 |
+
assert self.fd is not None
|
| 203 |
+
assert self.im is not None
|
| 204 |
+
|
| 205 |
+
rawmode, stride, orientation = self.args
|
| 206 |
+
pagesize = self.state.xsize * self.state.ysize
|
| 207 |
+
zsize = len(self.mode)
|
| 208 |
+
self.fd.seek(512)
|
| 209 |
+
|
| 210 |
+
for band in range(zsize):
|
| 211 |
+
channel = Image.new("L", (self.state.xsize, self.state.ysize))
|
| 212 |
+
channel.frombytes(
|
| 213 |
+
self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
|
| 214 |
+
)
|
| 215 |
+
self.im.putband(channel.im, band)
|
| 216 |
+
|
| 217 |
+
return -1, 0
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
#
|
| 221 |
+
# registry
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
Image.register_decoder("SGI16", SGI16Decoder)
|
| 225 |
+
Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
|
| 226 |
+
Image.register_save(SgiImageFile.format, _save)
|
| 227 |
+
Image.register_mime(SgiImageFile.format, "image/sgi")
|
| 228 |
+
|
| 229 |
+
Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
|
| 230 |
+
|
| 231 |
+
# End of file
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/SpiderImagePlugin.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
#
|
| 4 |
+
# SPIDER image file handling
|
| 5 |
+
#
|
| 6 |
+
# History:
|
| 7 |
+
# 2004-08-02 Created BB
|
| 8 |
+
# 2006-03-02 added save method
|
| 9 |
+
# 2006-03-13 added support for stack images
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
|
| 12 |
+
# Copyright (c) 2004 by William Baxter.
|
| 13 |
+
# Copyright (c) 2004 by Secret Labs AB.
|
| 14 |
+
# Copyright (c) 2004 by Fredrik Lundh.
|
| 15 |
+
#
|
| 16 |
+
|
| 17 |
+
##
|
| 18 |
+
# Image plugin for the Spider image format. This format is used
|
| 19 |
+
# by the SPIDER software, in processing image data from electron
|
| 20 |
+
# microscopy and tomography.
|
| 21 |
+
##
|
| 22 |
+
|
| 23 |
+
#
|
| 24 |
+
# SpiderImagePlugin.py
|
| 25 |
+
#
|
| 26 |
+
# The Spider image format is used by SPIDER software, in processing
|
| 27 |
+
# image data from electron microscopy and tomography.
|
| 28 |
+
#
|
| 29 |
+
# Spider home page:
|
| 30 |
+
# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
|
| 31 |
+
#
|
| 32 |
+
# Details about the Spider image format:
|
| 33 |
+
# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
|
| 34 |
+
#
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
|
| 37 |
+
import os
|
| 38 |
+
import struct
|
| 39 |
+
import sys
|
| 40 |
+
from typing import IO, Any, cast
|
| 41 |
+
|
| 42 |
+
from . import Image, ImageFile
|
| 43 |
+
from ._util import DeferredError
|
| 44 |
+
|
| 45 |
+
TYPE_CHECKING = False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def isInt(f: Any) -> int:
|
| 49 |
+
try:
|
| 50 |
+
i = int(f)
|
| 51 |
+
if f - i == 0:
|
| 52 |
+
return 1
|
| 53 |
+
else:
|
| 54 |
+
return 0
|
| 55 |
+
except (ValueError, OverflowError):
|
| 56 |
+
return 0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
iforms = [1, 3, -11, -12, -21, -22]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# There is no magic number to identify Spider files, so just check a
|
| 63 |
+
# series of header locations to see if they have reasonable values.
|
| 64 |
+
# Returns no. of bytes in the header, if it is a valid Spider header,
|
| 65 |
+
# otherwise returns 0
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def isSpiderHeader(t: tuple[float, ...]) -> int:
|
| 69 |
+
h = (99,) + t # add 1 value so can use spider header index start=1
|
| 70 |
+
# header values 1,2,5,12,13,22,23 should be integers
|
| 71 |
+
for i in [1, 2, 5, 12, 13, 22, 23]:
|
| 72 |
+
if not isInt(h[i]):
|
| 73 |
+
return 0
|
| 74 |
+
# check iform
|
| 75 |
+
iform = int(h[5])
|
| 76 |
+
if iform not in iforms:
|
| 77 |
+
return 0
|
| 78 |
+
# check other header values
|
| 79 |
+
labrec = int(h[13]) # no. records in file header
|
| 80 |
+
labbyt = int(h[22]) # total no. of bytes in header
|
| 81 |
+
lenbyt = int(h[23]) # record length in bytes
|
| 82 |
+
if labbyt != (labrec * lenbyt):
|
| 83 |
+
return 0
|
| 84 |
+
# looks like a valid header
|
| 85 |
+
return labbyt
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def isSpiderImage(filename: str) -> int:
|
| 89 |
+
with open(filename, "rb") as fp:
|
| 90 |
+
f = fp.read(92) # read 23 * 4 bytes
|
| 91 |
+
t = struct.unpack(">23f", f) # try big-endian first
|
| 92 |
+
hdrlen = isSpiderHeader(t)
|
| 93 |
+
if hdrlen == 0:
|
| 94 |
+
t = struct.unpack("<23f", f) # little-endian
|
| 95 |
+
hdrlen = isSpiderHeader(t)
|
| 96 |
+
return hdrlen
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class SpiderImageFile(ImageFile.ImageFile):
|
| 100 |
+
format = "SPIDER"
|
| 101 |
+
format_description = "Spider 2D image"
|
| 102 |
+
_close_exclusive_fp_after_loading = False
|
| 103 |
+
|
| 104 |
+
def _open(self) -> None:
|
| 105 |
+
# check header
|
| 106 |
+
n = 27 * 4 # read 27 float values
|
| 107 |
+
assert self.fp is not None
|
| 108 |
+
f = self.fp.read(n)
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
self.bigendian = 1
|
| 112 |
+
t = struct.unpack(">27f", f) # try big-endian first
|
| 113 |
+
hdrlen = isSpiderHeader(t)
|
| 114 |
+
if hdrlen == 0:
|
| 115 |
+
self.bigendian = 0
|
| 116 |
+
t = struct.unpack("<27f", f) # little-endian
|
| 117 |
+
hdrlen = isSpiderHeader(t)
|
| 118 |
+
if hdrlen == 0:
|
| 119 |
+
msg = "not a valid Spider file"
|
| 120 |
+
raise SyntaxError(msg)
|
| 121 |
+
except struct.error as e:
|
| 122 |
+
msg = "not a valid Spider file"
|
| 123 |
+
raise SyntaxError(msg) from e
|
| 124 |
+
|
| 125 |
+
h = (99,) + t # add 1 value : spider header index starts at 1
|
| 126 |
+
iform = int(h[5])
|
| 127 |
+
if iform != 1:
|
| 128 |
+
msg = "not a Spider 2D image"
|
| 129 |
+
raise SyntaxError(msg)
|
| 130 |
+
|
| 131 |
+
self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
|
| 132 |
+
self.istack = int(h[24])
|
| 133 |
+
self.imgnumber = int(h[27])
|
| 134 |
+
|
| 135 |
+
if self.istack == 0 and self.imgnumber == 0:
|
| 136 |
+
# stk=0, img=0: a regular 2D image
|
| 137 |
+
offset = hdrlen
|
| 138 |
+
self._nimages = 1
|
| 139 |
+
elif self.istack > 0 and self.imgnumber == 0:
|
| 140 |
+
# stk>0, img=0: Opening the stack for the first time
|
| 141 |
+
self.imgbytes = int(h[12]) * int(h[2]) * 4
|
| 142 |
+
self.hdrlen = hdrlen
|
| 143 |
+
self._nimages = int(h[26])
|
| 144 |
+
# Point to the first image in the stack
|
| 145 |
+
offset = hdrlen * 2
|
| 146 |
+
self.imgnumber = 1
|
| 147 |
+
elif self.istack == 0 and self.imgnumber > 0:
|
| 148 |
+
# stk=0, img>0: an image within the stack
|
| 149 |
+
offset = hdrlen + self.stkoffset
|
| 150 |
+
self.istack = 2 # So Image knows it's still a stack
|
| 151 |
+
else:
|
| 152 |
+
msg = "inconsistent stack header values"
|
| 153 |
+
raise SyntaxError(msg)
|
| 154 |
+
|
| 155 |
+
if self.bigendian:
|
| 156 |
+
self.rawmode = "F;32BF"
|
| 157 |
+
else:
|
| 158 |
+
self.rawmode = "F;32F"
|
| 159 |
+
self._mode = "F"
|
| 160 |
+
|
| 161 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)]
|
| 162 |
+
self._fp = self.fp # FIXME: hack
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def n_frames(self) -> int:
|
| 166 |
+
return self._nimages
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def is_animated(self) -> bool:
|
| 170 |
+
return self._nimages > 1
|
| 171 |
+
|
| 172 |
+
# 1st image index is zero (although SPIDER imgnumber starts at 1)
|
| 173 |
+
def tell(self) -> int:
|
| 174 |
+
if self.imgnumber < 1:
|
| 175 |
+
return 0
|
| 176 |
+
else:
|
| 177 |
+
return self.imgnumber - 1
|
| 178 |
+
|
| 179 |
+
def seek(self, frame: int) -> None:
|
| 180 |
+
if self.istack == 0:
|
| 181 |
+
msg = "attempt to seek in a non-stack file"
|
| 182 |
+
raise EOFError(msg)
|
| 183 |
+
if not self._seek_check(frame):
|
| 184 |
+
return
|
| 185 |
+
if isinstance(self._fp, DeferredError):
|
| 186 |
+
raise self._fp.ex
|
| 187 |
+
self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
|
| 188 |
+
self.fp = self._fp
|
| 189 |
+
self.fp.seek(self.stkoffset)
|
| 190 |
+
self._open()
|
| 191 |
+
|
| 192 |
+
# returns a byte image after rescaling to 0..255
|
| 193 |
+
def convert2byte(self, depth: int = 255) -> Image.Image:
|
| 194 |
+
extrema = self.getextrema()
|
| 195 |
+
assert isinstance(extrema[0], float)
|
| 196 |
+
minimum, maximum = cast(tuple[float, float], extrema)
|
| 197 |
+
m: float = 1
|
| 198 |
+
if maximum != minimum:
|
| 199 |
+
m = depth / (maximum - minimum)
|
| 200 |
+
b = -m * minimum
|
| 201 |
+
return self.point(lambda i: i * m + b).convert("L")
|
| 202 |
+
|
| 203 |
+
if TYPE_CHECKING:
|
| 204 |
+
from . import ImageTk
|
| 205 |
+
|
| 206 |
+
# returns a ImageTk.PhotoImage object, after rescaling to 0..255
|
| 207 |
+
def tkPhotoImage(self) -> ImageTk.PhotoImage:
|
| 208 |
+
from . import ImageTk
|
| 209 |
+
|
| 210 |
+
return ImageTk.PhotoImage(self.convert2byte(), palette=256)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# --------------------------------------------------------------------
|
| 214 |
+
# Image series
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# given a list of filenames, return a list of images
|
| 218 |
+
def loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None:
|
| 219 |
+
"""create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
|
| 220 |
+
if filelist is None or len(filelist) < 1:
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
byte_imgs = []
|
| 224 |
+
for img in filelist:
|
| 225 |
+
if not os.path.exists(img):
|
| 226 |
+
print(f"unable to find {img}")
|
| 227 |
+
continue
|
| 228 |
+
try:
|
| 229 |
+
with Image.open(img) as im:
|
| 230 |
+
assert isinstance(im, SpiderImageFile)
|
| 231 |
+
byte_im = im.convert2byte()
|
| 232 |
+
except Exception:
|
| 233 |
+
if not isSpiderImage(img):
|
| 234 |
+
print(f"{img} is not a Spider image file")
|
| 235 |
+
continue
|
| 236 |
+
byte_im.info["filename"] = img
|
| 237 |
+
byte_imgs.append(byte_im)
|
| 238 |
+
return byte_imgs
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
# --------------------------------------------------------------------
|
| 242 |
+
# For saving images in Spider format
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def makeSpiderHeader(im: Image.Image) -> list[bytes]:
|
| 246 |
+
nsam, nrow = im.size
|
| 247 |
+
lenbyt = nsam * 4 # There are labrec records in the header
|
| 248 |
+
labrec = int(1024 / lenbyt)
|
| 249 |
+
if 1024 % lenbyt != 0:
|
| 250 |
+
labrec += 1
|
| 251 |
+
labbyt = labrec * lenbyt
|
| 252 |
+
nvalues = int(labbyt / 4)
|
| 253 |
+
if nvalues < 23:
|
| 254 |
+
return []
|
| 255 |
+
|
| 256 |
+
hdr = [0.0] * nvalues
|
| 257 |
+
|
| 258 |
+
# NB these are Fortran indices
|
| 259 |
+
hdr[1] = 1.0 # nslice (=1 for an image)
|
| 260 |
+
hdr[2] = float(nrow) # number of rows per slice
|
| 261 |
+
hdr[3] = float(nrow) # number of records in the image
|
| 262 |
+
hdr[5] = 1.0 # iform for 2D image
|
| 263 |
+
hdr[12] = float(nsam) # number of pixels per line
|
| 264 |
+
hdr[13] = float(labrec) # number of records in file header
|
| 265 |
+
hdr[22] = float(labbyt) # total number of bytes in header
|
| 266 |
+
hdr[23] = float(lenbyt) # record length in bytes
|
| 267 |
+
|
| 268 |
+
# adjust for Fortran indexing
|
| 269 |
+
hdr = hdr[1:]
|
| 270 |
+
hdr.append(0.0)
|
| 271 |
+
# pack binary data into a string
|
| 272 |
+
return [struct.pack("f", v) for v in hdr]
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 276 |
+
if im.mode != "F":
|
| 277 |
+
im = im.convert("F")
|
| 278 |
+
|
| 279 |
+
hdr = makeSpiderHeader(im)
|
| 280 |
+
if len(hdr) < 256:
|
| 281 |
+
msg = "Error creating Spider header"
|
| 282 |
+
raise OSError(msg)
|
| 283 |
+
|
| 284 |
+
# write the SPIDER header
|
| 285 |
+
fp.writelines(hdr)
|
| 286 |
+
|
| 287 |
+
rawmode = "F;32NF" # 32-bit native floating point
|
| 288 |
+
ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)])
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 292 |
+
# get the filename extension and register it with Image
|
| 293 |
+
filename_ext = os.path.splitext(filename)[1]
|
| 294 |
+
ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
|
| 295 |
+
Image.register_extension(SpiderImageFile.format, ext)
|
| 296 |
+
_save(im, fp, filename)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# --------------------------------------------------------------------
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
Image.register_open(SpiderImageFile.format, SpiderImageFile)
|
| 303 |
+
Image.register_save(SpiderImageFile.format, _save_spider)
|
| 304 |
+
|
| 305 |
+
if __name__ == "__main__":
|
| 306 |
+
if len(sys.argv) < 2:
|
| 307 |
+
print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
|
| 308 |
+
sys.exit()
|
| 309 |
+
|
| 310 |
+
filename = sys.argv[1]
|
| 311 |
+
if not isSpiderImage(filename):
|
| 312 |
+
print("input image must be in Spider format")
|
| 313 |
+
sys.exit()
|
| 314 |
+
|
| 315 |
+
with Image.open(filename) as im:
|
| 316 |
+
print(f"image: {im}")
|
| 317 |
+
print(f"format: {im.format}")
|
| 318 |
+
print(f"size: {im.size}")
|
| 319 |
+
print(f"mode: {im.mode}")
|
| 320 |
+
print("max, min: ", end=" ")
|
| 321 |
+
print(im.getextrema())
|
| 322 |
+
|
| 323 |
+
if len(sys.argv) > 2:
|
| 324 |
+
outfile = sys.argv[2]
|
| 325 |
+
|
| 326 |
+
# perform some image operation
|
| 327 |
+
transposed_im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
| 328 |
+
print(
|
| 329 |
+
f"saving a flipped version of {os.path.basename(filename)} "
|
| 330 |
+
f"as {outfile} "
|
| 331 |
+
)
|
| 332 |
+
transposed_im.save(outfile, SpiderImageFile.format)
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/SunImagePlugin.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Sun image file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-09-10 fl Created
|
| 9 |
+
# 1996-05-28 fl Fixed 32-bit alignment
|
| 10 |
+
# 1998-12-29 fl Import ImagePalette module
|
| 11 |
+
# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault)
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 1995-1996 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from . import Image, ImageFile, ImagePalette
|
| 21 |
+
from ._binary import i32be as i32
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _accept(prefix: bytes) -> bool:
|
| 25 |
+
return len(prefix) >= 4 and i32(prefix) == 0x59A66A95
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
##
|
| 29 |
+
# Image plugin for Sun raster files.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SunImageFile(ImageFile.ImageFile):
|
| 33 |
+
format = "SUN"
|
| 34 |
+
format_description = "Sun Raster File"
|
| 35 |
+
|
| 36 |
+
def _open(self) -> None:
|
| 37 |
+
# The Sun Raster file header is 32 bytes in length
|
| 38 |
+
# and has the following format:
|
| 39 |
+
|
| 40 |
+
# typedef struct _SunRaster
|
| 41 |
+
# {
|
| 42 |
+
# DWORD MagicNumber; /* Magic (identification) number */
|
| 43 |
+
# DWORD Width; /* Width of image in pixels */
|
| 44 |
+
# DWORD Height; /* Height of image in pixels */
|
| 45 |
+
# DWORD Depth; /* Number of bits per pixel */
|
| 46 |
+
# DWORD Length; /* Size of image data in bytes */
|
| 47 |
+
# DWORD Type; /* Type of raster file */
|
| 48 |
+
# DWORD ColorMapType; /* Type of color map */
|
| 49 |
+
# DWORD ColorMapLength; /* Size of the color map in bytes */
|
| 50 |
+
# } SUNRASTER;
|
| 51 |
+
|
| 52 |
+
assert self.fp is not None
|
| 53 |
+
|
| 54 |
+
# HEAD
|
| 55 |
+
s = self.fp.read(32)
|
| 56 |
+
if not _accept(s):
|
| 57 |
+
msg = "not an SUN raster file"
|
| 58 |
+
raise SyntaxError(msg)
|
| 59 |
+
|
| 60 |
+
offset = 32
|
| 61 |
+
|
| 62 |
+
self._size = i32(s, 4), i32(s, 8)
|
| 63 |
+
|
| 64 |
+
depth = i32(s, 12)
|
| 65 |
+
# data_length = i32(s, 16) # unreliable, ignore.
|
| 66 |
+
file_type = i32(s, 20)
|
| 67 |
+
palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary
|
| 68 |
+
palette_length = i32(s, 28)
|
| 69 |
+
|
| 70 |
+
if depth == 1:
|
| 71 |
+
self._mode, rawmode = "1", "1;I"
|
| 72 |
+
elif depth == 4:
|
| 73 |
+
self._mode, rawmode = "L", "L;4"
|
| 74 |
+
elif depth == 8:
|
| 75 |
+
self._mode = rawmode = "L"
|
| 76 |
+
elif depth == 24:
|
| 77 |
+
if file_type == 3:
|
| 78 |
+
self._mode, rawmode = "RGB", "RGB"
|
| 79 |
+
else:
|
| 80 |
+
self._mode, rawmode = "RGB", "BGR"
|
| 81 |
+
elif depth == 32:
|
| 82 |
+
if file_type == 3:
|
| 83 |
+
self._mode, rawmode = "RGB", "RGBX"
|
| 84 |
+
else:
|
| 85 |
+
self._mode, rawmode = "RGB", "BGRX"
|
| 86 |
+
else:
|
| 87 |
+
msg = "Unsupported Mode/Bit Depth"
|
| 88 |
+
raise SyntaxError(msg)
|
| 89 |
+
|
| 90 |
+
if palette_length:
|
| 91 |
+
if palette_length > 1024:
|
| 92 |
+
msg = "Unsupported Color Palette Length"
|
| 93 |
+
raise SyntaxError(msg)
|
| 94 |
+
|
| 95 |
+
if palette_type != 1:
|
| 96 |
+
msg = "Unsupported Palette Type"
|
| 97 |
+
raise SyntaxError(msg)
|
| 98 |
+
|
| 99 |
+
offset = offset + palette_length
|
| 100 |
+
self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))
|
| 101 |
+
if self.mode == "L":
|
| 102 |
+
self._mode = "P"
|
| 103 |
+
rawmode = rawmode.replace("L", "P")
|
| 104 |
+
|
| 105 |
+
# 16 bit boundaries on stride
|
| 106 |
+
stride = ((self.size[0] * depth + 15) // 16) * 2
|
| 107 |
+
|
| 108 |
+
# file type: Type is the version (or flavor) of the bitmap
|
| 109 |
+
# file. The following values are typically found in the Type
|
| 110 |
+
# field:
|
| 111 |
+
# 0000h Old
|
| 112 |
+
# 0001h Standard
|
| 113 |
+
# 0002h Byte-encoded
|
| 114 |
+
# 0003h RGB format
|
| 115 |
+
# 0004h TIFF format
|
| 116 |
+
# 0005h IFF format
|
| 117 |
+
# FFFFh Experimental
|
| 118 |
+
|
| 119 |
+
# Old and standard are the same, except for the length tag.
|
| 120 |
+
# byte-encoded is run-length-encoded
|
| 121 |
+
# RGB looks similar to standard, but RGB byte order
|
| 122 |
+
# TIFF and IFF mean that they were converted from T/IFF
|
| 123 |
+
# Experimental means that it's something else.
|
| 124 |
+
# (https://www.fileformat.info/format/sunraster/egff.htm)
|
| 125 |
+
|
| 126 |
+
if file_type in (0, 1, 3, 4, 5):
|
| 127 |
+
self.tile = [
|
| 128 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride))
|
| 129 |
+
]
|
| 130 |
+
elif file_type == 2:
|
| 131 |
+
self.tile = [
|
| 132 |
+
ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode)
|
| 133 |
+
]
|
| 134 |
+
else:
|
| 135 |
+
msg = "Unsupported Sun Raster file type"
|
| 136 |
+
raise SyntaxError(msg)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
#
|
| 140 |
+
# registry
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
Image.register_open(SunImageFile.format, SunImageFile, _accept)
|
| 144 |
+
|
| 145 |
+
Image.register_extension(SunImageFile.format, ".ras")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TarIO.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# read files from within a tar file
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-06-18 fl Created
|
| 9 |
+
# 96-05-28 fl Open files in binary mode
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1995-96.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
|
| 20 |
+
from . import ContainerIO
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TarIO(ContainerIO.ContainerIO[bytes]):
|
| 24 |
+
"""A file object that provides read access to a given member of a TAR file."""
|
| 25 |
+
|
| 26 |
+
def __init__(self, tarfile: str, file: str) -> None:
|
| 27 |
+
"""
|
| 28 |
+
Create file object.
|
| 29 |
+
|
| 30 |
+
:param tarfile: Name of TAR file.
|
| 31 |
+
:param file: Name of member file.
|
| 32 |
+
"""
|
| 33 |
+
self.fh = open(tarfile, "rb")
|
| 34 |
+
|
| 35 |
+
while True:
|
| 36 |
+
s = self.fh.read(512)
|
| 37 |
+
if len(s) != 512:
|
| 38 |
+
self.fh.close()
|
| 39 |
+
|
| 40 |
+
msg = "unexpected end of tar file"
|
| 41 |
+
raise OSError(msg)
|
| 42 |
+
|
| 43 |
+
name = s[:100].decode("utf-8")
|
| 44 |
+
i = name.find("\0")
|
| 45 |
+
if i == 0:
|
| 46 |
+
self.fh.close()
|
| 47 |
+
|
| 48 |
+
msg = "cannot find subfile"
|
| 49 |
+
raise OSError(msg)
|
| 50 |
+
if i > 0:
|
| 51 |
+
name = name[:i]
|
| 52 |
+
|
| 53 |
+
size = int(s[124:135], 8)
|
| 54 |
+
|
| 55 |
+
if file == name:
|
| 56 |
+
break
|
| 57 |
+
|
| 58 |
+
self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
|
| 59 |
+
|
| 60 |
+
# Open region
|
| 61 |
+
super().__init__(self.fh, self.fh.tell(), size)
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# TGA file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-09-01 fl created (reads 24-bit files only)
|
| 9 |
+
# 97-01-04 fl support more TGA versions, including compressed images
|
| 10 |
+
# 98-07-04 fl fixed orientation and alpha layer bugs
|
| 11 |
+
# 98-09-11 fl fixed orientation for runlength decoder
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import warnings
|
| 21 |
+
from typing import IO
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile, ImagePalette
|
| 24 |
+
from ._binary import i16le as i16
|
| 25 |
+
from ._binary import o8
|
| 26 |
+
from ._binary import o16le as o16
|
| 27 |
+
|
| 28 |
+
#
|
| 29 |
+
# --------------------------------------------------------------------
|
| 30 |
+
# Read RGA file
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
MODES = {
|
| 34 |
+
# map imagetype/depth to rawmode
|
| 35 |
+
(1, 8): "P",
|
| 36 |
+
(3, 1): "1",
|
| 37 |
+
(3, 8): "L",
|
| 38 |
+
(3, 16): "LA",
|
| 39 |
+
(2, 16): "BGRA;15Z",
|
| 40 |
+
(2, 24): "BGR",
|
| 41 |
+
(2, 32): "BGRA",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
##
|
| 46 |
+
# Image plugin for Targa files.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class TgaImageFile(ImageFile.ImageFile):
|
| 50 |
+
format = "TGA"
|
| 51 |
+
format_description = "Targa"
|
| 52 |
+
|
| 53 |
+
def _open(self) -> None:
|
| 54 |
+
# process header
|
| 55 |
+
assert self.fp is not None
|
| 56 |
+
|
| 57 |
+
s = self.fp.read(18)
|
| 58 |
+
|
| 59 |
+
id_len = s[0]
|
| 60 |
+
|
| 61 |
+
colormaptype = s[1]
|
| 62 |
+
imagetype = s[2]
|
| 63 |
+
|
| 64 |
+
depth = s[16]
|
| 65 |
+
|
| 66 |
+
flags = s[17]
|
| 67 |
+
|
| 68 |
+
self._size = i16(s, 12), i16(s, 14)
|
| 69 |
+
|
| 70 |
+
# validate header fields
|
| 71 |
+
if (
|
| 72 |
+
colormaptype not in (0, 1)
|
| 73 |
+
or self.size[0] <= 0
|
| 74 |
+
or self.size[1] <= 0
|
| 75 |
+
or depth not in (1, 8, 16, 24, 32)
|
| 76 |
+
):
|
| 77 |
+
msg = "not a TGA file"
|
| 78 |
+
raise SyntaxError(msg)
|
| 79 |
+
|
| 80 |
+
# image mode
|
| 81 |
+
if imagetype in (3, 11):
|
| 82 |
+
self._mode = "L"
|
| 83 |
+
if depth == 1:
|
| 84 |
+
self._mode = "1" # ???
|
| 85 |
+
elif depth == 16:
|
| 86 |
+
self._mode = "LA"
|
| 87 |
+
elif imagetype in (1, 9):
|
| 88 |
+
self._mode = "P" if colormaptype else "L"
|
| 89 |
+
elif imagetype in (2, 10):
|
| 90 |
+
self._mode = "RGB" if depth == 24 else "RGBA"
|
| 91 |
+
else:
|
| 92 |
+
msg = "unknown TGA mode"
|
| 93 |
+
raise SyntaxError(msg)
|
| 94 |
+
|
| 95 |
+
# orientation
|
| 96 |
+
orientation = flags & 0x30
|
| 97 |
+
self._flip_horizontally = orientation in [0x10, 0x30]
|
| 98 |
+
if orientation in [0x20, 0x30]:
|
| 99 |
+
orientation = 1
|
| 100 |
+
elif orientation in [0, 0x10]:
|
| 101 |
+
orientation = -1
|
| 102 |
+
else:
|
| 103 |
+
msg = "unknown TGA orientation"
|
| 104 |
+
raise SyntaxError(msg)
|
| 105 |
+
|
| 106 |
+
self.info["orientation"] = orientation
|
| 107 |
+
|
| 108 |
+
if imagetype & 8:
|
| 109 |
+
self.info["compression"] = "tga_rle"
|
| 110 |
+
|
| 111 |
+
if id_len:
|
| 112 |
+
self.info["id_section"] = self.fp.read(id_len)
|
| 113 |
+
|
| 114 |
+
if colormaptype:
|
| 115 |
+
# read palette
|
| 116 |
+
start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
|
| 117 |
+
if mapdepth == 16:
|
| 118 |
+
self.palette = ImagePalette.raw(
|
| 119 |
+
"BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)
|
| 120 |
+
)
|
| 121 |
+
self.palette.mode = "RGBA"
|
| 122 |
+
elif mapdepth == 24:
|
| 123 |
+
self.palette = ImagePalette.raw(
|
| 124 |
+
"BGR", bytes(3 * start) + self.fp.read(3 * size)
|
| 125 |
+
)
|
| 126 |
+
elif mapdepth == 32:
|
| 127 |
+
self.palette = ImagePalette.raw(
|
| 128 |
+
"BGRA", bytes(4 * start) + self.fp.read(4 * size)
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
msg = "unknown TGA map depth"
|
| 132 |
+
raise SyntaxError(msg)
|
| 133 |
+
|
| 134 |
+
# setup tile descriptor
|
| 135 |
+
try:
|
| 136 |
+
rawmode = MODES[(imagetype & 7, depth)]
|
| 137 |
+
if imagetype & 8:
|
| 138 |
+
# compressed
|
| 139 |
+
self.tile = [
|
| 140 |
+
ImageFile._Tile(
|
| 141 |
+
"tga_rle",
|
| 142 |
+
(0, 0) + self.size,
|
| 143 |
+
self.fp.tell(),
|
| 144 |
+
(rawmode, orientation, depth),
|
| 145 |
+
)
|
| 146 |
+
]
|
| 147 |
+
else:
|
| 148 |
+
self.tile = [
|
| 149 |
+
ImageFile._Tile(
|
| 150 |
+
"raw",
|
| 151 |
+
(0, 0) + self.size,
|
| 152 |
+
self.fp.tell(),
|
| 153 |
+
(rawmode, 0, orientation),
|
| 154 |
+
)
|
| 155 |
+
]
|
| 156 |
+
except KeyError:
|
| 157 |
+
pass # cannot decode
|
| 158 |
+
|
| 159 |
+
def load_end(self) -> None:
|
| 160 |
+
if self._flip_horizontally:
|
| 161 |
+
self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
#
|
| 165 |
+
# --------------------------------------------------------------------
|
| 166 |
+
# Write TGA file
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
SAVE = {
|
| 170 |
+
"1": ("1", 1, 0, 3),
|
| 171 |
+
"L": ("L", 8, 0, 3),
|
| 172 |
+
"LA": ("LA", 16, 0, 3),
|
| 173 |
+
"P": ("P", 8, 1, 1),
|
| 174 |
+
"RGB": ("BGR", 24, 0, 2),
|
| 175 |
+
"RGBA": ("BGRA", 32, 0, 2),
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 180 |
+
try:
|
| 181 |
+
rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
|
| 182 |
+
except KeyError as e:
|
| 183 |
+
msg = f"cannot write mode {im.mode} as TGA"
|
| 184 |
+
raise OSError(msg) from e
|
| 185 |
+
|
| 186 |
+
if "rle" in im.encoderinfo:
|
| 187 |
+
rle = im.encoderinfo["rle"]
|
| 188 |
+
else:
|
| 189 |
+
compression = im.encoderinfo.get("compression", im.info.get("compression"))
|
| 190 |
+
rle = compression == "tga_rle"
|
| 191 |
+
if rle:
|
| 192 |
+
imagetype += 8
|
| 193 |
+
|
| 194 |
+
id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
|
| 195 |
+
id_len = len(id_section)
|
| 196 |
+
if id_len > 255:
|
| 197 |
+
id_len = 255
|
| 198 |
+
id_section = id_section[:255]
|
| 199 |
+
warnings.warn("id_section has been trimmed to 255 characters")
|
| 200 |
+
|
| 201 |
+
if colormaptype:
|
| 202 |
+
palette = im.im.getpalette("RGB", "BGR")
|
| 203 |
+
colormaplength, colormapentry = len(palette) // 3, 24
|
| 204 |
+
else:
|
| 205 |
+
colormaplength, colormapentry = 0, 0
|
| 206 |
+
|
| 207 |
+
if im.mode in ("LA", "RGBA"):
|
| 208 |
+
flags = 8
|
| 209 |
+
else:
|
| 210 |
+
flags = 0
|
| 211 |
+
|
| 212 |
+
orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
|
| 213 |
+
if orientation > 0:
|
| 214 |
+
flags = flags | 0x20
|
| 215 |
+
|
| 216 |
+
fp.write(
|
| 217 |
+
o8(id_len)
|
| 218 |
+
+ o8(colormaptype)
|
| 219 |
+
+ o8(imagetype)
|
| 220 |
+
+ o16(0) # colormapfirst
|
| 221 |
+
+ o16(colormaplength)
|
| 222 |
+
+ o8(colormapentry)
|
| 223 |
+
+ o16(0)
|
| 224 |
+
+ o16(0)
|
| 225 |
+
+ o16(im.size[0])
|
| 226 |
+
+ o16(im.size[1])
|
| 227 |
+
+ o8(bits)
|
| 228 |
+
+ o8(flags)
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
if id_section:
|
| 232 |
+
fp.write(id_section)
|
| 233 |
+
|
| 234 |
+
if colormaptype:
|
| 235 |
+
fp.write(palette)
|
| 236 |
+
|
| 237 |
+
if rle:
|
| 238 |
+
ImageFile._save(
|
| 239 |
+
im,
|
| 240 |
+
fp,
|
| 241 |
+
[ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))],
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
ImageFile._save(
|
| 245 |
+
im,
|
| 246 |
+
fp,
|
| 247 |
+
[ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))],
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# write targa version 2 footer
|
| 251 |
+
fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
#
|
| 255 |
+
# --------------------------------------------------------------------
|
| 256 |
+
# Registry
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
Image.register_open(TgaImageFile.format, TgaImageFile)
|
| 260 |
+
Image.register_save(TgaImageFile.format, _save)
|
| 261 |
+
|
| 262 |
+
Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
|
| 263 |
+
|
| 264 |
+
Image.register_mime(TgaImageFile.format, "image/x-tga")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py
ADDED
|
@@ -0,0 +1,2338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# TIFF file handling
|
| 6 |
+
#
|
| 7 |
+
# TIFF is a flexible, if somewhat aged, image file format originally
|
| 8 |
+
# defined by Aldus. Although TIFF supports a wide variety of pixel
|
| 9 |
+
# layouts and compression methods, the name doesn't really stand for
|
| 10 |
+
# "thousands of incompatible file formats," it just feels that way.
|
| 11 |
+
#
|
| 12 |
+
# To read TIFF data from a stream, the stream must be seekable. For
|
| 13 |
+
# progressive decoding, make sure to use TIFF files where the tag
|
| 14 |
+
# directory is placed first in the file.
|
| 15 |
+
#
|
| 16 |
+
# History:
|
| 17 |
+
# 1995-09-01 fl Created
|
| 18 |
+
# 1996-05-04 fl Handle JPEGTABLES tag
|
| 19 |
+
# 1996-05-18 fl Fixed COLORMAP support
|
| 20 |
+
# 1997-01-05 fl Fixed PREDICTOR support
|
| 21 |
+
# 1997-08-27 fl Added support for rational tags (from Perry Stoll)
|
| 22 |
+
# 1998-01-10 fl Fixed seek/tell (from Jan Blom)
|
| 23 |
+
# 1998-07-15 fl Use private names for internal variables
|
| 24 |
+
# 1999-06-13 fl Rewritten for PIL 1.0 (1.0)
|
| 25 |
+
# 2000-10-11 fl Additional fixes for Python 2.0 (1.1)
|
| 26 |
+
# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2)
|
| 27 |
+
# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3)
|
| 28 |
+
# 2001-12-18 fl Added workaround for broken Matrox library
|
| 29 |
+
# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart)
|
| 30 |
+
# 2003-05-19 fl Check FILLORDER tag
|
| 31 |
+
# 2003-09-26 fl Added RGBa support
|
| 32 |
+
# 2004-02-24 fl Added DPI support; fixed rational write support
|
| 33 |
+
# 2005-02-07 fl Added workaround for broken Corel Draw 10 files
|
| 34 |
+
# 2006-01-09 fl Added support for float/double tags (from Russell Nelson)
|
| 35 |
+
#
|
| 36 |
+
# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved.
|
| 37 |
+
# Copyright (c) 1995-1997 by Fredrik Lundh
|
| 38 |
+
#
|
| 39 |
+
# See the README file for information on usage and redistribution.
|
| 40 |
+
#
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import io
|
| 44 |
+
import itertools
|
| 45 |
+
import logging
|
| 46 |
+
import math
|
| 47 |
+
import os
|
| 48 |
+
import struct
|
| 49 |
+
import warnings
|
| 50 |
+
from collections.abc import Callable, MutableMapping
|
| 51 |
+
from fractions import Fraction
|
| 52 |
+
from numbers import Number, Rational
|
| 53 |
+
from typing import IO, Any, cast
|
| 54 |
+
|
| 55 |
+
from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags
|
| 56 |
+
from ._binary import i16be as i16
|
| 57 |
+
from ._binary import i32be as i32
|
| 58 |
+
from ._binary import o8
|
| 59 |
+
from ._util import DeferredError, is_path
|
| 60 |
+
from .TiffTags import TYPES
|
| 61 |
+
|
| 62 |
+
TYPE_CHECKING = False
|
| 63 |
+
if TYPE_CHECKING:
|
| 64 |
+
from collections.abc import Iterator
|
| 65 |
+
from typing import NoReturn
|
| 66 |
+
|
| 67 |
+
from ._typing import Buffer, IntegralLike, StrOrBytesPath
|
| 68 |
+
|
| 69 |
+
logger = logging.getLogger(__name__)
|
| 70 |
+
|
| 71 |
+
# Set these to true to force use of libtiff for reading or writing.
|
| 72 |
+
READ_LIBTIFF = False
|
| 73 |
+
WRITE_LIBTIFF = False
|
| 74 |
+
STRIP_SIZE = 65536
|
| 75 |
+
|
| 76 |
+
II = b"II" # little-endian (Intel style)
|
| 77 |
+
MM = b"MM" # big-endian (Motorola style)
|
| 78 |
+
|
| 79 |
+
#
|
| 80 |
+
# --------------------------------------------------------------------
|
| 81 |
+
# Read TIFF files
|
| 82 |
+
|
| 83 |
+
# a few tag names, just to make the code below a bit more readable
|
| 84 |
+
OSUBFILETYPE = 255
|
| 85 |
+
IMAGEWIDTH = 256
|
| 86 |
+
IMAGELENGTH = 257
|
| 87 |
+
BITSPERSAMPLE = 258
|
| 88 |
+
COMPRESSION = 259
|
| 89 |
+
PHOTOMETRIC_INTERPRETATION = 262
|
| 90 |
+
FILLORDER = 266
|
| 91 |
+
IMAGEDESCRIPTION = 270
|
| 92 |
+
STRIPOFFSETS = 273
|
| 93 |
+
SAMPLESPERPIXEL = 277
|
| 94 |
+
ROWSPERSTRIP = 278
|
| 95 |
+
STRIPBYTECOUNTS = 279
|
| 96 |
+
X_RESOLUTION = 282
|
| 97 |
+
Y_RESOLUTION = 283
|
| 98 |
+
PLANAR_CONFIGURATION = 284
|
| 99 |
+
RESOLUTION_UNIT = 296
|
| 100 |
+
TRANSFERFUNCTION = 301
|
| 101 |
+
SOFTWARE = 305
|
| 102 |
+
DATE_TIME = 306
|
| 103 |
+
ARTIST = 315
|
| 104 |
+
PREDICTOR = 317
|
| 105 |
+
COLORMAP = 320
|
| 106 |
+
TILEWIDTH = 322
|
| 107 |
+
TILELENGTH = 323
|
| 108 |
+
TILEOFFSETS = 324
|
| 109 |
+
TILEBYTECOUNTS = 325
|
| 110 |
+
SUBIFD = 330
|
| 111 |
+
EXTRASAMPLES = 338
|
| 112 |
+
SAMPLEFORMAT = 339
|
| 113 |
+
JPEGTABLES = 347
|
| 114 |
+
YCBCRSUBSAMPLING = 530
|
| 115 |
+
REFERENCEBLACKWHITE = 532
|
| 116 |
+
COPYRIGHT = 33432
|
| 117 |
+
IPTC_NAA_CHUNK = 33723 # newsphoto properties
|
| 118 |
+
PHOTOSHOP_CHUNK = 34377 # photoshop properties
|
| 119 |
+
ICCPROFILE = 34675
|
| 120 |
+
EXIFIFD = 34665
|
| 121 |
+
XMP = 700
|
| 122 |
+
JPEGQUALITY = 65537 # pseudo-tag by libtiff
|
| 123 |
+
|
| 124 |
+
# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
|
| 125 |
+
IMAGEJ_META_DATA_BYTE_COUNTS = 50838
|
| 126 |
+
IMAGEJ_META_DATA = 50839
|
| 127 |
+
|
| 128 |
+
COMPRESSION_INFO = {
|
| 129 |
+
# Compression => pil compression name
|
| 130 |
+
1: "raw",
|
| 131 |
+
2: "tiff_ccitt",
|
| 132 |
+
3: "group3",
|
| 133 |
+
4: "group4",
|
| 134 |
+
5: "tiff_lzw",
|
| 135 |
+
6: "tiff_jpeg", # obsolete
|
| 136 |
+
7: "jpeg",
|
| 137 |
+
8: "tiff_adobe_deflate",
|
| 138 |
+
32771: "tiff_raw_16", # 16-bit padding
|
| 139 |
+
32773: "packbits",
|
| 140 |
+
32809: "tiff_thunderscan",
|
| 141 |
+
32946: "tiff_deflate",
|
| 142 |
+
34676: "tiff_sgilog",
|
| 143 |
+
34677: "tiff_sgilog24",
|
| 144 |
+
34925: "lzma",
|
| 145 |
+
50000: "zstd",
|
| 146 |
+
50001: "webp",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}
|
| 150 |
+
|
| 151 |
+
OPEN_INFO = {
|
| 152 |
+
# (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
|
| 153 |
+
# ExtraSamples) => mode, rawmode
|
| 154 |
+
(II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 155 |
+
(MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 156 |
+
(II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 157 |
+
(MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 158 |
+
(II, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 159 |
+
(MM, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 160 |
+
(II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 161 |
+
(MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 162 |
+
(II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 163 |
+
(MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 164 |
+
(II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 165 |
+
(MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 166 |
+
(II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 167 |
+
(MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 168 |
+
(II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 169 |
+
(MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 170 |
+
(II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 171 |
+
(MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 172 |
+
(II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 173 |
+
(MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 174 |
+
(II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 175 |
+
(MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 176 |
+
(II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 177 |
+
(MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 178 |
+
(II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 179 |
+
(MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 180 |
+
(II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 181 |
+
(MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 182 |
+
(II, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 183 |
+
(MM, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 184 |
+
(II, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 185 |
+
(MM, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 186 |
+
(II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 187 |
+
(MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 188 |
+
(II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
|
| 189 |
+
(II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 190 |
+
(II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 191 |
+
(MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
|
| 192 |
+
(II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),
|
| 193 |
+
(II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),
|
| 194 |
+
(MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),
|
| 195 |
+
(II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 196 |
+
(MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 197 |
+
(II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
|
| 198 |
+
(II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
|
| 199 |
+
(MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),
|
| 200 |
+
(II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 201 |
+
(MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 202 |
+
(II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 203 |
+
(MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 204 |
+
(II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 205 |
+
(MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 206 |
+
(II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 207 |
+
(MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 208 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 209 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 210 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 211 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 212 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 213 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 214 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 215 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 216 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 217 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 218 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 219 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 220 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 221 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 222 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 223 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 224 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 225 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 226 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 227 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 228 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 229 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 230 |
+
(II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),
|
| 231 |
+
(MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),
|
| 232 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),
|
| 233 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),
|
| 234 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),
|
| 235 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),
|
| 236 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),
|
| 237 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),
|
| 238 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),
|
| 239 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),
|
| 240 |
+
(II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 241 |
+
(MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 242 |
+
(II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 243 |
+
(MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 244 |
+
(II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 245 |
+
(MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 246 |
+
(II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 247 |
+
(MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 248 |
+
(II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 249 |
+
(MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 250 |
+
(II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 251 |
+
(MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 252 |
+
(II, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 253 |
+
(MM, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 254 |
+
(II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
|
| 255 |
+
(MM, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
|
| 256 |
+
(II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 257 |
+
(MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 258 |
+
(II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 259 |
+
(MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 260 |
+
(II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 261 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 262 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 263 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 264 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 265 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 266 |
+
(II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),
|
| 267 |
+
(MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"),
|
| 268 |
+
(II, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 269 |
+
(MM, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 270 |
+
# JPEG compressed images handled by LibTiff and auto-converted to RGBX
|
| 271 |
+
# Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel
|
| 272 |
+
(II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 273 |
+
(MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 274 |
+
(II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 275 |
+
(MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)
|
| 279 |
+
|
| 280 |
+
PREFIXES = [
|
| 281 |
+
b"MM\x00\x2a", # Valid TIFF header with big-endian byte order
|
| 282 |
+
b"II\x2a\x00", # Valid TIFF header with little-endian byte order
|
| 283 |
+
b"MM\x2a\x00", # Invalid TIFF header, assume big-endian
|
| 284 |
+
b"II\x00\x2a", # Invalid TIFF header, assume little-endian
|
| 285 |
+
b"MM\x00\x2b", # BigTIFF with big-endian byte order
|
| 286 |
+
b"II\x2b\x00", # BigTIFF with little-endian byte order
|
| 287 |
+
]
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _accept(prefix: bytes) -> bool:
|
| 291 |
+
return prefix.startswith(tuple(PREFIXES))
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _limit_rational(
|
| 295 |
+
val: float | Fraction | IFDRational, max_val: int
|
| 296 |
+
) -> tuple[IntegralLike, IntegralLike]:
|
| 297 |
+
inv = abs(val) > 1
|
| 298 |
+
n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
|
| 299 |
+
return n_d[::-1] if inv else n_d
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _limit_signed_rational(
|
| 303 |
+
val: IFDRational, max_val: int, min_val: int
|
| 304 |
+
) -> tuple[IntegralLike, IntegralLike]:
|
| 305 |
+
frac = Fraction(val)
|
| 306 |
+
n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator
|
| 307 |
+
|
| 308 |
+
if min(float(i) for i in n_d) < min_val:
|
| 309 |
+
n_d = _limit_rational(val, abs(min_val))
|
| 310 |
+
|
| 311 |
+
n_d_float = tuple(float(i) for i in n_d)
|
| 312 |
+
if max(n_d_float) > max_val:
|
| 313 |
+
n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val)
|
| 314 |
+
|
| 315 |
+
return n_d
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
##
|
| 319 |
+
# Wrapper for TIFF IFDs.
|
| 320 |
+
|
| 321 |
+
_load_dispatch = {}
|
| 322 |
+
_write_dispatch = {}
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _delegate(op: str) -> Any:
|
| 326 |
+
def delegate(
|
| 327 |
+
self: IFDRational, *args: tuple[float, ...]
|
| 328 |
+
) -> bool | float | Fraction:
|
| 329 |
+
return getattr(self._val, op)(*args)
|
| 330 |
+
|
| 331 |
+
return delegate
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class IFDRational(Rational):
|
| 335 |
+
"""Implements a rational class where 0/0 is a legal value to match
|
| 336 |
+
the in the wild use of exif rationals.
|
| 337 |
+
|
| 338 |
+
e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
""" If the denominator is 0, store this as a float('nan'), otherwise store
|
| 342 |
+
as a fractions.Fraction(). Delegate as appropriate
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
__slots__ = ("_numerator", "_denominator", "_val")
|
| 347 |
+
|
| 348 |
+
def __init__(
|
| 349 |
+
self, value: float | Fraction | IFDRational, denominator: int = 1
|
| 350 |
+
) -> None:
|
| 351 |
+
"""
|
| 352 |
+
:param value: either an integer numerator, a
|
| 353 |
+
float/rational/other number, or an IFDRational
|
| 354 |
+
:param denominator: Optional integer denominator
|
| 355 |
+
"""
|
| 356 |
+
self._val: Fraction | float
|
| 357 |
+
if isinstance(value, IFDRational):
|
| 358 |
+
self._numerator = value.numerator
|
| 359 |
+
self._denominator = value.denominator
|
| 360 |
+
self._val = value._val
|
| 361 |
+
return
|
| 362 |
+
|
| 363 |
+
if isinstance(value, Fraction):
|
| 364 |
+
self._numerator = value.numerator
|
| 365 |
+
self._denominator = value.denominator
|
| 366 |
+
else:
|
| 367 |
+
if TYPE_CHECKING:
|
| 368 |
+
self._numerator = cast(IntegralLike, value)
|
| 369 |
+
else:
|
| 370 |
+
self._numerator = value
|
| 371 |
+
self._denominator = denominator
|
| 372 |
+
|
| 373 |
+
if denominator == 0:
|
| 374 |
+
self._val = float("nan")
|
| 375 |
+
elif denominator == 1:
|
| 376 |
+
self._val = Fraction(value)
|
| 377 |
+
elif int(value) == value:
|
| 378 |
+
self._val = Fraction(int(value), denominator)
|
| 379 |
+
else:
|
| 380 |
+
self._val = Fraction(value / denominator)
|
| 381 |
+
|
| 382 |
+
@property
|
| 383 |
+
def numerator(self) -> IntegralLike:
|
| 384 |
+
return self._numerator
|
| 385 |
+
|
| 386 |
+
@property
|
| 387 |
+
def denominator(self) -> int:
|
| 388 |
+
return self._denominator
|
| 389 |
+
|
| 390 |
+
def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]:
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
:param max_denominator: Integer, the maximum denominator value
|
| 394 |
+
:returns: Tuple of (numerator, denominator)
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
if self.denominator == 0:
|
| 398 |
+
return self.numerator, self.denominator
|
| 399 |
+
|
| 400 |
+
assert isinstance(self._val, Fraction)
|
| 401 |
+
f = self._val.limit_denominator(max_denominator)
|
| 402 |
+
return f.numerator, f.denominator
|
| 403 |
+
|
| 404 |
+
def __repr__(self) -> str:
|
| 405 |
+
return str(float(self._val))
|
| 406 |
+
|
| 407 |
+
def __hash__(self) -> int: # type: ignore[override]
|
| 408 |
+
return self._val.__hash__()
|
| 409 |
+
|
| 410 |
+
def __eq__(self, other: object) -> bool:
|
| 411 |
+
val = self._val
|
| 412 |
+
if isinstance(other, IFDRational):
|
| 413 |
+
other = other._val
|
| 414 |
+
if isinstance(other, float):
|
| 415 |
+
val = float(val)
|
| 416 |
+
return val == other
|
| 417 |
+
|
| 418 |
+
def __getstate__(self) -> list[float | Fraction | IntegralLike]:
|
| 419 |
+
return [self._val, self._numerator, self._denominator]
|
| 420 |
+
|
| 421 |
+
def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None:
|
| 422 |
+
IFDRational.__init__(self, 0)
|
| 423 |
+
_val, _numerator, _denominator = state
|
| 424 |
+
assert isinstance(_val, (float, Fraction))
|
| 425 |
+
self._val = _val
|
| 426 |
+
if TYPE_CHECKING:
|
| 427 |
+
self._numerator = cast(IntegralLike, _numerator)
|
| 428 |
+
else:
|
| 429 |
+
self._numerator = _numerator
|
| 430 |
+
assert isinstance(_denominator, int)
|
| 431 |
+
self._denominator = _denominator
|
| 432 |
+
|
| 433 |
+
""" a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul',
|
| 434 |
+
'truediv', 'rtruediv', 'floordiv', 'rfloordiv',
|
| 435 |
+
'mod','rmod', 'pow','rpow', 'pos', 'neg',
|
| 436 |
+
'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool',
|
| 437 |
+
'ceil', 'floor', 'round']
|
| 438 |
+
print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
|
| 439 |
+
"""
|
| 440 |
+
|
| 441 |
+
__add__ = _delegate("__add__")
|
| 442 |
+
__radd__ = _delegate("__radd__")
|
| 443 |
+
__sub__ = _delegate("__sub__")
|
| 444 |
+
__rsub__ = _delegate("__rsub__")
|
| 445 |
+
__mul__ = _delegate("__mul__")
|
| 446 |
+
__rmul__ = _delegate("__rmul__")
|
| 447 |
+
__truediv__ = _delegate("__truediv__")
|
| 448 |
+
__rtruediv__ = _delegate("__rtruediv__")
|
| 449 |
+
__floordiv__ = _delegate("__floordiv__")
|
| 450 |
+
__rfloordiv__ = _delegate("__rfloordiv__")
|
| 451 |
+
__mod__ = _delegate("__mod__")
|
| 452 |
+
__rmod__ = _delegate("__rmod__")
|
| 453 |
+
__pow__ = _delegate("__pow__")
|
| 454 |
+
__rpow__ = _delegate("__rpow__")
|
| 455 |
+
__pos__ = _delegate("__pos__")
|
| 456 |
+
__neg__ = _delegate("__neg__")
|
| 457 |
+
__abs__ = _delegate("__abs__")
|
| 458 |
+
__trunc__ = _delegate("__trunc__")
|
| 459 |
+
__lt__ = _delegate("__lt__")
|
| 460 |
+
__gt__ = _delegate("__gt__")
|
| 461 |
+
__le__ = _delegate("__le__")
|
| 462 |
+
__ge__ = _delegate("__ge__")
|
| 463 |
+
__bool__ = _delegate("__bool__")
|
| 464 |
+
__ceil__ = _delegate("__ceil__")
|
| 465 |
+
__floor__ = _delegate("__floor__")
|
| 466 |
+
__round__ = _delegate("__round__")
|
| 467 |
+
# Python >= 3.11
|
| 468 |
+
if hasattr(Fraction, "__int__"):
|
| 469 |
+
__int__ = _delegate("__int__")
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
_LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any]
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]:
|
| 476 |
+
def decorator(func: _LoaderFunc) -> _LoaderFunc:
|
| 477 |
+
from .TiffTags import TYPES
|
| 478 |
+
|
| 479 |
+
if func.__name__.startswith("load_"):
|
| 480 |
+
TYPES[idx] = func.__name__[5:].replace("_", " ")
|
| 481 |
+
_load_dispatch[idx] = size, func # noqa: F821
|
| 482 |
+
return func
|
| 483 |
+
|
| 484 |
+
return decorator
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
| 488 |
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 489 |
+
_write_dispatch[idx] = func # noqa: F821
|
| 490 |
+
return func
|
| 491 |
+
|
| 492 |
+
return decorator
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _register_basic(idx_fmt_name: tuple[int, str, str]) -> None:
|
| 496 |
+
from .TiffTags import TYPES
|
| 497 |
+
|
| 498 |
+
idx, fmt, name = idx_fmt_name
|
| 499 |
+
TYPES[idx] = name
|
| 500 |
+
size = struct.calcsize(f"={fmt}")
|
| 501 |
+
|
| 502 |
+
def basic_handler(
|
| 503 |
+
self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True
|
| 504 |
+
) -> tuple[Any, ...]:
|
| 505 |
+
return self._unpack(f"{len(data) // size}{fmt}", data)
|
| 506 |
+
|
| 507 |
+
_load_dispatch[idx] = size, basic_handler # noqa: F821
|
| 508 |
+
_write_dispatch[idx] = lambda self, *values: ( # noqa: F821
|
| 509 |
+
b"".join(self._pack(fmt, value) for value in values)
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
if TYPE_CHECKING:
|
| 514 |
+
_IFDv2Base = MutableMapping[int, Any]
|
| 515 |
+
else:
|
| 516 |
+
_IFDv2Base = MutableMapping
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
class ImageFileDirectory_v2(_IFDv2Base):
|
| 520 |
+
"""This class represents a TIFF tag directory. To speed things up, we
|
| 521 |
+
don't decode tags unless they're asked for.
|
| 522 |
+
|
| 523 |
+
Exposes a dictionary interface of the tags in the directory::
|
| 524 |
+
|
| 525 |
+
ifd = ImageFileDirectory_v2()
|
| 526 |
+
ifd[key] = 'Some Data'
|
| 527 |
+
ifd.tagtype[key] = TiffTags.ASCII
|
| 528 |
+
print(ifd[key])
|
| 529 |
+
'Some Data'
|
| 530 |
+
|
| 531 |
+
Individual values are returned as the strings or numbers, sequences are
|
| 532 |
+
returned as tuples of the values.
|
| 533 |
+
|
| 534 |
+
The tiff metadata type of each item is stored in a dictionary of
|
| 535 |
+
tag types in
|
| 536 |
+
:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
|
| 537 |
+
are read from a tiff file, guessed from the type added, or added
|
| 538 |
+
manually.
|
| 539 |
+
|
| 540 |
+
Data Structures:
|
| 541 |
+
|
| 542 |
+
* ``self.tagtype = {}``
|
| 543 |
+
|
| 544 |
+
* Key: numerical TIFF tag number
|
| 545 |
+
* Value: integer corresponding to the data type from
|
| 546 |
+
:py:data:`.TiffTags.TYPES`
|
| 547 |
+
|
| 548 |
+
.. versionadded:: 3.0.0
|
| 549 |
+
|
| 550 |
+
'Internal' data structures:
|
| 551 |
+
|
| 552 |
+
* ``self._tags_v2 = {}``
|
| 553 |
+
|
| 554 |
+
* Key: numerical TIFF tag number
|
| 555 |
+
* Value: decoded data, as tuple for multiple values
|
| 556 |
+
|
| 557 |
+
* ``self._tagdata = {}``
|
| 558 |
+
|
| 559 |
+
* Key: numerical TIFF tag number
|
| 560 |
+
* Value: undecoded byte string from file
|
| 561 |
+
|
| 562 |
+
* ``self._tags_v1 = {}``
|
| 563 |
+
|
| 564 |
+
* Key: numerical TIFF tag number
|
| 565 |
+
* Value: decoded data in the v1 format
|
| 566 |
+
|
| 567 |
+
Tags will be found in the private attributes ``self._tagdata``, and in
|
| 568 |
+
``self._tags_v2`` once decoded.
|
| 569 |
+
|
| 570 |
+
``self.legacy_api`` is a value for internal use, and shouldn't be changed
|
| 571 |
+
from outside code. In cooperation with
|
| 572 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api``
|
| 573 |
+
is true, then decoded tags will be populated into both ``_tags_v1`` and
|
| 574 |
+
``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF
|
| 575 |
+
save routine. Tags should be read from ``_tags_v1`` if
|
| 576 |
+
``legacy_api == true``.
|
| 577 |
+
|
| 578 |
+
"""
|
| 579 |
+
|
| 580 |
+
_load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {}
|
| 581 |
+
_write_dispatch: dict[int, Callable[..., Any]] = {}
|
| 582 |
+
|
| 583 |
+
def __init__(
|
| 584 |
+
self,
|
| 585 |
+
ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00",
|
| 586 |
+
prefix: bytes | None = None,
|
| 587 |
+
group: int | None = None,
|
| 588 |
+
) -> None:
|
| 589 |
+
"""Initialize an ImageFileDirectory.
|
| 590 |
+
|
| 591 |
+
To construct an ImageFileDirectory from a real file, pass the 8-byte
|
| 592 |
+
magic header to the constructor. To only set the endianness, pass it
|
| 593 |
+
as the 'prefix' keyword argument.
|
| 594 |
+
|
| 595 |
+
:param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
|
| 596 |
+
endianness.
|
| 597 |
+
:param prefix: Override the endianness of the file.
|
| 598 |
+
"""
|
| 599 |
+
if not _accept(ifh):
|
| 600 |
+
msg = f"not a TIFF file (header {repr(ifh)} not valid)"
|
| 601 |
+
raise SyntaxError(msg)
|
| 602 |
+
self._prefix = prefix if prefix is not None else ifh[:2]
|
| 603 |
+
if self._prefix == MM:
|
| 604 |
+
self._endian = ">"
|
| 605 |
+
elif self._prefix == II:
|
| 606 |
+
self._endian = "<"
|
| 607 |
+
else:
|
| 608 |
+
msg = "not a TIFF IFD"
|
| 609 |
+
raise SyntaxError(msg)
|
| 610 |
+
self._bigtiff = ifh[2] == 43
|
| 611 |
+
self.group = group
|
| 612 |
+
self.tagtype: dict[int, int] = {}
|
| 613 |
+
""" Dictionary of tag types """
|
| 614 |
+
self.reset()
|
| 615 |
+
self.next = (
|
| 616 |
+
self._unpack("Q", ifh[8:])[0]
|
| 617 |
+
if self._bigtiff
|
| 618 |
+
else self._unpack("L", ifh[4:])[0]
|
| 619 |
+
)
|
| 620 |
+
self._legacy_api = False
|
| 621 |
+
|
| 622 |
+
prefix = property(lambda self: self._prefix)
|
| 623 |
+
offset = property(lambda self: self._offset)
|
| 624 |
+
|
| 625 |
+
@property
|
| 626 |
+
def legacy_api(self) -> bool:
|
| 627 |
+
return self._legacy_api
|
| 628 |
+
|
| 629 |
+
@legacy_api.setter
|
| 630 |
+
def legacy_api(self, value: bool) -> NoReturn:
|
| 631 |
+
msg = "Not allowing setting of legacy api"
|
| 632 |
+
raise Exception(msg)
|
| 633 |
+
|
| 634 |
+
def reset(self) -> None:
|
| 635 |
+
self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false
|
| 636 |
+
self._tags_v2: dict[int, Any] = {} # main tag storage
|
| 637 |
+
self._tagdata: dict[int, bytes] = {}
|
| 638 |
+
self.tagtype = {} # added 2008-06-05 by Florian Hoech
|
| 639 |
+
self._next = None
|
| 640 |
+
self._offset: int | None = None
|
| 641 |
+
|
| 642 |
+
def __str__(self) -> str:
|
| 643 |
+
return str(dict(self))
|
| 644 |
+
|
| 645 |
+
def named(self) -> dict[str, Any]:
|
| 646 |
+
"""
|
| 647 |
+
:returns: dict of name|key: value
|
| 648 |
+
|
| 649 |
+
Returns the complete tag dictionary, with named tags where possible.
|
| 650 |
+
"""
|
| 651 |
+
return {
|
| 652 |
+
TiffTags.lookup(code, self.group).name: value
|
| 653 |
+
for code, value in self.items()
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
def __len__(self) -> int:
|
| 657 |
+
return len(set(self._tagdata) | set(self._tags_v2))
|
| 658 |
+
|
| 659 |
+
def __getitem__(self, tag: int) -> Any:
|
| 660 |
+
if tag not in self._tags_v2: # unpack on the fly
|
| 661 |
+
data = self._tagdata[tag]
|
| 662 |
+
typ = self.tagtype[tag]
|
| 663 |
+
size, handler = self._load_dispatch[typ]
|
| 664 |
+
self[tag] = handler(self, data, self.legacy_api) # check type
|
| 665 |
+
val = self._tags_v2[tag]
|
| 666 |
+
if self.legacy_api and not isinstance(val, (tuple, bytes)):
|
| 667 |
+
val = (val,)
|
| 668 |
+
return val
|
| 669 |
+
|
| 670 |
+
def __contains__(self, tag: object) -> bool:
|
| 671 |
+
return tag in self._tags_v2 or tag in self._tagdata
|
| 672 |
+
|
| 673 |
+
def __setitem__(self, tag: int, value: Any) -> None:
|
| 674 |
+
self._setitem(tag, value, self.legacy_api)
|
| 675 |
+
|
| 676 |
+
def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None:
|
| 677 |
+
basetypes = (Number, bytes, str)
|
| 678 |
+
|
| 679 |
+
info = TiffTags.lookup(tag, self.group)
|
| 680 |
+
values = [value] if isinstance(value, basetypes) else value
|
| 681 |
+
|
| 682 |
+
if tag not in self.tagtype:
|
| 683 |
+
if info.type:
|
| 684 |
+
self.tagtype[tag] = info.type
|
| 685 |
+
else:
|
| 686 |
+
self.tagtype[tag] = TiffTags.UNDEFINED
|
| 687 |
+
if all(isinstance(v, IFDRational) for v in values):
|
| 688 |
+
for v in values:
|
| 689 |
+
assert isinstance(v, IFDRational)
|
| 690 |
+
if v < 0:
|
| 691 |
+
self.tagtype[tag] = TiffTags.SIGNED_RATIONAL
|
| 692 |
+
break
|
| 693 |
+
else:
|
| 694 |
+
self.tagtype[tag] = TiffTags.RATIONAL
|
| 695 |
+
elif all(isinstance(v, int) for v in values):
|
| 696 |
+
short = True
|
| 697 |
+
signed_short = True
|
| 698 |
+
long = True
|
| 699 |
+
for v in values:
|
| 700 |
+
assert isinstance(v, int)
|
| 701 |
+
if short and not (0 <= v < 2**16):
|
| 702 |
+
short = False
|
| 703 |
+
if signed_short and not (-(2**15) < v < 2**15):
|
| 704 |
+
signed_short = False
|
| 705 |
+
if long and v < 0:
|
| 706 |
+
long = False
|
| 707 |
+
if short:
|
| 708 |
+
self.tagtype[tag] = TiffTags.SHORT
|
| 709 |
+
elif signed_short:
|
| 710 |
+
self.tagtype[tag] = TiffTags.SIGNED_SHORT
|
| 711 |
+
elif long:
|
| 712 |
+
self.tagtype[tag] = TiffTags.LONG
|
| 713 |
+
else:
|
| 714 |
+
self.tagtype[tag] = TiffTags.SIGNED_LONG
|
| 715 |
+
elif all(isinstance(v, float) for v in values):
|
| 716 |
+
self.tagtype[tag] = TiffTags.DOUBLE
|
| 717 |
+
elif all(isinstance(v, str) for v in values):
|
| 718 |
+
self.tagtype[tag] = TiffTags.ASCII
|
| 719 |
+
elif all(isinstance(v, bytes) for v in values):
|
| 720 |
+
self.tagtype[tag] = TiffTags.BYTE
|
| 721 |
+
|
| 722 |
+
if self.tagtype[tag] == TiffTags.UNDEFINED:
|
| 723 |
+
values = [
|
| 724 |
+
v.encode("ascii", "replace") if isinstance(v, str) else v
|
| 725 |
+
for v in values
|
| 726 |
+
]
|
| 727 |
+
elif self.tagtype[tag] == TiffTags.RATIONAL:
|
| 728 |
+
values = [float(v) if isinstance(v, int) else v for v in values]
|
| 729 |
+
|
| 730 |
+
is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict)
|
| 731 |
+
if not is_ifd:
|
| 732 |
+
values = tuple(
|
| 733 |
+
info.cvt_enum(value) if isinstance(value, str) else value
|
| 734 |
+
for value in values
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
dest = self._tags_v1 if legacy_api else self._tags_v2
|
| 738 |
+
|
| 739 |
+
# Three branches:
|
| 740 |
+
# Spec'd length == 1, Actual length 1, store as element
|
| 741 |
+
# Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed.
|
| 742 |
+
# No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple.
|
| 743 |
+
# Don't mess with the legacy api, since it's frozen.
|
| 744 |
+
if not is_ifd and (
|
| 745 |
+
(info.length == 1)
|
| 746 |
+
or self.tagtype[tag] == TiffTags.BYTE
|
| 747 |
+
or (info.length is None and len(values) == 1 and not legacy_api)
|
| 748 |
+
):
|
| 749 |
+
# Don't mess with the legacy api, since it's frozen.
|
| 750 |
+
if legacy_api and self.tagtype[tag] in [
|
| 751 |
+
TiffTags.RATIONAL,
|
| 752 |
+
TiffTags.SIGNED_RATIONAL,
|
| 753 |
+
]: # rationals
|
| 754 |
+
values = (values,)
|
| 755 |
+
try:
|
| 756 |
+
(dest[tag],) = values
|
| 757 |
+
except ValueError:
|
| 758 |
+
# We've got a builtin tag with 1 expected entry
|
| 759 |
+
warnings.warn(
|
| 760 |
+
f"Metadata Warning, tag {tag} had too many entries: "
|
| 761 |
+
f"{len(values)}, expected 1"
|
| 762 |
+
)
|
| 763 |
+
dest[tag] = values[0]
|
| 764 |
+
|
| 765 |
+
else:
|
| 766 |
+
# Spec'd length > 1 or undefined
|
| 767 |
+
# Unspec'd, and length > 1
|
| 768 |
+
dest[tag] = values
|
| 769 |
+
|
| 770 |
+
def __delitem__(self, tag: int) -> None:
|
| 771 |
+
self._tags_v2.pop(tag, None)
|
| 772 |
+
self._tags_v1.pop(tag, None)
|
| 773 |
+
self._tagdata.pop(tag, None)
|
| 774 |
+
|
| 775 |
+
def __iter__(self) -> Iterator[int]:
|
| 776 |
+
return iter(set(self._tagdata) | set(self._tags_v2))
|
| 777 |
+
|
| 778 |
+
def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]:
|
| 779 |
+
return struct.unpack(self._endian + fmt, data)
|
| 780 |
+
|
| 781 |
+
def _pack(self, fmt: str, *values: Any) -> bytes:
|
| 782 |
+
return struct.pack(self._endian + fmt, *values)
|
| 783 |
+
|
| 784 |
+
list(
|
| 785 |
+
map(
|
| 786 |
+
_register_basic,
|
| 787 |
+
[
|
| 788 |
+
(TiffTags.SHORT, "H", "short"),
|
| 789 |
+
(TiffTags.LONG, "L", "long"),
|
| 790 |
+
(TiffTags.SIGNED_BYTE, "b", "signed byte"),
|
| 791 |
+
(TiffTags.SIGNED_SHORT, "h", "signed short"),
|
| 792 |
+
(TiffTags.SIGNED_LONG, "l", "signed long"),
|
| 793 |
+
(TiffTags.FLOAT, "f", "float"),
|
| 794 |
+
(TiffTags.DOUBLE, "d", "double"),
|
| 795 |
+
(TiffTags.IFD, "L", "long"),
|
| 796 |
+
(TiffTags.LONG8, "Q", "long8"),
|
| 797 |
+
],
|
| 798 |
+
)
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
@_register_loader(1, 1) # Basic type, except for the legacy API.
|
| 802 |
+
def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes:
|
| 803 |
+
return data
|
| 804 |
+
|
| 805 |
+
@_register_writer(1) # Basic type, except for the legacy API.
|
| 806 |
+
def write_byte(self, data: bytes | int | IFDRational) -> bytes:
|
| 807 |
+
if isinstance(data, IFDRational):
|
| 808 |
+
data = int(data)
|
| 809 |
+
if isinstance(data, int):
|
| 810 |
+
data = bytes((data,))
|
| 811 |
+
return data
|
| 812 |
+
|
| 813 |
+
@_register_loader(2, 1)
|
| 814 |
+
def load_string(self, data: bytes, legacy_api: bool = True) -> str:
|
| 815 |
+
if data.endswith(b"\0"):
|
| 816 |
+
data = data[:-1]
|
| 817 |
+
return data.decode("latin-1", "replace")
|
| 818 |
+
|
| 819 |
+
@_register_writer(2)
|
| 820 |
+
def write_string(self, value: str | bytes | int) -> bytes:
|
| 821 |
+
# remerge of https://github.com/python-pillow/Pillow/pull/1416
|
| 822 |
+
if isinstance(value, int):
|
| 823 |
+
value = str(value)
|
| 824 |
+
if not isinstance(value, bytes):
|
| 825 |
+
value = value.encode("ascii", "replace")
|
| 826 |
+
return value + b"\0"
|
| 827 |
+
|
| 828 |
+
@_register_loader(5, 8)
|
| 829 |
+
def load_rational(
|
| 830 |
+
self, data: bytes, legacy_api: bool = True
|
| 831 |
+
) -> tuple[tuple[int, int] | IFDRational, ...]:
|
| 832 |
+
vals = self._unpack(f"{len(data) // 4}L", data)
|
| 833 |
+
|
| 834 |
+
def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
|
| 835 |
+
return (a, b) if legacy_api else IFDRational(a, b)
|
| 836 |
+
|
| 837 |
+
return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
|
| 838 |
+
|
| 839 |
+
@_register_writer(5)
|
| 840 |
+
def write_rational(self, *values: IFDRational) -> bytes:
|
| 841 |
+
return b"".join(
|
| 842 |
+
self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
@_register_loader(7, 1)
|
| 846 |
+
def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes:
|
| 847 |
+
return data
|
| 848 |
+
|
| 849 |
+
@_register_writer(7)
|
| 850 |
+
def write_undefined(self, value: bytes | int | IFDRational) -> bytes:
|
| 851 |
+
if isinstance(value, IFDRational):
|
| 852 |
+
value = int(value)
|
| 853 |
+
if isinstance(value, int):
|
| 854 |
+
value = str(value).encode("ascii", "replace")
|
| 855 |
+
return value
|
| 856 |
+
|
| 857 |
+
@_register_loader(10, 8)
|
| 858 |
+
def load_signed_rational(
|
| 859 |
+
self, data: bytes, legacy_api: bool = True
|
| 860 |
+
) -> tuple[tuple[int, int] | IFDRational, ...]:
|
| 861 |
+
vals = self._unpack(f"{len(data) // 4}l", data)
|
| 862 |
+
|
| 863 |
+
def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
|
| 864 |
+
return (a, b) if legacy_api else IFDRational(a, b)
|
| 865 |
+
|
| 866 |
+
return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
|
| 867 |
+
|
| 868 |
+
@_register_writer(10)
|
| 869 |
+
def write_signed_rational(self, *values: IFDRational) -> bytes:
|
| 870 |
+
return b"".join(
|
| 871 |
+
self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31)))
|
| 872 |
+
for frac in values
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
def _ensure_read(self, fp: IO[bytes], size: int) -> bytes:
|
| 876 |
+
ret = fp.read(size)
|
| 877 |
+
if len(ret) != size:
|
| 878 |
+
msg = (
|
| 879 |
+
"Corrupt EXIF data. "
|
| 880 |
+
f"Expecting to read {size} bytes but only got {len(ret)}. "
|
| 881 |
+
)
|
| 882 |
+
raise OSError(msg)
|
| 883 |
+
return ret
|
| 884 |
+
|
| 885 |
+
def load(self, fp: IO[bytes]) -> None:
|
| 886 |
+
self.reset()
|
| 887 |
+
self._offset = fp.tell()
|
| 888 |
+
|
| 889 |
+
try:
|
| 890 |
+
tag_count = (
|
| 891 |
+
self._unpack("Q", self._ensure_read(fp, 8))
|
| 892 |
+
if self._bigtiff
|
| 893 |
+
else self._unpack("H", self._ensure_read(fp, 2))
|
| 894 |
+
)[0]
|
| 895 |
+
for i in range(tag_count):
|
| 896 |
+
tag, typ, count, data = (
|
| 897 |
+
self._unpack("HHQ8s", self._ensure_read(fp, 20))
|
| 898 |
+
if self._bigtiff
|
| 899 |
+
else self._unpack("HHL4s", self._ensure_read(fp, 12))
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
tagname = TiffTags.lookup(tag, self.group).name
|
| 903 |
+
typname = TYPES.get(typ, "unknown")
|
| 904 |
+
msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})"
|
| 905 |
+
|
| 906 |
+
try:
|
| 907 |
+
unit_size, handler = self._load_dispatch[typ]
|
| 908 |
+
except KeyError:
|
| 909 |
+
logger.debug("%s - unsupported type %s", msg, typ)
|
| 910 |
+
continue # ignore unsupported type
|
| 911 |
+
size = count * unit_size
|
| 912 |
+
if size > (8 if self._bigtiff else 4):
|
| 913 |
+
here = fp.tell()
|
| 914 |
+
(offset,) = self._unpack("Q" if self._bigtiff else "L", data)
|
| 915 |
+
msg += f" Tag Location: {here} - Data Location: {offset}"
|
| 916 |
+
fp.seek(offset)
|
| 917 |
+
data = ImageFile._safe_read(fp, size)
|
| 918 |
+
fp.seek(here)
|
| 919 |
+
else:
|
| 920 |
+
data = data[:size]
|
| 921 |
+
|
| 922 |
+
if len(data) != size:
|
| 923 |
+
warnings.warn(
|
| 924 |
+
"Possibly corrupt EXIF data. "
|
| 925 |
+
f"Expecting to read {size} bytes but only got {len(data)}."
|
| 926 |
+
f" Skipping tag {tag}"
|
| 927 |
+
)
|
| 928 |
+
logger.debug(msg)
|
| 929 |
+
continue
|
| 930 |
+
|
| 931 |
+
if not data:
|
| 932 |
+
logger.debug(msg)
|
| 933 |
+
continue
|
| 934 |
+
|
| 935 |
+
self._tagdata[tag] = data
|
| 936 |
+
self.tagtype[tag] = typ
|
| 937 |
+
|
| 938 |
+
msg += " - value: "
|
| 939 |
+
msg += f"<table: {size} bytes>" if size > 32 else repr(data)
|
| 940 |
+
|
| 941 |
+
logger.debug(msg)
|
| 942 |
+
|
| 943 |
+
(self.next,) = (
|
| 944 |
+
self._unpack("Q", self._ensure_read(fp, 8))
|
| 945 |
+
if self._bigtiff
|
| 946 |
+
else self._unpack("L", self._ensure_read(fp, 4))
|
| 947 |
+
)
|
| 948 |
+
except OSError as msg:
|
| 949 |
+
warnings.warn(str(msg))
|
| 950 |
+
return
|
| 951 |
+
|
| 952 |
+
def _get_ifh(self) -> bytes:
|
| 953 |
+
ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42)
|
| 954 |
+
if self._bigtiff:
|
| 955 |
+
ifh += self._pack("HH", 8, 0)
|
| 956 |
+
ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8)
|
| 957 |
+
|
| 958 |
+
return ifh
|
| 959 |
+
|
| 960 |
+
def tobytes(self, offset: int = 0) -> bytes:
|
| 961 |
+
# FIXME What about tagdata?
|
| 962 |
+
result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2))
|
| 963 |
+
|
| 964 |
+
entries: list[tuple[int, int, int, bytes, bytes]] = []
|
| 965 |
+
|
| 966 |
+
fmt = "Q" if self._bigtiff else "L"
|
| 967 |
+
fmt_size = 8 if self._bigtiff else 4
|
| 968 |
+
offset += (
|
| 969 |
+
len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size
|
| 970 |
+
)
|
| 971 |
+
stripoffsets = None
|
| 972 |
+
|
| 973 |
+
# pass 1: convert tags to binary format
|
| 974 |
+
# always write tags in ascending order
|
| 975 |
+
for tag, value in sorted(self._tags_v2.items()):
|
| 976 |
+
if tag == STRIPOFFSETS:
|
| 977 |
+
stripoffsets = len(entries)
|
| 978 |
+
typ = self.tagtype[tag]
|
| 979 |
+
logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))
|
| 980 |
+
is_ifd = typ == TiffTags.LONG and isinstance(value, dict)
|
| 981 |
+
if is_ifd:
|
| 982 |
+
ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag)
|
| 983 |
+
values = self._tags_v2[tag]
|
| 984 |
+
for ifd_tag, ifd_value in values.items():
|
| 985 |
+
ifd[ifd_tag] = ifd_value
|
| 986 |
+
data = ifd.tobytes(offset)
|
| 987 |
+
else:
|
| 988 |
+
values = value if isinstance(value, tuple) else (value,)
|
| 989 |
+
data = self._write_dispatch[typ](self, *values)
|
| 990 |
+
|
| 991 |
+
tagname = TiffTags.lookup(tag, self.group).name
|
| 992 |
+
typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")
|
| 993 |
+
msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: "
|
| 994 |
+
msg += f"<table: {len(data)} bytes>" if len(data) >= 16 else str(values)
|
| 995 |
+
logger.debug(msg)
|
| 996 |
+
|
| 997 |
+
# count is sum of lengths for string and arbitrary data
|
| 998 |
+
if is_ifd:
|
| 999 |
+
count = 1
|
| 1000 |
+
elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
|
| 1001 |
+
count = len(data)
|
| 1002 |
+
else:
|
| 1003 |
+
count = len(values)
|
| 1004 |
+
# figure out if data fits into the entry
|
| 1005 |
+
if len(data) <= fmt_size:
|
| 1006 |
+
entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b""))
|
| 1007 |
+
else:
|
| 1008 |
+
entries.append((tag, typ, count, self._pack(fmt, offset), data))
|
| 1009 |
+
offset += (len(data) + 1) // 2 * 2 # pad to word
|
| 1010 |
+
|
| 1011 |
+
# update strip offset data to point beyond auxiliary data
|
| 1012 |
+
if stripoffsets is not None:
|
| 1013 |
+
tag, typ, count, value, data = entries[stripoffsets]
|
| 1014 |
+
if data:
|
| 1015 |
+
size, handler = self._load_dispatch[typ]
|
| 1016 |
+
values = [val + offset for val in handler(self, data, self.legacy_api)]
|
| 1017 |
+
data = self._write_dispatch[typ](self, *values)
|
| 1018 |
+
else:
|
| 1019 |
+
value = self._pack(fmt, self._unpack(fmt, value)[0] + offset)
|
| 1020 |
+
entries[stripoffsets] = tag, typ, count, value, data
|
| 1021 |
+
|
| 1022 |
+
# pass 2: write entries to file
|
| 1023 |
+
for tag, typ, count, value, data in entries:
|
| 1024 |
+
logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))
|
| 1025 |
+
result += self._pack(
|
| 1026 |
+
"HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value
|
| 1027 |
+
)
|
| 1028 |
+
|
| 1029 |
+
# -- overwrite here for multi-page --
|
| 1030 |
+
result += self._pack(fmt, 0) # end of entries
|
| 1031 |
+
|
| 1032 |
+
# pass 3: write auxiliary data to file
|
| 1033 |
+
for tag, typ, count, value, data in entries:
|
| 1034 |
+
result += data
|
| 1035 |
+
if len(data) & 1:
|
| 1036 |
+
result += b"\0"
|
| 1037 |
+
|
| 1038 |
+
return result
|
| 1039 |
+
|
| 1040 |
+
def save(self, fp: IO[bytes]) -> int:
|
| 1041 |
+
if fp.tell() == 0: # skip TIFF header on subsequent pages
|
| 1042 |
+
fp.write(self._get_ifh())
|
| 1043 |
+
|
| 1044 |
+
offset = fp.tell()
|
| 1045 |
+
result = self.tobytes(offset)
|
| 1046 |
+
fp.write(result)
|
| 1047 |
+
return offset + len(result)
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
ImageFileDirectory_v2._load_dispatch = _load_dispatch
|
| 1051 |
+
ImageFileDirectory_v2._write_dispatch = _write_dispatch
|
| 1052 |
+
for idx, name in TYPES.items():
|
| 1053 |
+
name = name.replace(" ", "_")
|
| 1054 |
+
setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])
|
| 1055 |
+
setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])
|
| 1056 |
+
del _load_dispatch, _write_dispatch, idx, name
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
# Legacy ImageFileDirectory support.
|
| 1060 |
+
class ImageFileDirectory_v1(ImageFileDirectory_v2):
|
| 1061 |
+
"""This class represents the **legacy** interface to a TIFF tag directory.
|
| 1062 |
+
|
| 1063 |
+
Exposes a dictionary interface of the tags in the directory::
|
| 1064 |
+
|
| 1065 |
+
ifd = ImageFileDirectory_v1()
|
| 1066 |
+
ifd[key] = 'Some Data'
|
| 1067 |
+
ifd.tagtype[key] = TiffTags.ASCII
|
| 1068 |
+
print(ifd[key])
|
| 1069 |
+
('Some Data',)
|
| 1070 |
+
|
| 1071 |
+
Also contains a dictionary of tag types as read from the tiff image file,
|
| 1072 |
+
:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.
|
| 1073 |
+
|
| 1074 |
+
Values are returned as a tuple.
|
| 1075 |
+
|
| 1076 |
+
.. deprecated:: 3.0.0
|
| 1077 |
+
"""
|
| 1078 |
+
|
| 1079 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 1080 |
+
super().__init__(*args, **kwargs)
|
| 1081 |
+
self._legacy_api = True
|
| 1082 |
+
|
| 1083 |
+
tags = property(lambda self: self._tags_v1)
|
| 1084 |
+
tagdata = property(lambda self: self._tagdata)
|
| 1085 |
+
|
| 1086 |
+
# defined in ImageFileDirectory_v2
|
| 1087 |
+
tagtype: dict[int, int]
|
| 1088 |
+
"""Dictionary of tag types"""
|
| 1089 |
+
|
| 1090 |
+
@classmethod
|
| 1091 |
+
def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1:
|
| 1092 |
+
"""Returns an
|
| 1093 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1094 |
+
instance with the same data as is contained in the original
|
| 1095 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1096 |
+
instance.
|
| 1097 |
+
|
| 1098 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1099 |
+
|
| 1100 |
+
"""
|
| 1101 |
+
|
| 1102 |
+
ifd = cls(prefix=original.prefix)
|
| 1103 |
+
ifd._tagdata = original._tagdata
|
| 1104 |
+
ifd.tagtype = original.tagtype
|
| 1105 |
+
ifd.next = original.next # an indicator for multipage tiffs
|
| 1106 |
+
return ifd
|
| 1107 |
+
|
| 1108 |
+
def to_v2(self) -> ImageFileDirectory_v2:
|
| 1109 |
+
"""Returns an
|
| 1110 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1111 |
+
instance with the same data as is contained in the original
|
| 1112 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1113 |
+
instance.
|
| 1114 |
+
|
| 1115 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1116 |
+
|
| 1117 |
+
"""
|
| 1118 |
+
|
| 1119 |
+
ifd = ImageFileDirectory_v2(prefix=self.prefix)
|
| 1120 |
+
ifd._tagdata = dict(self._tagdata)
|
| 1121 |
+
ifd.tagtype = dict(self.tagtype)
|
| 1122 |
+
ifd._tags_v2 = dict(self._tags_v2)
|
| 1123 |
+
return ifd
|
| 1124 |
+
|
| 1125 |
+
def __contains__(self, tag: object) -> bool:
|
| 1126 |
+
return tag in self._tags_v1 or tag in self._tagdata
|
| 1127 |
+
|
| 1128 |
+
def __len__(self) -> int:
|
| 1129 |
+
return len(set(self._tagdata) | set(self._tags_v1))
|
| 1130 |
+
|
| 1131 |
+
def __iter__(self) -> Iterator[int]:
|
| 1132 |
+
return iter(set(self._tagdata) | set(self._tags_v1))
|
| 1133 |
+
|
| 1134 |
+
def __setitem__(self, tag: int, value: Any) -> None:
|
| 1135 |
+
for legacy_api in (False, True):
|
| 1136 |
+
self._setitem(tag, value, legacy_api)
|
| 1137 |
+
|
| 1138 |
+
def __getitem__(self, tag: int) -> Any:
|
| 1139 |
+
if tag not in self._tags_v1: # unpack on the fly
|
| 1140 |
+
data = self._tagdata[tag]
|
| 1141 |
+
typ = self.tagtype[tag]
|
| 1142 |
+
size, handler = self._load_dispatch[typ]
|
| 1143 |
+
for legacy in (False, True):
|
| 1144 |
+
self._setitem(tag, handler(self, data, legacy), legacy)
|
| 1145 |
+
val = self._tags_v1[tag]
|
| 1146 |
+
if not isinstance(val, (tuple, bytes)):
|
| 1147 |
+
val = (val,)
|
| 1148 |
+
return val
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
# undone -- switch this pointer
|
| 1152 |
+
ImageFileDirectory = ImageFileDirectory_v1
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
##
|
| 1156 |
+
# Image plugin for TIFF files.
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
class TiffImageFile(ImageFile.ImageFile):
|
| 1160 |
+
format = "TIFF"
|
| 1161 |
+
format_description = "Adobe TIFF"
|
| 1162 |
+
_close_exclusive_fp_after_loading = False
|
| 1163 |
+
|
| 1164 |
+
def __init__(
|
| 1165 |
+
self,
|
| 1166 |
+
fp: StrOrBytesPath | IO[bytes],
|
| 1167 |
+
filename: str | bytes | None = None,
|
| 1168 |
+
) -> None:
|
| 1169 |
+
self.tag_v2: ImageFileDirectory_v2
|
| 1170 |
+
""" Image file directory (tag dictionary) """
|
| 1171 |
+
|
| 1172 |
+
self.tag: ImageFileDirectory_v1
|
| 1173 |
+
""" Legacy tag entries """
|
| 1174 |
+
|
| 1175 |
+
super().__init__(fp, filename)
|
| 1176 |
+
|
| 1177 |
+
def _open(self) -> None:
|
| 1178 |
+
"""Open the first image in a TIFF file"""
|
| 1179 |
+
|
| 1180 |
+
# Header
|
| 1181 |
+
assert self.fp is not None
|
| 1182 |
+
ifh = self.fp.read(8)
|
| 1183 |
+
if ifh[2] == 43:
|
| 1184 |
+
ifh += self.fp.read(8)
|
| 1185 |
+
|
| 1186 |
+
self.tag_v2 = ImageFileDirectory_v2(ifh)
|
| 1187 |
+
|
| 1188 |
+
# setup frame pointers
|
| 1189 |
+
self.__first = self.__next = self.tag_v2.next
|
| 1190 |
+
self.__frame = -1
|
| 1191 |
+
self._fp = self.fp
|
| 1192 |
+
self._frame_pos: list[int] = []
|
| 1193 |
+
self._n_frames: int | None = None
|
| 1194 |
+
|
| 1195 |
+
logger.debug("*** TiffImageFile._open ***")
|
| 1196 |
+
logger.debug("- __first: %s", self.__first)
|
| 1197 |
+
logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)
|
| 1198 |
+
|
| 1199 |
+
# and load the first frame
|
| 1200 |
+
self._seek(0)
|
| 1201 |
+
|
| 1202 |
+
@property
|
| 1203 |
+
def n_frames(self) -> int:
|
| 1204 |
+
current_n_frames = self._n_frames
|
| 1205 |
+
if current_n_frames is None:
|
| 1206 |
+
current = self.tell()
|
| 1207 |
+
self._seek(len(self._frame_pos))
|
| 1208 |
+
while self._n_frames is None:
|
| 1209 |
+
self._seek(self.tell() + 1)
|
| 1210 |
+
self.seek(current)
|
| 1211 |
+
assert self._n_frames is not None
|
| 1212 |
+
return self._n_frames
|
| 1213 |
+
|
| 1214 |
+
def seek(self, frame: int) -> None:
|
| 1215 |
+
"""Select a given frame as current image"""
|
| 1216 |
+
if not self._seek_check(frame):
|
| 1217 |
+
return
|
| 1218 |
+
self._seek(frame)
|
| 1219 |
+
if self._im is not None and (
|
| 1220 |
+
self.im.size != self._tile_size
|
| 1221 |
+
or self.im.mode != self.mode
|
| 1222 |
+
or self.readonly
|
| 1223 |
+
):
|
| 1224 |
+
self._im = None
|
| 1225 |
+
|
| 1226 |
+
def _seek(self, frame: int) -> None:
|
| 1227 |
+
if isinstance(self._fp, DeferredError):
|
| 1228 |
+
raise self._fp.ex
|
| 1229 |
+
self.fp = self._fp
|
| 1230 |
+
|
| 1231 |
+
while len(self._frame_pos) <= frame:
|
| 1232 |
+
if not self.__next:
|
| 1233 |
+
msg = "no more images in TIFF file"
|
| 1234 |
+
raise EOFError(msg)
|
| 1235 |
+
logger.debug(
|
| 1236 |
+
"Seeking to frame %s, on frame %s, __next %s, location: %s",
|
| 1237 |
+
frame,
|
| 1238 |
+
self.__frame,
|
| 1239 |
+
self.__next,
|
| 1240 |
+
self.fp.tell(),
|
| 1241 |
+
)
|
| 1242 |
+
if self.__next >= 2**63:
|
| 1243 |
+
msg = "Unable to seek to frame"
|
| 1244 |
+
raise ValueError(msg)
|
| 1245 |
+
self.fp.seek(self.__next)
|
| 1246 |
+
self._frame_pos.append(self.__next)
|
| 1247 |
+
logger.debug("Loading tags, location: %s", self.fp.tell())
|
| 1248 |
+
self.tag_v2.load(self.fp)
|
| 1249 |
+
if self.tag_v2.next in self._frame_pos:
|
| 1250 |
+
# This IFD has already been processed
|
| 1251 |
+
# Declare this to be the end of the image
|
| 1252 |
+
self.__next = 0
|
| 1253 |
+
else:
|
| 1254 |
+
self.__next = self.tag_v2.next
|
| 1255 |
+
if self.__next == 0:
|
| 1256 |
+
self._n_frames = frame + 1
|
| 1257 |
+
if len(self._frame_pos) == 1:
|
| 1258 |
+
self.is_animated = self.__next != 0
|
| 1259 |
+
self.__frame += 1
|
| 1260 |
+
self.fp.seek(self._frame_pos[frame])
|
| 1261 |
+
self.tag_v2.load(self.fp)
|
| 1262 |
+
if XMP in self.tag_v2:
|
| 1263 |
+
xmp = self.tag_v2[XMP]
|
| 1264 |
+
if isinstance(xmp, tuple) and len(xmp) == 1:
|
| 1265 |
+
xmp = xmp[0]
|
| 1266 |
+
self.info["xmp"] = xmp
|
| 1267 |
+
elif "xmp" in self.info:
|
| 1268 |
+
del self.info["xmp"]
|
| 1269 |
+
self._reload_exif()
|
| 1270 |
+
# fill the legacy tag/ifd entries
|
| 1271 |
+
self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
|
| 1272 |
+
self.__frame = frame
|
| 1273 |
+
self._setup()
|
| 1274 |
+
|
| 1275 |
+
def tell(self) -> int:
|
| 1276 |
+
"""Return the current frame number"""
|
| 1277 |
+
return self.__frame
|
| 1278 |
+
|
| 1279 |
+
def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]:
|
| 1280 |
+
"""
|
| 1281 |
+
Returns a dictionary of Photoshop "Image Resource Blocks".
|
| 1282 |
+
The keys are the image resource ID. For more information, see
|
| 1283 |
+
https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727
|
| 1284 |
+
|
| 1285 |
+
:returns: Photoshop "Image Resource Blocks" in a dictionary.
|
| 1286 |
+
"""
|
| 1287 |
+
blocks = {}
|
| 1288 |
+
val = self.tag_v2.get(ExifTags.Base.ImageResources)
|
| 1289 |
+
if val:
|
| 1290 |
+
while val.startswith(b"8BIM"):
|
| 1291 |
+
id = i16(val[4:6])
|
| 1292 |
+
n = math.ceil((val[6] + 1) / 2) * 2
|
| 1293 |
+
size = i32(val[6 + n : 10 + n])
|
| 1294 |
+
data = val[10 + n : 10 + n + size]
|
| 1295 |
+
blocks[id] = {"data": data}
|
| 1296 |
+
|
| 1297 |
+
val = val[math.ceil((10 + n + size) / 2) * 2 :]
|
| 1298 |
+
return blocks
|
| 1299 |
+
|
| 1300 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 1301 |
+
if self.tile and self.use_load_libtiff:
|
| 1302 |
+
return self._load_libtiff()
|
| 1303 |
+
return super().load()
|
| 1304 |
+
|
| 1305 |
+
def load_prepare(self) -> None:
|
| 1306 |
+
if self._im is None:
|
| 1307 |
+
Image._decompression_bomb_check(self._tile_size)
|
| 1308 |
+
self.im = Image.core.new(self.mode, self._tile_size)
|
| 1309 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 1310 |
+
|
| 1311 |
+
def load_end(self) -> None:
|
| 1312 |
+
# allow closing if we're on the first frame, there's no next
|
| 1313 |
+
# This is the ImageFile.load path only, libtiff specific below.
|
| 1314 |
+
if not self.is_animated:
|
| 1315 |
+
self._close_exclusive_fp_after_loading = True
|
| 1316 |
+
|
| 1317 |
+
# load IFD data from fp before it is closed
|
| 1318 |
+
exif = self.getexif()
|
| 1319 |
+
for key in TiffTags.TAGS_V2_GROUPS:
|
| 1320 |
+
if key not in exif:
|
| 1321 |
+
continue
|
| 1322 |
+
exif.get_ifd(key)
|
| 1323 |
+
|
| 1324 |
+
ImageOps.exif_transpose(self, in_place=True)
|
| 1325 |
+
if ExifTags.Base.Orientation in self.tag_v2:
|
| 1326 |
+
del self.tag_v2[ExifTags.Base.Orientation]
|
| 1327 |
+
|
| 1328 |
+
def _load_libtiff(self) -> Image.core.PixelAccess | None:
|
| 1329 |
+
"""Overload method triggered when we detect a compressed tiff
|
| 1330 |
+
Calls out to libtiff"""
|
| 1331 |
+
|
| 1332 |
+
Image.Image.load(self)
|
| 1333 |
+
|
| 1334 |
+
self.load_prepare()
|
| 1335 |
+
|
| 1336 |
+
if not len(self.tile) == 1:
|
| 1337 |
+
msg = "Not exactly one tile"
|
| 1338 |
+
raise OSError(msg)
|
| 1339 |
+
|
| 1340 |
+
# (self._compression, (extents tuple),
|
| 1341 |
+
# 0, (rawmode, self._compression, fp))
|
| 1342 |
+
extents = self.tile[0][1]
|
| 1343 |
+
args = self.tile[0][3]
|
| 1344 |
+
|
| 1345 |
+
# To be nice on memory footprint, if there's a
|
| 1346 |
+
# file descriptor, use that instead of reading
|
| 1347 |
+
# into a string in python.
|
| 1348 |
+
assert self.fp is not None
|
| 1349 |
+
try:
|
| 1350 |
+
fp = hasattr(self.fp, "fileno") and self.fp.fileno()
|
| 1351 |
+
# flush the file descriptor, prevents error on pypy 2.4+
|
| 1352 |
+
# should also eliminate the need for fp.tell
|
| 1353 |
+
# in _seek
|
| 1354 |
+
if hasattr(self.fp, "flush"):
|
| 1355 |
+
self.fp.flush()
|
| 1356 |
+
except OSError:
|
| 1357 |
+
# io.BytesIO have a fileno, but returns an OSError if
|
| 1358 |
+
# it doesn't use a file descriptor.
|
| 1359 |
+
fp = False
|
| 1360 |
+
|
| 1361 |
+
if fp:
|
| 1362 |
+
assert isinstance(args, tuple)
|
| 1363 |
+
args_list = list(args)
|
| 1364 |
+
args_list[2] = fp
|
| 1365 |
+
args = tuple(args_list)
|
| 1366 |
+
|
| 1367 |
+
decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)
|
| 1368 |
+
try:
|
| 1369 |
+
decoder.setimage(self.im, extents)
|
| 1370 |
+
except ValueError as e:
|
| 1371 |
+
msg = "Couldn't set the image"
|
| 1372 |
+
raise OSError(msg) from e
|
| 1373 |
+
|
| 1374 |
+
close_self_fp = self._exclusive_fp and not self.is_animated
|
| 1375 |
+
if hasattr(self.fp, "getvalue"):
|
| 1376 |
+
# We've got a stringio like thing passed in. Yay for all in memory.
|
| 1377 |
+
# The decoder needs the entire file in one shot, so there's not
|
| 1378 |
+
# a lot we can do here other than give it the entire file.
|
| 1379 |
+
# unless we could do something like get the address of the
|
| 1380 |
+
# underlying string for stringio.
|
| 1381 |
+
#
|
| 1382 |
+
# Rearranging for supporting byteio items, since they have a fileno
|
| 1383 |
+
# that returns an OSError if there's no underlying fp. Easier to
|
| 1384 |
+
# deal with here by reordering.
|
| 1385 |
+
logger.debug("have getvalue. just sending in a string from getvalue")
|
| 1386 |
+
n, err = decoder.decode(self.fp.getvalue())
|
| 1387 |
+
elif fp:
|
| 1388 |
+
# we've got a actual file on disk, pass in the fp.
|
| 1389 |
+
logger.debug("have fileno, calling fileno version of the decoder.")
|
| 1390 |
+
if not close_self_fp:
|
| 1391 |
+
self.fp.seek(0)
|
| 1392 |
+
# Save and restore the file position, because libtiff will move it
|
| 1393 |
+
# outside of the Python runtime, and that will confuse
|
| 1394 |
+
# io.BufferedReader and possible others.
|
| 1395 |
+
# NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(),
|
| 1396 |
+
# because the buffer read head already may not equal the actual
|
| 1397 |
+
# file position, and fp.seek() may just adjust it's internal
|
| 1398 |
+
# pointer and not actually seek the OS file handle.
|
| 1399 |
+
pos = os.lseek(fp, 0, os.SEEK_CUR)
|
| 1400 |
+
# 4 bytes, otherwise the trace might error out
|
| 1401 |
+
n, err = decoder.decode(b"fpfp")
|
| 1402 |
+
os.lseek(fp, pos, os.SEEK_SET)
|
| 1403 |
+
else:
|
| 1404 |
+
# we have something else.
|
| 1405 |
+
logger.debug("don't have fileno or getvalue. just reading")
|
| 1406 |
+
self.fp.seek(0)
|
| 1407 |
+
# UNDONE -- so much for that buffer size thing.
|
| 1408 |
+
n, err = decoder.decode(self.fp.read())
|
| 1409 |
+
|
| 1410 |
+
self.tile = []
|
| 1411 |
+
self.readonly = 0
|
| 1412 |
+
|
| 1413 |
+
self.load_end()
|
| 1414 |
+
|
| 1415 |
+
if close_self_fp:
|
| 1416 |
+
self.fp.close()
|
| 1417 |
+
self.fp = None # might be shared
|
| 1418 |
+
|
| 1419 |
+
if err < 0:
|
| 1420 |
+
msg = f"decoder error {err}"
|
| 1421 |
+
raise OSError(msg)
|
| 1422 |
+
|
| 1423 |
+
return Image.Image.load(self)
|
| 1424 |
+
|
| 1425 |
+
def _setup(self) -> None:
|
| 1426 |
+
"""Setup this image object based on current tags"""
|
| 1427 |
+
|
| 1428 |
+
if 0xBC01 in self.tag_v2:
|
| 1429 |
+
msg = "Windows Media Photo files not yet supported"
|
| 1430 |
+
raise OSError(msg)
|
| 1431 |
+
|
| 1432 |
+
# extract relevant tags
|
| 1433 |
+
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
|
| 1434 |
+
self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
|
| 1435 |
+
|
| 1436 |
+
# photometric is a required tag, but not everyone is reading
|
| 1437 |
+
# the specification
|
| 1438 |
+
photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
|
| 1439 |
+
|
| 1440 |
+
# old style jpeg compression images most certainly are YCbCr
|
| 1441 |
+
if self._compression == "tiff_jpeg":
|
| 1442 |
+
photo = 6
|
| 1443 |
+
|
| 1444 |
+
fillorder = self.tag_v2.get(FILLORDER, 1)
|
| 1445 |
+
|
| 1446 |
+
logger.debug("*** Summary ***")
|
| 1447 |
+
logger.debug("- compression: %s", self._compression)
|
| 1448 |
+
logger.debug("- photometric_interpretation: %s", photo)
|
| 1449 |
+
logger.debug("- planar_configuration: %s", self._planar_configuration)
|
| 1450 |
+
logger.debug("- fill_order: %s", fillorder)
|
| 1451 |
+
logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING))
|
| 1452 |
+
|
| 1453 |
+
# size
|
| 1454 |
+
try:
|
| 1455 |
+
xsize = self.tag_v2[IMAGEWIDTH]
|
| 1456 |
+
ysize = self.tag_v2[IMAGELENGTH]
|
| 1457 |
+
except KeyError as e:
|
| 1458 |
+
msg = "Missing dimensions"
|
| 1459 |
+
raise TypeError(msg) from e
|
| 1460 |
+
if not isinstance(xsize, int) or not isinstance(ysize, int):
|
| 1461 |
+
msg = "Invalid dimensions"
|
| 1462 |
+
raise ValueError(msg)
|
| 1463 |
+
self._tile_size = xsize, ysize
|
| 1464 |
+
orientation = self.tag_v2.get(ExifTags.Base.Orientation)
|
| 1465 |
+
if orientation in (5, 6, 7, 8):
|
| 1466 |
+
self._size = ysize, xsize
|
| 1467 |
+
else:
|
| 1468 |
+
self._size = xsize, ysize
|
| 1469 |
+
|
| 1470 |
+
logger.debug("- size: %s", self.size)
|
| 1471 |
+
|
| 1472 |
+
sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))
|
| 1473 |
+
if len(sample_format) > 1 and max(sample_format) == min(sample_format) == 1:
|
| 1474 |
+
# SAMPLEFORMAT is properly per band, so an RGB image will
|
| 1475 |
+
# be (1,1,1). But, we don't support per band pixel types,
|
| 1476 |
+
# and anything more than one band is a uint8. So, just
|
| 1477 |
+
# take the first element. Revisit this if adding support
|
| 1478 |
+
# for more exotic images.
|
| 1479 |
+
sample_format = (1,)
|
| 1480 |
+
|
| 1481 |
+
bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
|
| 1482 |
+
extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
|
| 1483 |
+
if photo in (2, 6, 8): # RGB, YCbCr, LAB
|
| 1484 |
+
bps_count = 3
|
| 1485 |
+
elif photo == 5: # CMYK
|
| 1486 |
+
bps_count = 4
|
| 1487 |
+
else:
|
| 1488 |
+
bps_count = 1
|
| 1489 |
+
bps_count += len(extra_tuple)
|
| 1490 |
+
bps_actual_count = len(bps_tuple)
|
| 1491 |
+
samples_per_pixel = self.tag_v2.get(
|
| 1492 |
+
SAMPLESPERPIXEL,
|
| 1493 |
+
3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
|
| 1494 |
+
)
|
| 1495 |
+
|
| 1496 |
+
if samples_per_pixel > MAX_SAMPLESPERPIXEL:
|
| 1497 |
+
# DOS check, samples_per_pixel can be a Long, and we extend the tuple below
|
| 1498 |
+
logger.error(
|
| 1499 |
+
"More samples per pixel than can be decoded: %s", samples_per_pixel
|
| 1500 |
+
)
|
| 1501 |
+
msg = "Invalid value for samples per pixel"
|
| 1502 |
+
raise SyntaxError(msg)
|
| 1503 |
+
|
| 1504 |
+
if samples_per_pixel < bps_actual_count:
|
| 1505 |
+
# If a file has more values in bps_tuple than expected,
|
| 1506 |
+
# remove the excess.
|
| 1507 |
+
bps_tuple = bps_tuple[:samples_per_pixel]
|
| 1508 |
+
elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:
|
| 1509 |
+
# If a file has only one value in bps_tuple, when it should have more,
|
| 1510 |
+
# presume it is the same number of bits for all of the samples.
|
| 1511 |
+
bps_tuple = bps_tuple * samples_per_pixel
|
| 1512 |
+
|
| 1513 |
+
if len(bps_tuple) != samples_per_pixel:
|
| 1514 |
+
msg = "unknown data organization"
|
| 1515 |
+
raise SyntaxError(msg)
|
| 1516 |
+
|
| 1517 |
+
# mode: check photometric interpretation and bits per pixel
|
| 1518 |
+
key = (
|
| 1519 |
+
self.tag_v2.prefix,
|
| 1520 |
+
photo,
|
| 1521 |
+
sample_format,
|
| 1522 |
+
fillorder,
|
| 1523 |
+
bps_tuple,
|
| 1524 |
+
extra_tuple,
|
| 1525 |
+
)
|
| 1526 |
+
logger.debug("format key: %s", key)
|
| 1527 |
+
try:
|
| 1528 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1529 |
+
except KeyError as e:
|
| 1530 |
+
logger.debug("- unsupported format")
|
| 1531 |
+
msg = "unknown pixel mode"
|
| 1532 |
+
raise SyntaxError(msg) from e
|
| 1533 |
+
|
| 1534 |
+
logger.debug("- raw mode: %s", rawmode)
|
| 1535 |
+
logger.debug("- pil mode: %s", self.mode)
|
| 1536 |
+
|
| 1537 |
+
self.info["compression"] = self._compression
|
| 1538 |
+
|
| 1539 |
+
xres = self.tag_v2.get(X_RESOLUTION, 1)
|
| 1540 |
+
yres = self.tag_v2.get(Y_RESOLUTION, 1)
|
| 1541 |
+
|
| 1542 |
+
if xres and yres:
|
| 1543 |
+
resunit = self.tag_v2.get(RESOLUTION_UNIT)
|
| 1544 |
+
if resunit == 2: # dots per inch
|
| 1545 |
+
self.info["dpi"] = (xres, yres)
|
| 1546 |
+
elif resunit == 3: # dots per centimeter. convert to dpi
|
| 1547 |
+
self.info["dpi"] = (xres * 2.54, yres * 2.54)
|
| 1548 |
+
elif resunit is None: # used to default to 1, but now 2)
|
| 1549 |
+
self.info["dpi"] = (xres, yres)
|
| 1550 |
+
# For backward compatibility,
|
| 1551 |
+
# we also preserve the old behavior
|
| 1552 |
+
self.info["resolution"] = xres, yres
|
| 1553 |
+
else: # No absolute unit of measurement
|
| 1554 |
+
self.info["resolution"] = xres, yres
|
| 1555 |
+
|
| 1556 |
+
# build tile descriptors
|
| 1557 |
+
x = y = layer = 0
|
| 1558 |
+
self.tile = []
|
| 1559 |
+
self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
|
| 1560 |
+
if self.use_load_libtiff:
|
| 1561 |
+
# Decoder expects entire file as one tile.
|
| 1562 |
+
# There's a buffer size limit in load (64k)
|
| 1563 |
+
# so large g4 images will fail if we use that
|
| 1564 |
+
# function.
|
| 1565 |
+
#
|
| 1566 |
+
# Setup the one tile for the whole image, then
|
| 1567 |
+
# use the _load_libtiff function.
|
| 1568 |
+
|
| 1569 |
+
# libtiff handles the fillmode for us, so 1;IR should
|
| 1570 |
+
# actually be 1;I. Including the R double reverses the
|
| 1571 |
+
# bits, so stripes of the image are reversed. See
|
| 1572 |
+
# https://github.com/python-pillow/Pillow/issues/279
|
| 1573 |
+
if fillorder == 2:
|
| 1574 |
+
# Replace fillorder with fillorder=1
|
| 1575 |
+
key = key[:3] + (1,) + key[4:]
|
| 1576 |
+
logger.debug("format key: %s", key)
|
| 1577 |
+
# this should always work, since all the
|
| 1578 |
+
# fillorder==2 modes have a corresponding
|
| 1579 |
+
# fillorder=1 mode
|
| 1580 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1581 |
+
# YCbCr images with new jpeg compression with pixels in one plane
|
| 1582 |
+
# unpacked straight into RGB values
|
| 1583 |
+
if (
|
| 1584 |
+
photo == 6
|
| 1585 |
+
and self._compression == "jpeg"
|
| 1586 |
+
and self._planar_configuration == 1
|
| 1587 |
+
):
|
| 1588 |
+
rawmode = "RGB"
|
| 1589 |
+
# libtiff always returns the bytes in native order.
|
| 1590 |
+
# we're expecting image byte order. So, if the rawmode
|
| 1591 |
+
# contains I;16, we need to convert from native to image
|
| 1592 |
+
# byte order.
|
| 1593 |
+
elif rawmode == "I;16":
|
| 1594 |
+
rawmode = "I;16N"
|
| 1595 |
+
elif rawmode.endswith((";16B", ";16L")):
|
| 1596 |
+
rawmode = rawmode[:-1] + "N"
|
| 1597 |
+
|
| 1598 |
+
# Offset in the tile tuple is 0, we go from 0,0 to
|
| 1599 |
+
# w,h, and we only do this once -- eds
|
| 1600 |
+
a = (rawmode, self._compression, False, self.tag_v2.offset)
|
| 1601 |
+
self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))
|
| 1602 |
+
|
| 1603 |
+
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
|
| 1604 |
+
# striped image
|
| 1605 |
+
if STRIPOFFSETS in self.tag_v2:
|
| 1606 |
+
offsets = self.tag_v2[STRIPOFFSETS]
|
| 1607 |
+
h = self.tag_v2.get(ROWSPERSTRIP, ysize)
|
| 1608 |
+
w = xsize
|
| 1609 |
+
else:
|
| 1610 |
+
# tiled image
|
| 1611 |
+
offsets = self.tag_v2[TILEOFFSETS]
|
| 1612 |
+
tilewidth = self.tag_v2.get(TILEWIDTH)
|
| 1613 |
+
h = self.tag_v2.get(TILELENGTH)
|
| 1614 |
+
if not isinstance(tilewidth, int) or not isinstance(h, int):
|
| 1615 |
+
msg = "Invalid tile dimensions"
|
| 1616 |
+
raise ValueError(msg)
|
| 1617 |
+
w = tilewidth
|
| 1618 |
+
|
| 1619 |
+
if w == xsize and h == ysize and self._planar_configuration != 2:
|
| 1620 |
+
# Every tile covers the image. Only use the last offset
|
| 1621 |
+
offsets = offsets[-1:]
|
| 1622 |
+
|
| 1623 |
+
for offset in offsets:
|
| 1624 |
+
if x + w > xsize:
|
| 1625 |
+
stride = w * sum(bps_tuple) / 8 # bytes per line
|
| 1626 |
+
else:
|
| 1627 |
+
stride = 0
|
| 1628 |
+
|
| 1629 |
+
tile_rawmode = rawmode
|
| 1630 |
+
if self._planar_configuration == 2:
|
| 1631 |
+
# each band on it's own layer
|
| 1632 |
+
tile_rawmode = rawmode[layer]
|
| 1633 |
+
# adjust stride width accordingly
|
| 1634 |
+
stride /= bps_count
|
| 1635 |
+
|
| 1636 |
+
args = (tile_rawmode, int(stride), 1)
|
| 1637 |
+
self.tile.append(
|
| 1638 |
+
ImageFile._Tile(
|
| 1639 |
+
self._compression,
|
| 1640 |
+
(x, y, min(x + w, xsize), min(y + h, ysize)),
|
| 1641 |
+
offset,
|
| 1642 |
+
args,
|
| 1643 |
+
)
|
| 1644 |
+
)
|
| 1645 |
+
x += w
|
| 1646 |
+
if x >= xsize:
|
| 1647 |
+
x, y = 0, y + h
|
| 1648 |
+
if y >= ysize:
|
| 1649 |
+
y = 0
|
| 1650 |
+
layer += 1
|
| 1651 |
+
else:
|
| 1652 |
+
logger.debug("- unsupported data organization")
|
| 1653 |
+
msg = "unknown data organization"
|
| 1654 |
+
raise SyntaxError(msg)
|
| 1655 |
+
|
| 1656 |
+
# Fix up info.
|
| 1657 |
+
if ICCPROFILE in self.tag_v2:
|
| 1658 |
+
self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
|
| 1659 |
+
|
| 1660 |
+
# fixup palette descriptor
|
| 1661 |
+
|
| 1662 |
+
if self.mode in ["P", "PA"]:
|
| 1663 |
+
palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
|
| 1664 |
+
self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
|
| 1665 |
+
|
| 1666 |
+
|
| 1667 |
+
#
|
| 1668 |
+
# --------------------------------------------------------------------
|
| 1669 |
+
# Write TIFF files
|
| 1670 |
+
|
| 1671 |
+
# little endian is default except for image modes with
|
| 1672 |
+
# explicit big endian byte-order
|
| 1673 |
+
|
| 1674 |
+
SAVE_INFO = {
|
| 1675 |
+
# mode => rawmode, byteorder, photometrics,
|
| 1676 |
+
# sampleformat, bitspersample, extra
|
| 1677 |
+
"1": ("1", II, 1, 1, (1,), None),
|
| 1678 |
+
"L": ("L", II, 1, 1, (8,), None),
|
| 1679 |
+
"LA": ("LA", II, 1, 1, (8, 8), 2),
|
| 1680 |
+
"P": ("P", II, 3, 1, (8,), None),
|
| 1681 |
+
"PA": ("PA", II, 3, 1, (8, 8), 2),
|
| 1682 |
+
"I": ("I;32S", II, 1, 2, (32,), None),
|
| 1683 |
+
"I;16": ("I;16", II, 1, 1, (16,), None),
|
| 1684 |
+
"I;16L": ("I;16L", II, 1, 1, (16,), None),
|
| 1685 |
+
"F": ("F;32F", II, 1, 3, (32,), None),
|
| 1686 |
+
"RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
|
| 1687 |
+
"RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
|
| 1688 |
+
"RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
|
| 1689 |
+
"CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
|
| 1690 |
+
"YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
|
| 1691 |
+
"LAB": ("LAB", II, 8, 1, (8, 8, 8), None),
|
| 1692 |
+
"I;16B": ("I;16B", MM, 1, 1, (16,), None),
|
| 1693 |
+
}
|
| 1694 |
+
|
| 1695 |
+
|
| 1696 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 1697 |
+
try:
|
| 1698 |
+
rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
|
| 1699 |
+
except KeyError as e:
|
| 1700 |
+
msg = f"cannot write mode {im.mode} as TIFF"
|
| 1701 |
+
raise OSError(msg) from e
|
| 1702 |
+
|
| 1703 |
+
encoderinfo = im.encoderinfo
|
| 1704 |
+
encoderconfig = im.encoderconfig
|
| 1705 |
+
|
| 1706 |
+
ifd = ImageFileDirectory_v2(prefix=prefix)
|
| 1707 |
+
if encoderinfo.get("big_tiff"):
|
| 1708 |
+
ifd._bigtiff = True
|
| 1709 |
+
|
| 1710 |
+
try:
|
| 1711 |
+
compression = encoderinfo["compression"]
|
| 1712 |
+
except KeyError:
|
| 1713 |
+
compression = im.info.get("compression")
|
| 1714 |
+
if isinstance(compression, int):
|
| 1715 |
+
# compression value may be from BMP. Ignore it
|
| 1716 |
+
compression = None
|
| 1717 |
+
if compression is None:
|
| 1718 |
+
compression = "raw"
|
| 1719 |
+
elif compression == "tiff_jpeg":
|
| 1720 |
+
# OJPEG is obsolete, so use new-style JPEG compression instead
|
| 1721 |
+
compression = "jpeg"
|
| 1722 |
+
elif compression == "tiff_deflate":
|
| 1723 |
+
compression = "tiff_adobe_deflate"
|
| 1724 |
+
|
| 1725 |
+
libtiff = WRITE_LIBTIFF or compression != "raw"
|
| 1726 |
+
|
| 1727 |
+
# required for color libtiff images
|
| 1728 |
+
ifd[PLANAR_CONFIGURATION] = 1
|
| 1729 |
+
|
| 1730 |
+
ifd[IMAGEWIDTH] = im.size[0]
|
| 1731 |
+
ifd[IMAGELENGTH] = im.size[1]
|
| 1732 |
+
|
| 1733 |
+
# write any arbitrary tags passed in as an ImageFileDirectory
|
| 1734 |
+
if "tiffinfo" in encoderinfo:
|
| 1735 |
+
info = encoderinfo["tiffinfo"]
|
| 1736 |
+
elif "exif" in encoderinfo:
|
| 1737 |
+
info = encoderinfo["exif"]
|
| 1738 |
+
if isinstance(info, bytes):
|
| 1739 |
+
exif = Image.Exif()
|
| 1740 |
+
exif.load(info)
|
| 1741 |
+
info = exif
|
| 1742 |
+
else:
|
| 1743 |
+
info = {}
|
| 1744 |
+
logger.debug("Tiffinfo Keys: %s", list(info))
|
| 1745 |
+
if isinstance(info, ImageFileDirectory_v1):
|
| 1746 |
+
info = info.to_v2()
|
| 1747 |
+
for key in info:
|
| 1748 |
+
if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
|
| 1749 |
+
ifd[key] = info.get_ifd(key)
|
| 1750 |
+
else:
|
| 1751 |
+
ifd[key] = info.get(key)
|
| 1752 |
+
try:
|
| 1753 |
+
ifd.tagtype[key] = info.tagtype[key]
|
| 1754 |
+
except Exception:
|
| 1755 |
+
pass # might not be an IFD. Might not have populated type
|
| 1756 |
+
|
| 1757 |
+
legacy_ifd = {}
|
| 1758 |
+
if hasattr(im, "tag"):
|
| 1759 |
+
legacy_ifd = im.tag.to_v2()
|
| 1760 |
+
|
| 1761 |
+
supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
|
| 1762 |
+
for tag in (
|
| 1763 |
+
# IFD offset that may not be correct in the saved image
|
| 1764 |
+
EXIFIFD,
|
| 1765 |
+
# Determined by the image format and should not be copied from legacy_ifd.
|
| 1766 |
+
SAMPLEFORMAT,
|
| 1767 |
+
):
|
| 1768 |
+
if tag in supplied_tags:
|
| 1769 |
+
del supplied_tags[tag]
|
| 1770 |
+
|
| 1771 |
+
# additions written by Greg Couch, gregc@cgl.ucsf.edu
|
| 1772 |
+
# inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
|
| 1773 |
+
if hasattr(im, "tag_v2"):
|
| 1774 |
+
# preserve tags from original TIFF image file
|
| 1775 |
+
for key in (
|
| 1776 |
+
RESOLUTION_UNIT,
|
| 1777 |
+
X_RESOLUTION,
|
| 1778 |
+
Y_RESOLUTION,
|
| 1779 |
+
IPTC_NAA_CHUNK,
|
| 1780 |
+
PHOTOSHOP_CHUNK,
|
| 1781 |
+
XMP,
|
| 1782 |
+
):
|
| 1783 |
+
if key in im.tag_v2:
|
| 1784 |
+
if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (
|
| 1785 |
+
TiffTags.BYTE,
|
| 1786 |
+
TiffTags.UNDEFINED,
|
| 1787 |
+
):
|
| 1788 |
+
del supplied_tags[key]
|
| 1789 |
+
else:
|
| 1790 |
+
ifd[key] = im.tag_v2[key]
|
| 1791 |
+
ifd.tagtype[key] = im.tag_v2.tagtype[key]
|
| 1792 |
+
|
| 1793 |
+
# preserve ICC profile (should also work when saving other formats
|
| 1794 |
+
# which support profiles as TIFF) -- 2008-06-06 Florian Hoech
|
| 1795 |
+
icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1796 |
+
if icc:
|
| 1797 |
+
ifd[ICCPROFILE] = icc
|
| 1798 |
+
|
| 1799 |
+
for key, name in [
|
| 1800 |
+
(IMAGEDESCRIPTION, "description"),
|
| 1801 |
+
(X_RESOLUTION, "resolution"),
|
| 1802 |
+
(Y_RESOLUTION, "resolution"),
|
| 1803 |
+
(X_RESOLUTION, "x_resolution"),
|
| 1804 |
+
(Y_RESOLUTION, "y_resolution"),
|
| 1805 |
+
(RESOLUTION_UNIT, "resolution_unit"),
|
| 1806 |
+
(SOFTWARE, "software"),
|
| 1807 |
+
(DATE_TIME, "date_time"),
|
| 1808 |
+
(ARTIST, "artist"),
|
| 1809 |
+
(COPYRIGHT, "copyright"),
|
| 1810 |
+
]:
|
| 1811 |
+
if name in encoderinfo:
|
| 1812 |
+
ifd[key] = encoderinfo[name]
|
| 1813 |
+
|
| 1814 |
+
dpi = encoderinfo.get("dpi")
|
| 1815 |
+
if dpi:
|
| 1816 |
+
ifd[RESOLUTION_UNIT] = 2
|
| 1817 |
+
ifd[X_RESOLUTION] = dpi[0]
|
| 1818 |
+
ifd[Y_RESOLUTION] = dpi[1]
|
| 1819 |
+
|
| 1820 |
+
if bits != (1,):
|
| 1821 |
+
ifd[BITSPERSAMPLE] = bits
|
| 1822 |
+
if len(bits) != 1:
|
| 1823 |
+
ifd[SAMPLESPERPIXEL] = len(bits)
|
| 1824 |
+
if extra is not None:
|
| 1825 |
+
ifd[EXTRASAMPLES] = extra
|
| 1826 |
+
if format != 1:
|
| 1827 |
+
ifd[SAMPLEFORMAT] = format
|
| 1828 |
+
|
| 1829 |
+
if PHOTOMETRIC_INTERPRETATION not in ifd:
|
| 1830 |
+
ifd[PHOTOMETRIC_INTERPRETATION] = photo
|
| 1831 |
+
elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:
|
| 1832 |
+
if im.mode == "1":
|
| 1833 |
+
inverted_im = im.copy()
|
| 1834 |
+
px = inverted_im.load()
|
| 1835 |
+
if px is not None:
|
| 1836 |
+
for y in range(inverted_im.height):
|
| 1837 |
+
for x in range(inverted_im.width):
|
| 1838 |
+
px[x, y] = 0 if px[x, y] == 255 else 255
|
| 1839 |
+
im = inverted_im
|
| 1840 |
+
else:
|
| 1841 |
+
im = ImageOps.invert(im)
|
| 1842 |
+
|
| 1843 |
+
if im.mode in ["P", "PA"]:
|
| 1844 |
+
lut = im.im.getpalette("RGB", "RGB;L")
|
| 1845 |
+
colormap = []
|
| 1846 |
+
colors = len(lut) // 3
|
| 1847 |
+
for i in range(3):
|
| 1848 |
+
colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]
|
| 1849 |
+
colormap += [0] * (256 - colors)
|
| 1850 |
+
ifd[COLORMAP] = colormap
|
| 1851 |
+
# data orientation
|
| 1852 |
+
w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]
|
| 1853 |
+
stride = len(bits) * ((w * bits[0] + 7) // 8)
|
| 1854 |
+
if ROWSPERSTRIP not in ifd:
|
| 1855 |
+
# aim for given strip size (64 KB by default) when using libtiff writer
|
| 1856 |
+
if libtiff:
|
| 1857 |
+
im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)
|
| 1858 |
+
rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)
|
| 1859 |
+
# JPEG encoder expects multiple of 8 rows
|
| 1860 |
+
if compression == "jpeg":
|
| 1861 |
+
rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)
|
| 1862 |
+
else:
|
| 1863 |
+
rows_per_strip = h
|
| 1864 |
+
if rows_per_strip == 0:
|
| 1865 |
+
rows_per_strip = 1
|
| 1866 |
+
ifd[ROWSPERSTRIP] = rows_per_strip
|
| 1867 |
+
strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]
|
| 1868 |
+
strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]
|
| 1869 |
+
if strip_byte_counts >= 2**16:
|
| 1870 |
+
ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
|
| 1871 |
+
ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (
|
| 1872 |
+
stride * h - strip_byte_counts * (strips_per_image - 1),
|
| 1873 |
+
)
|
| 1874 |
+
ifd[STRIPOFFSETS] = tuple(
|
| 1875 |
+
range(0, strip_byte_counts * strips_per_image, strip_byte_counts)
|
| 1876 |
+
) # this is adjusted by IFD writer
|
| 1877 |
+
# no compression by default:
|
| 1878 |
+
ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
|
| 1879 |
+
|
| 1880 |
+
if im.mode == "YCbCr":
|
| 1881 |
+
for tag, default_value in {
|
| 1882 |
+
YCBCRSUBSAMPLING: (1, 1),
|
| 1883 |
+
REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),
|
| 1884 |
+
}.items():
|
| 1885 |
+
ifd.setdefault(tag, default_value)
|
| 1886 |
+
|
| 1887 |
+
blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]
|
| 1888 |
+
if libtiff:
|
| 1889 |
+
if "quality" in encoderinfo:
|
| 1890 |
+
quality = encoderinfo["quality"]
|
| 1891 |
+
if not isinstance(quality, int) or quality < 0 or quality > 100:
|
| 1892 |
+
msg = "Invalid quality setting"
|
| 1893 |
+
raise ValueError(msg)
|
| 1894 |
+
if compression != "jpeg":
|
| 1895 |
+
msg = "quality setting only supported for 'jpeg' compression"
|
| 1896 |
+
raise ValueError(msg)
|
| 1897 |
+
ifd[JPEGQUALITY] = quality
|
| 1898 |
+
|
| 1899 |
+
logger.debug("Saving using libtiff encoder")
|
| 1900 |
+
logger.debug("Items: %s", sorted(ifd.items()))
|
| 1901 |
+
_fp = 0
|
| 1902 |
+
if hasattr(fp, "fileno"):
|
| 1903 |
+
try:
|
| 1904 |
+
fp.seek(0)
|
| 1905 |
+
_fp = fp.fileno()
|
| 1906 |
+
except io.UnsupportedOperation:
|
| 1907 |
+
pass
|
| 1908 |
+
|
| 1909 |
+
# optional types for non core tags
|
| 1910 |
+
types = {}
|
| 1911 |
+
# STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
|
| 1912 |
+
# based on the data in the strip.
|
| 1913 |
+
# OSUBFILETYPE is deprecated.
|
| 1914 |
+
# The other tags expect arrays with a certain length (fixed or depending on
|
| 1915 |
+
# BITSPERSAMPLE, etc), passing arrays with a different length will result in
|
| 1916 |
+
# segfaults. Block these tags until we add extra validation.
|
| 1917 |
+
# SUBIFD may also cause a segfault.
|
| 1918 |
+
blocklist += [
|
| 1919 |
+
OSUBFILETYPE,
|
| 1920 |
+
REFERENCEBLACKWHITE,
|
| 1921 |
+
STRIPBYTECOUNTS,
|
| 1922 |
+
STRIPOFFSETS,
|
| 1923 |
+
TRANSFERFUNCTION,
|
| 1924 |
+
SUBIFD,
|
| 1925 |
+
]
|
| 1926 |
+
|
| 1927 |
+
# bits per sample is a single short in the tiff directory, not a list.
|
| 1928 |
+
atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
|
| 1929 |
+
# Merge the ones that we have with (optional) more bits from
|
| 1930 |
+
# the original file, e.g x,y resolution so that we can
|
| 1931 |
+
# save(load('')) == original file.
|
| 1932 |
+
for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
|
| 1933 |
+
# Libtiff can only process certain core items without adding
|
| 1934 |
+
# them to the custom dictionary.
|
| 1935 |
+
# Custom items are supported for int, float, unicode, string and byte
|
| 1936 |
+
# values. Other types and tuples require a tagtype.
|
| 1937 |
+
if tag not in TiffTags.LIBTIFF_CORE:
|
| 1938 |
+
if tag in TiffTags.TAGS_V2_GROUPS:
|
| 1939 |
+
types[tag] = TiffTags.LONG8
|
| 1940 |
+
elif tag in ifd.tagtype:
|
| 1941 |
+
types[tag] = ifd.tagtype[tag]
|
| 1942 |
+
elif isinstance(value, (int, float, str, bytes)) or (
|
| 1943 |
+
isinstance(value, tuple)
|
| 1944 |
+
and all(isinstance(v, (int, float, IFDRational)) for v in value)
|
| 1945 |
+
):
|
| 1946 |
+
type = TiffTags.lookup(tag).type
|
| 1947 |
+
if type:
|
| 1948 |
+
types[tag] = type
|
| 1949 |
+
if tag not in atts and tag not in blocklist:
|
| 1950 |
+
if isinstance(value, str):
|
| 1951 |
+
atts[tag] = value.encode("ascii", "replace") + b"\0"
|
| 1952 |
+
elif isinstance(value, IFDRational):
|
| 1953 |
+
atts[tag] = float(value)
|
| 1954 |
+
else:
|
| 1955 |
+
atts[tag] = value
|
| 1956 |
+
|
| 1957 |
+
if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:
|
| 1958 |
+
atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]
|
| 1959 |
+
|
| 1960 |
+
logger.debug("Converted items: %s", sorted(atts.items()))
|
| 1961 |
+
|
| 1962 |
+
# libtiff always expects the bytes in native order.
|
| 1963 |
+
# we're storing image byte order. So, if the rawmode
|
| 1964 |
+
# contains I;16, we need to convert from native to image
|
| 1965 |
+
# byte order.
|
| 1966 |
+
if im.mode in ("I;16", "I;16B", "I;16L"):
|
| 1967 |
+
rawmode = "I;16N"
|
| 1968 |
+
|
| 1969 |
+
# Pass tags as sorted list so that the tags are set in a fixed order.
|
| 1970 |
+
# This is required by libtiff for some tags. For example, the JPEGQUALITY
|
| 1971 |
+
# pseudo tag requires that the COMPRESS tag was already set.
|
| 1972 |
+
tags = list(atts.items())
|
| 1973 |
+
tags.sort()
|
| 1974 |
+
a = (rawmode, compression, _fp, filename, tags, types)
|
| 1975 |
+
encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
|
| 1976 |
+
encoder.setimage(im.im, (0, 0) + im.size)
|
| 1977 |
+
while True:
|
| 1978 |
+
errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:]
|
| 1979 |
+
if not _fp:
|
| 1980 |
+
fp.write(data)
|
| 1981 |
+
if errcode:
|
| 1982 |
+
break
|
| 1983 |
+
if errcode < 0:
|
| 1984 |
+
msg = f"encoder error {errcode} when writing image file"
|
| 1985 |
+
raise OSError(msg)
|
| 1986 |
+
|
| 1987 |
+
else:
|
| 1988 |
+
for tag in blocklist:
|
| 1989 |
+
del ifd[tag]
|
| 1990 |
+
offset = ifd.save(fp)
|
| 1991 |
+
|
| 1992 |
+
ImageFile._save(
|
| 1993 |
+
im,
|
| 1994 |
+
fp,
|
| 1995 |
+
[ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))],
|
| 1996 |
+
)
|
| 1997 |
+
|
| 1998 |
+
# -- helper for multi-page save --
|
| 1999 |
+
if "_debug_multipage" in encoderinfo:
|
| 2000 |
+
# just to access o32 and o16 (using correct byte order)
|
| 2001 |
+
setattr(im, "_debug_multipage", ifd)
|
| 2002 |
+
|
| 2003 |
+
|
| 2004 |
+
class AppendingTiffWriter(io.BytesIO):
|
| 2005 |
+
fieldSizes = [
|
| 2006 |
+
0, # None
|
| 2007 |
+
1, # byte
|
| 2008 |
+
1, # ascii
|
| 2009 |
+
2, # short
|
| 2010 |
+
4, # long
|
| 2011 |
+
8, # rational
|
| 2012 |
+
1, # sbyte
|
| 2013 |
+
1, # undefined
|
| 2014 |
+
2, # sshort
|
| 2015 |
+
4, # slong
|
| 2016 |
+
8, # srational
|
| 2017 |
+
4, # float
|
| 2018 |
+
8, # double
|
| 2019 |
+
4, # ifd
|
| 2020 |
+
2, # unicode
|
| 2021 |
+
4, # complex
|
| 2022 |
+
8, # long8
|
| 2023 |
+
]
|
| 2024 |
+
|
| 2025 |
+
Tags = {
|
| 2026 |
+
273, # StripOffsets
|
| 2027 |
+
288, # FreeOffsets
|
| 2028 |
+
324, # TileOffsets
|
| 2029 |
+
519, # JPEGQTables
|
| 2030 |
+
520, # JPEGDCTables
|
| 2031 |
+
521, # JPEGACTables
|
| 2032 |
+
}
|
| 2033 |
+
|
| 2034 |
+
def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None:
|
| 2035 |
+
self.f: IO[bytes]
|
| 2036 |
+
if is_path(fn):
|
| 2037 |
+
self.name = fn
|
| 2038 |
+
self.close_fp = True
|
| 2039 |
+
try:
|
| 2040 |
+
self.f = open(fn, "w+b" if new else "r+b")
|
| 2041 |
+
except OSError:
|
| 2042 |
+
self.f = open(fn, "w+b")
|
| 2043 |
+
else:
|
| 2044 |
+
self.f = cast(IO[bytes], fn)
|
| 2045 |
+
self.close_fp = False
|
| 2046 |
+
self.beginning = self.f.tell()
|
| 2047 |
+
self.setup()
|
| 2048 |
+
|
| 2049 |
+
def setup(self) -> None:
|
| 2050 |
+
# Reset everything.
|
| 2051 |
+
self.f.seek(self.beginning, os.SEEK_SET)
|
| 2052 |
+
|
| 2053 |
+
self.whereToWriteNewIFDOffset: int | None = None
|
| 2054 |
+
self.offsetOfNewPage = 0
|
| 2055 |
+
|
| 2056 |
+
self.IIMM = iimm = self.f.read(4)
|
| 2057 |
+
self._bigtiff = b"\x2b" in iimm
|
| 2058 |
+
if not iimm:
|
| 2059 |
+
# empty file - first page
|
| 2060 |
+
self.isFirst = True
|
| 2061 |
+
return
|
| 2062 |
+
|
| 2063 |
+
self.isFirst = False
|
| 2064 |
+
if iimm not in PREFIXES:
|
| 2065 |
+
msg = "Invalid TIFF file header"
|
| 2066 |
+
raise RuntimeError(msg)
|
| 2067 |
+
|
| 2068 |
+
self.setEndian("<" if iimm.startswith(II) else ">")
|
| 2069 |
+
|
| 2070 |
+
if self._bigtiff:
|
| 2071 |
+
self.f.seek(4, os.SEEK_CUR)
|
| 2072 |
+
self.skipIFDs()
|
| 2073 |
+
self.goToEnd()
|
| 2074 |
+
|
| 2075 |
+
def finalize(self) -> None:
|
| 2076 |
+
if self.isFirst:
|
| 2077 |
+
return
|
| 2078 |
+
|
| 2079 |
+
# fix offsets
|
| 2080 |
+
self.f.seek(self.offsetOfNewPage)
|
| 2081 |
+
|
| 2082 |
+
iimm = self.f.read(4)
|
| 2083 |
+
if not iimm:
|
| 2084 |
+
# Make it easy to finish a frame without committing to a new one.
|
| 2085 |
+
return
|
| 2086 |
+
|
| 2087 |
+
if iimm != self.IIMM:
|
| 2088 |
+
msg = "IIMM of new page doesn't match IIMM of first page"
|
| 2089 |
+
raise RuntimeError(msg)
|
| 2090 |
+
|
| 2091 |
+
if self._bigtiff:
|
| 2092 |
+
self.f.seek(4, os.SEEK_CUR)
|
| 2093 |
+
ifd_offset = self._read(8 if self._bigtiff else 4)
|
| 2094 |
+
ifd_offset += self.offsetOfNewPage
|
| 2095 |
+
assert self.whereToWriteNewIFDOffset is not None
|
| 2096 |
+
self.f.seek(self.whereToWriteNewIFDOffset)
|
| 2097 |
+
self._write(ifd_offset, 8 if self._bigtiff else 4)
|
| 2098 |
+
self.f.seek(ifd_offset)
|
| 2099 |
+
self.fixIFD()
|
| 2100 |
+
|
| 2101 |
+
def newFrame(self) -> None:
|
| 2102 |
+
# Call this to finish a frame.
|
| 2103 |
+
self.finalize()
|
| 2104 |
+
self.setup()
|
| 2105 |
+
|
| 2106 |
+
def __enter__(self) -> AppendingTiffWriter:
|
| 2107 |
+
return self
|
| 2108 |
+
|
| 2109 |
+
def __exit__(self, *args: object) -> None:
|
| 2110 |
+
if self.close_fp:
|
| 2111 |
+
self.close()
|
| 2112 |
+
|
| 2113 |
+
def tell(self) -> int:
|
| 2114 |
+
return self.f.tell() - self.offsetOfNewPage
|
| 2115 |
+
|
| 2116 |
+
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
|
| 2117 |
+
"""
|
| 2118 |
+
:param offset: Distance to seek.
|
| 2119 |
+
:param whence: Whether the distance is relative to the start,
|
| 2120 |
+
end or current position.
|
| 2121 |
+
:returns: The resulting position, relative to the start.
|
| 2122 |
+
"""
|
| 2123 |
+
if whence == os.SEEK_SET:
|
| 2124 |
+
offset += self.offsetOfNewPage
|
| 2125 |
+
|
| 2126 |
+
self.f.seek(offset, whence)
|
| 2127 |
+
return self.tell()
|
| 2128 |
+
|
| 2129 |
+
def goToEnd(self) -> None:
|
| 2130 |
+
self.f.seek(0, os.SEEK_END)
|
| 2131 |
+
pos = self.f.tell()
|
| 2132 |
+
|
| 2133 |
+
# pad to 16 byte boundary
|
| 2134 |
+
pad_bytes = 16 - pos % 16
|
| 2135 |
+
if 0 < pad_bytes < 16:
|
| 2136 |
+
self.f.write(bytes(pad_bytes))
|
| 2137 |
+
self.offsetOfNewPage = self.f.tell()
|
| 2138 |
+
|
| 2139 |
+
def setEndian(self, endian: str) -> None:
|
| 2140 |
+
self.endian = endian
|
| 2141 |
+
self.longFmt = f"{self.endian}L"
|
| 2142 |
+
self.shortFmt = f"{self.endian}H"
|
| 2143 |
+
self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L")
|
| 2144 |
+
|
| 2145 |
+
def skipIFDs(self) -> None:
|
| 2146 |
+
while True:
|
| 2147 |
+
ifd_offset = self._read(8 if self._bigtiff else 4)
|
| 2148 |
+
if ifd_offset == 0:
|
| 2149 |
+
self.whereToWriteNewIFDOffset = self.f.tell() - (
|
| 2150 |
+
8 if self._bigtiff else 4
|
| 2151 |
+
)
|
| 2152 |
+
break
|
| 2153 |
+
|
| 2154 |
+
self.f.seek(ifd_offset)
|
| 2155 |
+
num_tags = self._read(8 if self._bigtiff else 2)
|
| 2156 |
+
self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR)
|
| 2157 |
+
|
| 2158 |
+
def write(self, data: Buffer, /) -> int:
|
| 2159 |
+
return self.f.write(data)
|
| 2160 |
+
|
| 2161 |
+
def _fmt(self, field_size: int) -> str:
|
| 2162 |
+
try:
|
| 2163 |
+
return {2: "H", 4: "L", 8: "Q"}[field_size]
|
| 2164 |
+
except KeyError:
|
| 2165 |
+
msg = "offset is not supported"
|
| 2166 |
+
raise RuntimeError(msg)
|
| 2167 |
+
|
| 2168 |
+
def _read(self, field_size: int) -> int:
|
| 2169 |
+
(value,) = struct.unpack(
|
| 2170 |
+
self.endian + self._fmt(field_size), self.f.read(field_size)
|
| 2171 |
+
)
|
| 2172 |
+
return value
|
| 2173 |
+
|
| 2174 |
+
def readShort(self) -> int:
|
| 2175 |
+
return self._read(2)
|
| 2176 |
+
|
| 2177 |
+
def readLong(self) -> int:
|
| 2178 |
+
return self._read(4)
|
| 2179 |
+
|
| 2180 |
+
@staticmethod
|
| 2181 |
+
def _verify_bytes_written(bytes_written: int | None, expected: int) -> None:
|
| 2182 |
+
if bytes_written is not None and bytes_written != expected:
|
| 2183 |
+
msg = f"wrote only {bytes_written} bytes but wanted {expected}"
|
| 2184 |
+
raise RuntimeError(msg)
|
| 2185 |
+
|
| 2186 |
+
def _rewriteLast(
|
| 2187 |
+
self, value: int, field_size: int, new_field_size: int = 0
|
| 2188 |
+
) -> None:
|
| 2189 |
+
self.f.seek(-field_size, os.SEEK_CUR)
|
| 2190 |
+
if not new_field_size:
|
| 2191 |
+
new_field_size = field_size
|
| 2192 |
+
bytes_written = self.f.write(
|
| 2193 |
+
struct.pack(self.endian + self._fmt(new_field_size), value)
|
| 2194 |
+
)
|
| 2195 |
+
self._verify_bytes_written(bytes_written, new_field_size)
|
| 2196 |
+
|
| 2197 |
+
def rewriteLastShortToLong(self, value: int) -> None:
|
| 2198 |
+
self._rewriteLast(value, 2, 4)
|
| 2199 |
+
|
| 2200 |
+
def rewriteLastShort(self, value: int) -> None:
|
| 2201 |
+
return self._rewriteLast(value, 2)
|
| 2202 |
+
|
| 2203 |
+
def rewriteLastLong(self, value: int) -> None:
|
| 2204 |
+
return self._rewriteLast(value, 4)
|
| 2205 |
+
|
| 2206 |
+
def _write(self, value: int, field_size: int) -> None:
|
| 2207 |
+
bytes_written = self.f.write(
|
| 2208 |
+
struct.pack(self.endian + self._fmt(field_size), value)
|
| 2209 |
+
)
|
| 2210 |
+
self._verify_bytes_written(bytes_written, field_size)
|
| 2211 |
+
|
| 2212 |
+
def writeShort(self, value: int) -> None:
|
| 2213 |
+
self._write(value, 2)
|
| 2214 |
+
|
| 2215 |
+
def writeLong(self, value: int) -> None:
|
| 2216 |
+
self._write(value, 4)
|
| 2217 |
+
|
| 2218 |
+
def close(self) -> None:
|
| 2219 |
+
self.finalize()
|
| 2220 |
+
if self.close_fp:
|
| 2221 |
+
self.f.close()
|
| 2222 |
+
|
| 2223 |
+
def fixIFD(self) -> None:
|
| 2224 |
+
num_tags = self._read(8 if self._bigtiff else 2)
|
| 2225 |
+
|
| 2226 |
+
for i in range(num_tags):
|
| 2227 |
+
tag, field_type, count = struct.unpack(
|
| 2228 |
+
self.tagFormat, self.f.read(12 if self._bigtiff else 8)
|
| 2229 |
+
)
|
| 2230 |
+
|
| 2231 |
+
field_size = self.fieldSizes[field_type]
|
| 2232 |
+
total_size = field_size * count
|
| 2233 |
+
fmt_size = 8 if self._bigtiff else 4
|
| 2234 |
+
is_local = total_size <= fmt_size
|
| 2235 |
+
if not is_local:
|
| 2236 |
+
offset = self._read(fmt_size) + self.offsetOfNewPage
|
| 2237 |
+
self._rewriteLast(offset, fmt_size)
|
| 2238 |
+
|
| 2239 |
+
if tag in self.Tags:
|
| 2240 |
+
cur_pos = self.f.tell()
|
| 2241 |
+
|
| 2242 |
+
logger.debug(
|
| 2243 |
+
"fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d",
|
| 2244 |
+
TiffTags.lookup(tag).name,
|
| 2245 |
+
tag,
|
| 2246 |
+
TYPES.get(field_type, "unknown"),
|
| 2247 |
+
field_type,
|
| 2248 |
+
field_size,
|
| 2249 |
+
count,
|
| 2250 |
+
)
|
| 2251 |
+
|
| 2252 |
+
if is_local:
|
| 2253 |
+
self._fixOffsets(count, field_size)
|
| 2254 |
+
self.f.seek(cur_pos + fmt_size)
|
| 2255 |
+
else:
|
| 2256 |
+
self.f.seek(offset)
|
| 2257 |
+
self._fixOffsets(count, field_size)
|
| 2258 |
+
self.f.seek(cur_pos)
|
| 2259 |
+
|
| 2260 |
+
elif is_local:
|
| 2261 |
+
# skip the locally stored value that is not an offset
|
| 2262 |
+
self.f.seek(fmt_size, os.SEEK_CUR)
|
| 2263 |
+
|
| 2264 |
+
def _fixOffsets(self, count: int, field_size: int) -> None:
|
| 2265 |
+
for i in range(count):
|
| 2266 |
+
offset = self._read(field_size)
|
| 2267 |
+
offset += self.offsetOfNewPage
|
| 2268 |
+
|
| 2269 |
+
new_field_size = 0
|
| 2270 |
+
if self._bigtiff and field_size in (2, 4) and offset >= 2**32:
|
| 2271 |
+
# offset is now too large - we must convert long to long8
|
| 2272 |
+
new_field_size = 8
|
| 2273 |
+
elif field_size == 2 and offset >= 2**16:
|
| 2274 |
+
# offset is now too large - we must convert short to long
|
| 2275 |
+
new_field_size = 4
|
| 2276 |
+
if new_field_size:
|
| 2277 |
+
if count != 1:
|
| 2278 |
+
msg = "not implemented"
|
| 2279 |
+
raise RuntimeError(msg) # XXX TODO
|
| 2280 |
+
|
| 2281 |
+
# simple case - the offset is just one and therefore it is
|
| 2282 |
+
# local (not referenced with another offset)
|
| 2283 |
+
self._rewriteLast(offset, field_size, new_field_size)
|
| 2284 |
+
# Move back past the new offset, past 'count', and before 'field_type'
|
| 2285 |
+
rewind = -new_field_size - 4 - 2
|
| 2286 |
+
self.f.seek(rewind, os.SEEK_CUR)
|
| 2287 |
+
self.writeShort(new_field_size) # rewrite the type
|
| 2288 |
+
self.f.seek(2 - rewind, os.SEEK_CUR)
|
| 2289 |
+
else:
|
| 2290 |
+
self._rewriteLast(offset, field_size)
|
| 2291 |
+
|
| 2292 |
+
def fixOffsets(
|
| 2293 |
+
self, count: int, isShort: bool = False, isLong: bool = False
|
| 2294 |
+
) -> None:
|
| 2295 |
+
if isShort:
|
| 2296 |
+
field_size = 2
|
| 2297 |
+
elif isLong:
|
| 2298 |
+
field_size = 4
|
| 2299 |
+
else:
|
| 2300 |
+
field_size = 0
|
| 2301 |
+
return self._fixOffsets(count, field_size)
|
| 2302 |
+
|
| 2303 |
+
|
| 2304 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 2305 |
+
append_images = list(im.encoderinfo.get("append_images", []))
|
| 2306 |
+
if not hasattr(im, "n_frames") and not append_images:
|
| 2307 |
+
return _save(im, fp, filename)
|
| 2308 |
+
|
| 2309 |
+
cur_idx = im.tell()
|
| 2310 |
+
try:
|
| 2311 |
+
with AppendingTiffWriter(fp) as tf:
|
| 2312 |
+
for ims in [im] + append_images:
|
| 2313 |
+
encoderinfo = ims._attach_default_encoderinfo(im)
|
| 2314 |
+
if not hasattr(ims, "encoderconfig"):
|
| 2315 |
+
ims.encoderconfig = ()
|
| 2316 |
+
nfr = getattr(ims, "n_frames", 1)
|
| 2317 |
+
|
| 2318 |
+
for idx in range(nfr):
|
| 2319 |
+
ims.seek(idx)
|
| 2320 |
+
ims.load()
|
| 2321 |
+
_save(ims, tf, filename)
|
| 2322 |
+
tf.newFrame()
|
| 2323 |
+
ims.encoderinfo = encoderinfo
|
| 2324 |
+
finally:
|
| 2325 |
+
im.seek(cur_idx)
|
| 2326 |
+
|
| 2327 |
+
|
| 2328 |
+
#
|
| 2329 |
+
# --------------------------------------------------------------------
|
| 2330 |
+
# Register
|
| 2331 |
+
|
| 2332 |
+
Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
|
| 2333 |
+
Image.register_save(TiffImageFile.format, _save)
|
| 2334 |
+
Image.register_save_all(TiffImageFile.format, _save_all)
|
| 2335 |
+
|
| 2336 |
+
Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"])
|
| 2337 |
+
|
| 2338 |
+
Image.register_mime(TiffImageFile.format, "image/tiff")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/TiffTags.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# TIFF tags
|
| 6 |
+
#
|
| 7 |
+
# This module provides clear-text names for various well-known
|
| 8 |
+
# TIFF tags. the TIFF codec works just fine without it.
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1999.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
|
| 15 |
+
##
|
| 16 |
+
# This module provides constants and clear-text names for various
|
| 17 |
+
# well-known TIFF tags.
|
| 18 |
+
##
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from typing import NamedTuple
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _TagInfo(NamedTuple):
|
| 25 |
+
value: int | None
|
| 26 |
+
name: str
|
| 27 |
+
type: int | None
|
| 28 |
+
length: int | None
|
| 29 |
+
enum: dict[str, int]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TagInfo(_TagInfo):
|
| 33 |
+
__slots__: list[str] = []
|
| 34 |
+
|
| 35 |
+
def __new__(
|
| 36 |
+
cls,
|
| 37 |
+
value: int | None = None,
|
| 38 |
+
name: str = "unknown",
|
| 39 |
+
type: int | None = None,
|
| 40 |
+
length: int | None = None,
|
| 41 |
+
enum: dict[str, int] | None = None,
|
| 42 |
+
) -> TagInfo:
|
| 43 |
+
return super().__new__(cls, value, name, type, length, enum or {})
|
| 44 |
+
|
| 45 |
+
def cvt_enum(self, value: str) -> int | str:
|
| 46 |
+
# Using get will call hash(value), which can be expensive
|
| 47 |
+
# for some types (e.g. Fraction). Since self.enum is rarely
|
| 48 |
+
# used, it's usually better to test it first.
|
| 49 |
+
return self.enum.get(value, value) if self.enum else value
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def lookup(tag: int, group: int | None = None) -> TagInfo:
|
| 53 |
+
"""
|
| 54 |
+
:param tag: Integer tag number
|
| 55 |
+
:param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in
|
| 56 |
+
|
| 57 |
+
.. versionadded:: 8.3.0
|
| 58 |
+
|
| 59 |
+
:returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,
|
| 60 |
+
otherwise just populating the value and name from ``TAGS``.
|
| 61 |
+
If the tag is not recognized, "unknown" is returned for the name
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
if group is not None:
|
| 66 |
+
info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None
|
| 67 |
+
else:
|
| 68 |
+
info = TAGS_V2.get(tag)
|
| 69 |
+
return info or TagInfo(tag, TAGS.get(tag, "unknown"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
##
|
| 73 |
+
# Map tag numbers to tag info.
|
| 74 |
+
#
|
| 75 |
+
# id: (Name, Type, Length[, enum_values])
|
| 76 |
+
#
|
| 77 |
+
# The length here differs from the length in the tiff spec. For
|
| 78 |
+
# numbers, the tiff spec is for the number of fields returned. We
|
| 79 |
+
# agree here. For string-like types, the tiff spec uses the length of
|
| 80 |
+
# field in bytes. In Pillow, we are using the number of expected
|
| 81 |
+
# fields, in general 1 for string-like types.
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
BYTE = 1
|
| 85 |
+
ASCII = 2
|
| 86 |
+
SHORT = 3
|
| 87 |
+
LONG = 4
|
| 88 |
+
RATIONAL = 5
|
| 89 |
+
SIGNED_BYTE = 6
|
| 90 |
+
UNDEFINED = 7
|
| 91 |
+
SIGNED_SHORT = 8
|
| 92 |
+
SIGNED_LONG = 9
|
| 93 |
+
SIGNED_RATIONAL = 10
|
| 94 |
+
FLOAT = 11
|
| 95 |
+
DOUBLE = 12
|
| 96 |
+
IFD = 13
|
| 97 |
+
LONG8 = 16
|
| 98 |
+
|
| 99 |
+
_tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = {
|
| 100 |
+
254: ("NewSubfileType", LONG, 1),
|
| 101 |
+
255: ("SubfileType", SHORT, 1),
|
| 102 |
+
256: ("ImageWidth", LONG, 1),
|
| 103 |
+
257: ("ImageLength", LONG, 1),
|
| 104 |
+
258: ("BitsPerSample", SHORT, 0),
|
| 105 |
+
259: (
|
| 106 |
+
"Compression",
|
| 107 |
+
SHORT,
|
| 108 |
+
1,
|
| 109 |
+
{
|
| 110 |
+
"Uncompressed": 1,
|
| 111 |
+
"CCITT 1d": 2,
|
| 112 |
+
"Group 3 Fax": 3,
|
| 113 |
+
"Group 4 Fax": 4,
|
| 114 |
+
"LZW": 5,
|
| 115 |
+
"JPEG": 6,
|
| 116 |
+
"PackBits": 32773,
|
| 117 |
+
},
|
| 118 |
+
),
|
| 119 |
+
262: (
|
| 120 |
+
"PhotometricInterpretation",
|
| 121 |
+
SHORT,
|
| 122 |
+
1,
|
| 123 |
+
{
|
| 124 |
+
"WhiteIsZero": 0,
|
| 125 |
+
"BlackIsZero": 1,
|
| 126 |
+
"RGB": 2,
|
| 127 |
+
"RGB Palette": 3,
|
| 128 |
+
"Transparency Mask": 4,
|
| 129 |
+
"CMYK": 5,
|
| 130 |
+
"YCbCr": 6,
|
| 131 |
+
"CieLAB": 8,
|
| 132 |
+
"CFA": 32803, # TIFF/EP, Adobe DNG
|
| 133 |
+
"LinearRaw": 32892, # Adobe DNG
|
| 134 |
+
},
|
| 135 |
+
),
|
| 136 |
+
263: ("Threshholding", SHORT, 1),
|
| 137 |
+
264: ("CellWidth", SHORT, 1),
|
| 138 |
+
265: ("CellLength", SHORT, 1),
|
| 139 |
+
266: ("FillOrder", SHORT, 1),
|
| 140 |
+
269: ("DocumentName", ASCII, 1),
|
| 141 |
+
270: ("ImageDescription", ASCII, 1),
|
| 142 |
+
271: ("Make", ASCII, 1),
|
| 143 |
+
272: ("Model", ASCII, 1),
|
| 144 |
+
273: ("StripOffsets", LONG, 0),
|
| 145 |
+
274: ("Orientation", SHORT, 1),
|
| 146 |
+
277: ("SamplesPerPixel", SHORT, 1),
|
| 147 |
+
278: ("RowsPerStrip", LONG, 1),
|
| 148 |
+
279: ("StripByteCounts", LONG, 0),
|
| 149 |
+
280: ("MinSampleValue", SHORT, 0),
|
| 150 |
+
281: ("MaxSampleValue", SHORT, 0),
|
| 151 |
+
282: ("XResolution", RATIONAL, 1),
|
| 152 |
+
283: ("YResolution", RATIONAL, 1),
|
| 153 |
+
284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),
|
| 154 |
+
285: ("PageName", ASCII, 1),
|
| 155 |
+
286: ("XPosition", RATIONAL, 1),
|
| 156 |
+
287: ("YPosition", RATIONAL, 1),
|
| 157 |
+
288: ("FreeOffsets", LONG, 1),
|
| 158 |
+
289: ("FreeByteCounts", LONG, 1),
|
| 159 |
+
290: ("GrayResponseUnit", SHORT, 1),
|
| 160 |
+
291: ("GrayResponseCurve", SHORT, 0),
|
| 161 |
+
292: ("T4Options", LONG, 1),
|
| 162 |
+
293: ("T6Options", LONG, 1),
|
| 163 |
+
296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),
|
| 164 |
+
297: ("PageNumber", SHORT, 2),
|
| 165 |
+
301: ("TransferFunction", SHORT, 0),
|
| 166 |
+
305: ("Software", ASCII, 1),
|
| 167 |
+
306: ("DateTime", ASCII, 1),
|
| 168 |
+
315: ("Artist", ASCII, 1),
|
| 169 |
+
316: ("HostComputer", ASCII, 1),
|
| 170 |
+
317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),
|
| 171 |
+
318: ("WhitePoint", RATIONAL, 2),
|
| 172 |
+
319: ("PrimaryChromaticities", RATIONAL, 6),
|
| 173 |
+
320: ("ColorMap", SHORT, 0),
|
| 174 |
+
321: ("HalftoneHints", SHORT, 2),
|
| 175 |
+
322: ("TileWidth", LONG, 1),
|
| 176 |
+
323: ("TileLength", LONG, 1),
|
| 177 |
+
324: ("TileOffsets", LONG, 0),
|
| 178 |
+
325: ("TileByteCounts", LONG, 0),
|
| 179 |
+
330: ("SubIFDs", LONG, 0),
|
| 180 |
+
332: ("InkSet", SHORT, 1),
|
| 181 |
+
333: ("InkNames", ASCII, 1),
|
| 182 |
+
334: ("NumberOfInks", SHORT, 1),
|
| 183 |
+
336: ("DotRange", SHORT, 0),
|
| 184 |
+
337: ("TargetPrinter", ASCII, 1),
|
| 185 |
+
338: ("ExtraSamples", SHORT, 0),
|
| 186 |
+
339: ("SampleFormat", SHORT, 0),
|
| 187 |
+
340: ("SMinSampleValue", DOUBLE, 0),
|
| 188 |
+
341: ("SMaxSampleValue", DOUBLE, 0),
|
| 189 |
+
342: ("TransferRange", SHORT, 6),
|
| 190 |
+
347: ("JPEGTables", UNDEFINED, 1),
|
| 191 |
+
# obsolete JPEG tags
|
| 192 |
+
512: ("JPEGProc", SHORT, 1),
|
| 193 |
+
513: ("JPEGInterchangeFormat", LONG, 1),
|
| 194 |
+
514: ("JPEGInterchangeFormatLength", LONG, 1),
|
| 195 |
+
515: ("JPEGRestartInterval", SHORT, 1),
|
| 196 |
+
517: ("JPEGLosslessPredictors", SHORT, 0),
|
| 197 |
+
518: ("JPEGPointTransforms", SHORT, 0),
|
| 198 |
+
519: ("JPEGQTables", LONG, 0),
|
| 199 |
+
520: ("JPEGDCTables", LONG, 0),
|
| 200 |
+
521: ("JPEGACTables", LONG, 0),
|
| 201 |
+
529: ("YCbCrCoefficients", RATIONAL, 3),
|
| 202 |
+
530: ("YCbCrSubSampling", SHORT, 2),
|
| 203 |
+
531: ("YCbCrPositioning", SHORT, 1),
|
| 204 |
+
532: ("ReferenceBlackWhite", RATIONAL, 6),
|
| 205 |
+
700: ("XMP", BYTE, 0),
|
| 206 |
+
# Four private SGI tags
|
| 207 |
+
32995: ("Matteing", SHORT, 1),
|
| 208 |
+
32996: ("DataType", SHORT, 0),
|
| 209 |
+
32997: ("ImageDepth", LONG, 1),
|
| 210 |
+
32998: ("TileDepth", LONG, 1),
|
| 211 |
+
33432: ("Copyright", ASCII, 1),
|
| 212 |
+
33723: ("IptcNaaInfo", UNDEFINED, 1),
|
| 213 |
+
34377: ("PhotoshopInfo", BYTE, 0),
|
| 214 |
+
# FIXME add more tags here
|
| 215 |
+
34665: ("ExifIFD", LONG, 1),
|
| 216 |
+
34675: ("ICCProfile", UNDEFINED, 1),
|
| 217 |
+
34853: ("GPSInfoIFD", LONG, 1),
|
| 218 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 219 |
+
37724: ("ImageSourceData", UNDEFINED, 1),
|
| 220 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 221 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 222 |
+
# MPInfo
|
| 223 |
+
45056: ("MPFVersion", UNDEFINED, 1),
|
| 224 |
+
45057: ("NumberOfImages", LONG, 1),
|
| 225 |
+
45058: ("MPEntry", UNDEFINED, 1),
|
| 226 |
+
45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
|
| 227 |
+
45060: ("TotalFrames", LONG, 1),
|
| 228 |
+
45313: ("MPIndividualNum", LONG, 1),
|
| 229 |
+
45569: ("PanOrientation", LONG, 1),
|
| 230 |
+
45570: ("PanOverlap_H", RATIONAL, 1),
|
| 231 |
+
45571: ("PanOverlap_V", RATIONAL, 1),
|
| 232 |
+
45572: ("BaseViewpointNum", LONG, 1),
|
| 233 |
+
45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
|
| 234 |
+
45574: ("BaselineLength", RATIONAL, 1),
|
| 235 |
+
45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
|
| 236 |
+
45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
|
| 237 |
+
45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
|
| 238 |
+
45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
|
| 239 |
+
45579: ("YawAngle", SIGNED_RATIONAL, 1),
|
| 240 |
+
45580: ("PitchAngle", SIGNED_RATIONAL, 1),
|
| 241 |
+
45581: ("RollAngle", SIGNED_RATIONAL, 1),
|
| 242 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 243 |
+
50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
|
| 244 |
+
50780: ("BestQualityScale", RATIONAL, 1),
|
| 245 |
+
50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
|
| 246 |
+
50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
|
| 247 |
+
}
|
| 248 |
+
_tags_v2_groups = {
|
| 249 |
+
# ExifIFD
|
| 250 |
+
34665: {
|
| 251 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 252 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 253 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 254 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 255 |
+
},
|
| 256 |
+
# GPSInfoIFD
|
| 257 |
+
34853: {
|
| 258 |
+
0: ("GPSVersionID", BYTE, 4),
|
| 259 |
+
1: ("GPSLatitudeRef", ASCII, 2),
|
| 260 |
+
2: ("GPSLatitude", RATIONAL, 3),
|
| 261 |
+
3: ("GPSLongitudeRef", ASCII, 2),
|
| 262 |
+
4: ("GPSLongitude", RATIONAL, 3),
|
| 263 |
+
5: ("GPSAltitudeRef", BYTE, 1),
|
| 264 |
+
6: ("GPSAltitude", RATIONAL, 1),
|
| 265 |
+
7: ("GPSTimeStamp", RATIONAL, 3),
|
| 266 |
+
8: ("GPSSatellites", ASCII, 0),
|
| 267 |
+
9: ("GPSStatus", ASCII, 2),
|
| 268 |
+
10: ("GPSMeasureMode", ASCII, 2),
|
| 269 |
+
11: ("GPSDOP", RATIONAL, 1),
|
| 270 |
+
12: ("GPSSpeedRef", ASCII, 2),
|
| 271 |
+
13: ("GPSSpeed", RATIONAL, 1),
|
| 272 |
+
14: ("GPSTrackRef", ASCII, 2),
|
| 273 |
+
15: ("GPSTrack", RATIONAL, 1),
|
| 274 |
+
16: ("GPSImgDirectionRef", ASCII, 2),
|
| 275 |
+
17: ("GPSImgDirection", RATIONAL, 1),
|
| 276 |
+
18: ("GPSMapDatum", ASCII, 0),
|
| 277 |
+
19: ("GPSDestLatitudeRef", ASCII, 2),
|
| 278 |
+
20: ("GPSDestLatitude", RATIONAL, 3),
|
| 279 |
+
21: ("GPSDestLongitudeRef", ASCII, 2),
|
| 280 |
+
22: ("GPSDestLongitude", RATIONAL, 3),
|
| 281 |
+
23: ("GPSDestBearingRef", ASCII, 2),
|
| 282 |
+
24: ("GPSDestBearing", RATIONAL, 1),
|
| 283 |
+
25: ("GPSDestDistanceRef", ASCII, 2),
|
| 284 |
+
26: ("GPSDestDistance", RATIONAL, 1),
|
| 285 |
+
27: ("GPSProcessingMethod", UNDEFINED, 0),
|
| 286 |
+
28: ("GPSAreaInformation", UNDEFINED, 0),
|
| 287 |
+
29: ("GPSDateStamp", ASCII, 11),
|
| 288 |
+
30: ("GPSDifferential", SHORT, 1),
|
| 289 |
+
},
|
| 290 |
+
# InteroperabilityIFD
|
| 291 |
+
40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
# Legacy Tags structure
|
| 295 |
+
# these tags aren't included above, but were in the previous versions
|
| 296 |
+
TAGS: dict[int | tuple[int, int], str] = {
|
| 297 |
+
347: "JPEGTables",
|
| 298 |
+
700: "XMP",
|
| 299 |
+
# Additional Exif Info
|
| 300 |
+
32932: "Wang Annotation",
|
| 301 |
+
33434: "ExposureTime",
|
| 302 |
+
33437: "FNumber",
|
| 303 |
+
33445: "MD FileTag",
|
| 304 |
+
33446: "MD ScalePixel",
|
| 305 |
+
33447: "MD ColorTable",
|
| 306 |
+
33448: "MD LabName",
|
| 307 |
+
33449: "MD SampleInfo",
|
| 308 |
+
33450: "MD PrepDate",
|
| 309 |
+
33451: "MD PrepTime",
|
| 310 |
+
33452: "MD FileUnits",
|
| 311 |
+
33550: "ModelPixelScaleTag",
|
| 312 |
+
33723: "IptcNaaInfo",
|
| 313 |
+
33918: "INGR Packet Data Tag",
|
| 314 |
+
33919: "INGR Flag Registers",
|
| 315 |
+
33920: "IrasB Transformation Matrix",
|
| 316 |
+
33922: "ModelTiepointTag",
|
| 317 |
+
34264: "ModelTransformationTag",
|
| 318 |
+
34377: "PhotoshopInfo",
|
| 319 |
+
34735: "GeoKeyDirectoryTag",
|
| 320 |
+
34736: "GeoDoubleParamsTag",
|
| 321 |
+
34737: "GeoAsciiParamsTag",
|
| 322 |
+
34850: "ExposureProgram",
|
| 323 |
+
34852: "SpectralSensitivity",
|
| 324 |
+
34855: "ISOSpeedRatings",
|
| 325 |
+
34856: "OECF",
|
| 326 |
+
34864: "SensitivityType",
|
| 327 |
+
34865: "StandardOutputSensitivity",
|
| 328 |
+
34866: "RecommendedExposureIndex",
|
| 329 |
+
34867: "ISOSpeed",
|
| 330 |
+
34868: "ISOSpeedLatitudeyyy",
|
| 331 |
+
34869: "ISOSpeedLatitudezzz",
|
| 332 |
+
34908: "HylaFAX FaxRecvParams",
|
| 333 |
+
34909: "HylaFAX FaxSubAddress",
|
| 334 |
+
34910: "HylaFAX FaxRecvTime",
|
| 335 |
+
36864: "ExifVersion",
|
| 336 |
+
36867: "DateTimeOriginal",
|
| 337 |
+
36868: "DateTimeDigitized",
|
| 338 |
+
37121: "ComponentsConfiguration",
|
| 339 |
+
37122: "CompressedBitsPerPixel",
|
| 340 |
+
37724: "ImageSourceData",
|
| 341 |
+
37377: "ShutterSpeedValue",
|
| 342 |
+
37378: "ApertureValue",
|
| 343 |
+
37379: "BrightnessValue",
|
| 344 |
+
37380: "ExposureBiasValue",
|
| 345 |
+
37381: "MaxApertureValue",
|
| 346 |
+
37382: "SubjectDistance",
|
| 347 |
+
37383: "MeteringMode",
|
| 348 |
+
37384: "LightSource",
|
| 349 |
+
37385: "Flash",
|
| 350 |
+
37386: "FocalLength",
|
| 351 |
+
37396: "SubjectArea",
|
| 352 |
+
37500: "MakerNote",
|
| 353 |
+
37510: "UserComment",
|
| 354 |
+
37520: "SubSec",
|
| 355 |
+
37521: "SubSecTimeOriginal",
|
| 356 |
+
37522: "SubsecTimeDigitized",
|
| 357 |
+
40960: "FlashPixVersion",
|
| 358 |
+
40961: "ColorSpace",
|
| 359 |
+
40962: "PixelXDimension",
|
| 360 |
+
40963: "PixelYDimension",
|
| 361 |
+
40964: "RelatedSoundFile",
|
| 362 |
+
40965: "InteroperabilityIFD",
|
| 363 |
+
41483: "FlashEnergy",
|
| 364 |
+
41484: "SpatialFrequencyResponse",
|
| 365 |
+
41486: "FocalPlaneXResolution",
|
| 366 |
+
41487: "FocalPlaneYResolution",
|
| 367 |
+
41488: "FocalPlaneResolutionUnit",
|
| 368 |
+
41492: "SubjectLocation",
|
| 369 |
+
41493: "ExposureIndex",
|
| 370 |
+
41495: "SensingMethod",
|
| 371 |
+
41728: "FileSource",
|
| 372 |
+
41729: "SceneType",
|
| 373 |
+
41730: "CFAPattern",
|
| 374 |
+
41985: "CustomRendered",
|
| 375 |
+
41986: "ExposureMode",
|
| 376 |
+
41987: "WhiteBalance",
|
| 377 |
+
41988: "DigitalZoomRatio",
|
| 378 |
+
41989: "FocalLengthIn35mmFilm",
|
| 379 |
+
41990: "SceneCaptureType",
|
| 380 |
+
41991: "GainControl",
|
| 381 |
+
41992: "Contrast",
|
| 382 |
+
41993: "Saturation",
|
| 383 |
+
41994: "Sharpness",
|
| 384 |
+
41995: "DeviceSettingDescription",
|
| 385 |
+
41996: "SubjectDistanceRange",
|
| 386 |
+
42016: "ImageUniqueID",
|
| 387 |
+
42032: "CameraOwnerName",
|
| 388 |
+
42033: "BodySerialNumber",
|
| 389 |
+
42034: "LensSpecification",
|
| 390 |
+
42035: "LensMake",
|
| 391 |
+
42036: "LensModel",
|
| 392 |
+
42037: "LensSerialNumber",
|
| 393 |
+
42112: "GDAL_METADATA",
|
| 394 |
+
42113: "GDAL_NODATA",
|
| 395 |
+
42240: "Gamma",
|
| 396 |
+
50215: "Oce Scanjob Description",
|
| 397 |
+
50216: "Oce Application Selector",
|
| 398 |
+
50217: "Oce Identification Number",
|
| 399 |
+
50218: "Oce ImageLogic Characteristics",
|
| 400 |
+
# Adobe DNG
|
| 401 |
+
50706: "DNGVersion",
|
| 402 |
+
50707: "DNGBackwardVersion",
|
| 403 |
+
50708: "UniqueCameraModel",
|
| 404 |
+
50709: "LocalizedCameraModel",
|
| 405 |
+
50710: "CFAPlaneColor",
|
| 406 |
+
50711: "CFALayout",
|
| 407 |
+
50712: "LinearizationTable",
|
| 408 |
+
50713: "BlackLevelRepeatDim",
|
| 409 |
+
50714: "BlackLevel",
|
| 410 |
+
50715: "BlackLevelDeltaH",
|
| 411 |
+
50716: "BlackLevelDeltaV",
|
| 412 |
+
50717: "WhiteLevel",
|
| 413 |
+
50718: "DefaultScale",
|
| 414 |
+
50719: "DefaultCropOrigin",
|
| 415 |
+
50720: "DefaultCropSize",
|
| 416 |
+
50721: "ColorMatrix1",
|
| 417 |
+
50722: "ColorMatrix2",
|
| 418 |
+
50723: "CameraCalibration1",
|
| 419 |
+
50724: "CameraCalibration2",
|
| 420 |
+
50725: "ReductionMatrix1",
|
| 421 |
+
50726: "ReductionMatrix2",
|
| 422 |
+
50727: "AnalogBalance",
|
| 423 |
+
50728: "AsShotNeutral",
|
| 424 |
+
50729: "AsShotWhiteXY",
|
| 425 |
+
50730: "BaselineExposure",
|
| 426 |
+
50731: "BaselineNoise",
|
| 427 |
+
50732: "BaselineSharpness",
|
| 428 |
+
50733: "BayerGreenSplit",
|
| 429 |
+
50734: "LinearResponseLimit",
|
| 430 |
+
50735: "CameraSerialNumber",
|
| 431 |
+
50736: "LensInfo",
|
| 432 |
+
50737: "ChromaBlurRadius",
|
| 433 |
+
50738: "AntiAliasStrength",
|
| 434 |
+
50740: "DNGPrivateData",
|
| 435 |
+
50778: "CalibrationIlluminant1",
|
| 436 |
+
50779: "CalibrationIlluminant2",
|
| 437 |
+
50784: "Alias Layer Metadata",
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
TAGS_V2: dict[int, TagInfo] = {}
|
| 441 |
+
TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {}
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _populate() -> None:
|
| 445 |
+
for k, v in _tags_v2.items():
|
| 446 |
+
# Populate legacy structure.
|
| 447 |
+
TAGS[k] = v[0]
|
| 448 |
+
if len(v) == 4:
|
| 449 |
+
for sk, sv in v[3].items():
|
| 450 |
+
TAGS[(k, sv)] = sk
|
| 451 |
+
|
| 452 |
+
TAGS_V2[k] = TagInfo(k, *v)
|
| 453 |
+
|
| 454 |
+
for group, tags in _tags_v2_groups.items():
|
| 455 |
+
TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()}
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
_populate()
|
| 459 |
+
##
|
| 460 |
+
# Map type numbers to type names -- defined in ImageFileDirectory.
|
| 461 |
+
|
| 462 |
+
TYPES: dict[int, str] = {}
|
| 463 |
+
|
| 464 |
+
#
|
| 465 |
+
# These tags are handled by default in libtiff, without
|
| 466 |
+
# adding to the custom dictionary. From tif_dir.c, searching for
|
| 467 |
+
# case TIFFTAG in the _TIFFVSetField function:
|
| 468 |
+
# Line: item.
|
| 469 |
+
# 148: case TIFFTAG_SUBFILETYPE:
|
| 470 |
+
# 151: case TIFFTAG_IMAGEWIDTH:
|
| 471 |
+
# 154: case TIFFTAG_IMAGELENGTH:
|
| 472 |
+
# 157: case TIFFTAG_BITSPERSAMPLE:
|
| 473 |
+
# 181: case TIFFTAG_COMPRESSION:
|
| 474 |
+
# 202: case TIFFTAG_PHOTOMETRIC:
|
| 475 |
+
# 205: case TIFFTAG_THRESHHOLDING:
|
| 476 |
+
# 208: case TIFFTAG_FILLORDER:
|
| 477 |
+
# 214: case TIFFTAG_ORIENTATION:
|
| 478 |
+
# 221: case TIFFTAG_SAMPLESPERPIXEL:
|
| 479 |
+
# 228: case TIFFTAG_ROWSPERSTRIP:
|
| 480 |
+
# 238: case TIFFTAG_MINSAMPLEVALUE:
|
| 481 |
+
# 241: case TIFFTAG_MAXSAMPLEVALUE:
|
| 482 |
+
# 244: case TIFFTAG_SMINSAMPLEVALUE:
|
| 483 |
+
# 247: case TIFFTAG_SMAXSAMPLEVALUE:
|
| 484 |
+
# 250: case TIFFTAG_XRESOLUTION:
|
| 485 |
+
# 256: case TIFFTAG_YRESOLUTION:
|
| 486 |
+
# 262: case TIFFTAG_PLANARCONFIG:
|
| 487 |
+
# 268: case TIFFTAG_XPOSITION:
|
| 488 |
+
# 271: case TIFFTAG_YPOSITION:
|
| 489 |
+
# 274: case TIFFTAG_RESOLUTIONUNIT:
|
| 490 |
+
# 280: case TIFFTAG_PAGENUMBER:
|
| 491 |
+
# 284: case TIFFTAG_HALFTONEHINTS:
|
| 492 |
+
# 288: case TIFFTAG_COLORMAP:
|
| 493 |
+
# 294: case TIFFTAG_EXTRASAMPLES:
|
| 494 |
+
# 298: case TIFFTAG_MATTEING:
|
| 495 |
+
# 305: case TIFFTAG_TILEWIDTH:
|
| 496 |
+
# 316: case TIFFTAG_TILELENGTH:
|
| 497 |
+
# 327: case TIFFTAG_TILEDEPTH:
|
| 498 |
+
# 333: case TIFFTAG_DATATYPE:
|
| 499 |
+
# 344: case TIFFTAG_SAMPLEFORMAT:
|
| 500 |
+
# 361: case TIFFTAG_IMAGEDEPTH:
|
| 501 |
+
# 364: case TIFFTAG_SUBIFD:
|
| 502 |
+
# 376: case TIFFTAG_YCBCRPOSITIONING:
|
| 503 |
+
# 379: case TIFFTAG_YCBCRSUBSAMPLING:
|
| 504 |
+
# 383: case TIFFTAG_TRANSFERFUNCTION:
|
| 505 |
+
# 389: case TIFFTAG_REFERENCEBLACKWHITE:
|
| 506 |
+
# 393: case TIFFTAG_INKNAMES:
|
| 507 |
+
|
| 508 |
+
# Following pseudo-tags are also handled by default in libtiff:
|
| 509 |
+
# TIFFTAG_JPEGQUALITY 65537
|
| 510 |
+
|
| 511 |
+
# some of these are not in our TAGS_V2 dict and were included from tiff.h
|
| 512 |
+
|
| 513 |
+
# This list also exists in encode.c
|
| 514 |
+
LIBTIFF_CORE = {
|
| 515 |
+
255,
|
| 516 |
+
256,
|
| 517 |
+
257,
|
| 518 |
+
258,
|
| 519 |
+
259,
|
| 520 |
+
262,
|
| 521 |
+
263,
|
| 522 |
+
266,
|
| 523 |
+
274,
|
| 524 |
+
277,
|
| 525 |
+
278,
|
| 526 |
+
280,
|
| 527 |
+
281,
|
| 528 |
+
340,
|
| 529 |
+
341,
|
| 530 |
+
282,
|
| 531 |
+
283,
|
| 532 |
+
284,
|
| 533 |
+
286,
|
| 534 |
+
287,
|
| 535 |
+
296,
|
| 536 |
+
297,
|
| 537 |
+
321,
|
| 538 |
+
320,
|
| 539 |
+
338,
|
| 540 |
+
32995,
|
| 541 |
+
322,
|
| 542 |
+
323,
|
| 543 |
+
32998,
|
| 544 |
+
32996,
|
| 545 |
+
339,
|
| 546 |
+
32997,
|
| 547 |
+
330,
|
| 548 |
+
531,
|
| 549 |
+
530,
|
| 550 |
+
301,
|
| 551 |
+
532,
|
| 552 |
+
333,
|
| 553 |
+
# as above
|
| 554 |
+
269, # this has been in our tests forever, and works
|
| 555 |
+
65537,
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
|
| 559 |
+
LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
|
| 560 |
+
LIBTIFF_CORE.remove(323) # Tiled images
|
| 561 |
+
|
| 562 |
+
# Note to advanced users: There may be combinations of these
|
| 563 |
+
# parameters and values that when added properly, will work and
|
| 564 |
+
# produce valid tiff images that may work in your application.
|
| 565 |
+
# It is safe to add and remove tags from this set from Pillow's point
|
| 566 |
+
# of view so long as you test against libtiff.
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WalImageFile.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# WAL file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2003-04-23 fl created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2003 by Fredrik Lundh.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This reader is based on the specification available from:
|
| 17 |
+
https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
|
| 18 |
+
and has been tested with a few sample files found using google.
|
| 19 |
+
|
| 20 |
+
.. note::
|
| 21 |
+
This format cannot be automatically recognized, so the reader
|
| 22 |
+
is not registered for use with :py:func:`PIL.Image.open()`.
|
| 23 |
+
To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
from typing import IO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageFile
|
| 30 |
+
from ._binary import i32le as i32
|
| 31 |
+
from ._typing import StrOrBytesPath
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class WalImageFile(ImageFile.ImageFile):
|
| 35 |
+
format = "WAL"
|
| 36 |
+
format_description = "Quake2 Texture"
|
| 37 |
+
|
| 38 |
+
def _open(self) -> None:
|
| 39 |
+
self._mode = "P"
|
| 40 |
+
|
| 41 |
+
# read header fields
|
| 42 |
+
assert self.fp is not None
|
| 43 |
+
header = self.fp.read(32 + 24 + 32 + 12)
|
| 44 |
+
self._size = i32(header, 32), i32(header, 36)
|
| 45 |
+
Image._decompression_bomb_check(self.size)
|
| 46 |
+
|
| 47 |
+
# load pixel data
|
| 48 |
+
offset = i32(header, 40)
|
| 49 |
+
self.fp.seek(offset)
|
| 50 |
+
|
| 51 |
+
# strings are null-terminated
|
| 52 |
+
self.info["name"] = header[:32].split(b"\0", 1)[0]
|
| 53 |
+
if next_name := header[56 : 56 + 32].split(b"\0", 1)[0]:
|
| 54 |
+
self.info["next_name"] = next_name
|
| 55 |
+
|
| 56 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 57 |
+
if self._im is None:
|
| 58 |
+
assert self.fp is not None
|
| 59 |
+
self.im = Image.core.new(self.mode, self.size)
|
| 60 |
+
self.frombytes(self.fp.read(self.size[0] * self.size[1]))
|
| 61 |
+
self.putpalette(quake2palette)
|
| 62 |
+
return Image.Image.load(self)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile:
|
| 66 |
+
"""
|
| 67 |
+
Load texture from a Quake2 WAL texture file.
|
| 68 |
+
|
| 69 |
+
By default, a Quake2 standard palette is attached to the texture.
|
| 70 |
+
To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
|
| 71 |
+
|
| 72 |
+
:param filename: WAL file name, or an opened file handle.
|
| 73 |
+
:returns: An image instance.
|
| 74 |
+
"""
|
| 75 |
+
return WalImageFile(filename)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
quake2palette = (
|
| 79 |
+
# default palette taken from piffo 0.93 by Hans Häggström
|
| 80 |
+
b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
|
| 81 |
+
b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
|
| 82 |
+
b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
|
| 83 |
+
b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
|
| 84 |
+
b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
|
| 85 |
+
b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
|
| 86 |
+
b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
|
| 87 |
+
b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
|
| 88 |
+
b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
|
| 89 |
+
b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
|
| 90 |
+
b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
|
| 91 |
+
b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
|
| 92 |
+
b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
|
| 93 |
+
b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
|
| 94 |
+
b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
|
| 95 |
+
b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
|
| 96 |
+
b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
|
| 97 |
+
b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
|
| 98 |
+
b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
|
| 99 |
+
b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
|
| 100 |
+
b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
|
| 101 |
+
b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
|
| 102 |
+
b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
|
| 103 |
+
b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
|
| 104 |
+
b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
|
| 105 |
+
b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
|
| 106 |
+
b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
|
| 107 |
+
b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
|
| 108 |
+
b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
|
| 109 |
+
b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
|
| 110 |
+
b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
|
| 111 |
+
b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
|
| 112 |
+
b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
|
| 113 |
+
b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
|
| 114 |
+
b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
|
| 115 |
+
b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
|
| 116 |
+
b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
|
| 117 |
+
b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
|
| 118 |
+
b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
|
| 119 |
+
b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
|
| 120 |
+
b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
|
| 121 |
+
b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
|
| 122 |
+
b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
|
| 123 |
+
b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
|
| 124 |
+
b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
|
| 125 |
+
b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
|
| 126 |
+
b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
|
| 127 |
+
b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
|
| 128 |
+
)
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
|
| 5 |
+
from . import Image, ImageFile
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from . import _webp
|
| 9 |
+
|
| 10 |
+
SUPPORTED = True
|
| 11 |
+
except ImportError:
|
| 12 |
+
SUPPORTED = False
|
| 13 |
+
|
| 14 |
+
TYPE_CHECKING = False
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from typing import IO, Any
|
| 17 |
+
|
| 18 |
+
_VP8_MODES_BY_IDENTIFIER = {
|
| 19 |
+
b"VP8 ": "RGB",
|
| 20 |
+
b"VP8X": "RGBA",
|
| 21 |
+
b"VP8L": "RGBA", # lossless
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _accept(prefix: bytes) -> bool | str:
|
| 26 |
+
is_riff_file_format = prefix.startswith(b"RIFF")
|
| 27 |
+
is_webp_file = prefix[8:12] == b"WEBP"
|
| 28 |
+
is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
|
| 29 |
+
|
| 30 |
+
if is_riff_file_format and is_webp_file and is_valid_vp8_mode:
|
| 31 |
+
if not SUPPORTED:
|
| 32 |
+
return (
|
| 33 |
+
"image file could not be identified because WEBP support not installed"
|
| 34 |
+
)
|
| 35 |
+
return True
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class WebPImageFile(ImageFile.ImageFile):
|
| 40 |
+
format = "WEBP"
|
| 41 |
+
format_description = "WebP image"
|
| 42 |
+
__loaded = 0
|
| 43 |
+
__logical_frame = 0
|
| 44 |
+
|
| 45 |
+
def _open(self) -> None:
|
| 46 |
+
# Use the newer AnimDecoder API to parse the (possibly) animated file,
|
| 47 |
+
# and access muxed chunks like ICC/EXIF/XMP.
|
| 48 |
+
assert self.fp is not None
|
| 49 |
+
self._decoder = _webp.WebPAnimDecoder(self.fp.read())
|
| 50 |
+
|
| 51 |
+
# Get info from decoder
|
| 52 |
+
self._size, self.info["loop"], bgcolor, self.n_frames, self.rawmode = (
|
| 53 |
+
self._decoder.get_info()
|
| 54 |
+
)
|
| 55 |
+
self.info["background"] = (
|
| 56 |
+
(bgcolor >> 16) & 0xFF, # R
|
| 57 |
+
(bgcolor >> 8) & 0xFF, # G
|
| 58 |
+
bgcolor & 0xFF, # B
|
| 59 |
+
(bgcolor >> 24) & 0xFF, # A
|
| 60 |
+
)
|
| 61 |
+
self.is_animated = self.n_frames > 1
|
| 62 |
+
self._mode = "RGB" if self.rawmode == "RGBX" else self.rawmode
|
| 63 |
+
|
| 64 |
+
# Attempt to read ICC / EXIF / XMP chunks from file
|
| 65 |
+
for key, chunk_name in {
|
| 66 |
+
"icc_profile": "ICCP",
|
| 67 |
+
"exif": "EXIF",
|
| 68 |
+
"xmp": "XMP ",
|
| 69 |
+
}.items():
|
| 70 |
+
if value := self._decoder.get_chunk(chunk_name):
|
| 71 |
+
self.info[key] = value
|
| 72 |
+
|
| 73 |
+
# Initialize seek state
|
| 74 |
+
self._reset(reset=False)
|
| 75 |
+
|
| 76 |
+
def _getexif(self) -> dict[int, Any] | None:
|
| 77 |
+
if "exif" not in self.info:
|
| 78 |
+
return None
|
| 79 |
+
return self.getexif()._get_merged_dict()
|
| 80 |
+
|
| 81 |
+
def seek(self, frame: int) -> None:
|
| 82 |
+
if not self._seek_check(frame):
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
# Set logical frame to requested position
|
| 86 |
+
self.__logical_frame = frame
|
| 87 |
+
|
| 88 |
+
def _reset(self, reset: bool = True) -> None:
|
| 89 |
+
if reset:
|
| 90 |
+
self._decoder.reset()
|
| 91 |
+
self.__physical_frame = 0
|
| 92 |
+
self.__loaded = -1
|
| 93 |
+
self.__timestamp = 0
|
| 94 |
+
|
| 95 |
+
def _get_next(self) -> tuple[bytes, int, int]:
|
| 96 |
+
# Get next frame
|
| 97 |
+
ret = self._decoder.get_next()
|
| 98 |
+
self.__physical_frame += 1
|
| 99 |
+
|
| 100 |
+
# Check if an error occurred
|
| 101 |
+
if ret is None:
|
| 102 |
+
self._reset() # Reset just to be safe
|
| 103 |
+
self.seek(0)
|
| 104 |
+
msg = "failed to decode next frame in WebP file"
|
| 105 |
+
raise EOFError(msg)
|
| 106 |
+
|
| 107 |
+
# Compute duration
|
| 108 |
+
data, timestamp = ret
|
| 109 |
+
duration = timestamp - self.__timestamp
|
| 110 |
+
self.__timestamp = timestamp
|
| 111 |
+
|
| 112 |
+
# libwebp gives frame end, adjust to start of frame
|
| 113 |
+
timestamp -= duration
|
| 114 |
+
return data, timestamp, duration
|
| 115 |
+
|
| 116 |
+
def _seek(self, frame: int) -> None:
|
| 117 |
+
if self.__physical_frame == frame:
|
| 118 |
+
return # Nothing to do
|
| 119 |
+
if frame < self.__physical_frame:
|
| 120 |
+
self._reset() # Rewind to beginning
|
| 121 |
+
while self.__physical_frame < frame:
|
| 122 |
+
self._get_next() # Advance to the requested frame
|
| 123 |
+
|
| 124 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 125 |
+
if self.__loaded != self.__logical_frame:
|
| 126 |
+
self._seek(self.__logical_frame)
|
| 127 |
+
|
| 128 |
+
# We need to load the image data for this frame
|
| 129 |
+
data, self.info["timestamp"], self.info["duration"] = self._get_next()
|
| 130 |
+
self.__loaded = self.__logical_frame
|
| 131 |
+
|
| 132 |
+
# Set tile
|
| 133 |
+
if self.fp and self._exclusive_fp:
|
| 134 |
+
self.fp.close()
|
| 135 |
+
self.fp = BytesIO(data)
|
| 136 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)]
|
| 137 |
+
|
| 138 |
+
return super().load()
|
| 139 |
+
|
| 140 |
+
def load_seek(self, pos: int) -> None:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
def tell(self) -> int:
|
| 144 |
+
return self.__logical_frame
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _convert_frame(im: Image.Image) -> Image.Image:
|
| 148 |
+
# Make sure image mode is supported
|
| 149 |
+
if im.mode not in ("RGBX", "RGBA", "RGB"):
|
| 150 |
+
im = im.convert("RGBA" if im.has_transparency_data else "RGB")
|
| 151 |
+
return im
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 155 |
+
encoderinfo = im.encoderinfo.copy()
|
| 156 |
+
append_images = list(encoderinfo.get("append_images", []))
|
| 157 |
+
|
| 158 |
+
# If total frame count is 1, then save using the legacy API, which
|
| 159 |
+
# will preserve non-alpha modes
|
| 160 |
+
total = 0
|
| 161 |
+
for ims in [im] + append_images:
|
| 162 |
+
total += getattr(ims, "n_frames", 1)
|
| 163 |
+
if total == 1:
|
| 164 |
+
_save(im, fp, filename)
|
| 165 |
+
return
|
| 166 |
+
|
| 167 |
+
background: int | tuple[int, ...] = (0, 0, 0, 0)
|
| 168 |
+
if "background" in encoderinfo:
|
| 169 |
+
background = encoderinfo["background"]
|
| 170 |
+
elif "background" in im.info:
|
| 171 |
+
background = im.info["background"]
|
| 172 |
+
if isinstance(background, int):
|
| 173 |
+
# GifImagePlugin stores a global color table index in
|
| 174 |
+
# info["background"]. So it must be converted to an RGBA value
|
| 175 |
+
palette = im.getpalette()
|
| 176 |
+
if palette:
|
| 177 |
+
r, g, b = palette[background * 3 : (background + 1) * 3]
|
| 178 |
+
background = (r, g, b, 255)
|
| 179 |
+
else:
|
| 180 |
+
background = (background, background, background, 255)
|
| 181 |
+
|
| 182 |
+
duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
|
| 183 |
+
loop = im.encoderinfo.get("loop", 0)
|
| 184 |
+
minimize_size = im.encoderinfo.get("minimize_size", False)
|
| 185 |
+
kmin = im.encoderinfo.get("kmin", None)
|
| 186 |
+
kmax = im.encoderinfo.get("kmax", None)
|
| 187 |
+
allow_mixed = im.encoderinfo.get("allow_mixed", False)
|
| 188 |
+
verbose = False
|
| 189 |
+
lossless = im.encoderinfo.get("lossless", False)
|
| 190 |
+
quality = im.encoderinfo.get("quality", 80)
|
| 191 |
+
alpha_quality = im.encoderinfo.get("alpha_quality", 100)
|
| 192 |
+
method = im.encoderinfo.get("method", 0)
|
| 193 |
+
icc_profile = im.encoderinfo.get("icc_profile") or ""
|
| 194 |
+
exif = im.encoderinfo.get("exif", "")
|
| 195 |
+
if isinstance(exif, Image.Exif):
|
| 196 |
+
exif = exif.tobytes()
|
| 197 |
+
xmp = im.encoderinfo.get("xmp", "")
|
| 198 |
+
if allow_mixed:
|
| 199 |
+
lossless = False
|
| 200 |
+
|
| 201 |
+
# Sensible keyframe defaults are from gif2webp.c script
|
| 202 |
+
if kmin is None:
|
| 203 |
+
kmin = 9 if lossless else 3
|
| 204 |
+
if kmax is None:
|
| 205 |
+
kmax = 17 if lossless else 5
|
| 206 |
+
|
| 207 |
+
# Validate background color
|
| 208 |
+
if (
|
| 209 |
+
not isinstance(background, (list, tuple))
|
| 210 |
+
or len(background) != 4
|
| 211 |
+
or not all(0 <= v < 256 for v in background)
|
| 212 |
+
):
|
| 213 |
+
msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"
|
| 214 |
+
raise OSError(msg)
|
| 215 |
+
|
| 216 |
+
# Convert to packed uint
|
| 217 |
+
bg_r, bg_g, bg_b, bg_a = background
|
| 218 |
+
background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0)
|
| 219 |
+
|
| 220 |
+
# Setup the WebP animation encoder
|
| 221 |
+
enc = _webp.WebPAnimEncoder(
|
| 222 |
+
im.size,
|
| 223 |
+
background,
|
| 224 |
+
loop,
|
| 225 |
+
minimize_size,
|
| 226 |
+
kmin,
|
| 227 |
+
kmax,
|
| 228 |
+
allow_mixed,
|
| 229 |
+
verbose,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# Add each frame
|
| 233 |
+
frame_idx = 0
|
| 234 |
+
timestamp = 0
|
| 235 |
+
cur_idx = im.tell()
|
| 236 |
+
try:
|
| 237 |
+
for ims in [im] + append_images:
|
| 238 |
+
# Get number of frames in this image
|
| 239 |
+
nfr = getattr(ims, "n_frames", 1)
|
| 240 |
+
|
| 241 |
+
for idx in range(nfr):
|
| 242 |
+
ims.seek(idx)
|
| 243 |
+
|
| 244 |
+
frame = _convert_frame(ims)
|
| 245 |
+
|
| 246 |
+
# Append the frame to the animation encoder
|
| 247 |
+
enc.add(
|
| 248 |
+
frame.getim(),
|
| 249 |
+
round(timestamp),
|
| 250 |
+
lossless,
|
| 251 |
+
quality,
|
| 252 |
+
alpha_quality,
|
| 253 |
+
method,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
# Update timestamp and frame index
|
| 257 |
+
if isinstance(duration, (list, tuple)):
|
| 258 |
+
timestamp += duration[frame_idx]
|
| 259 |
+
else:
|
| 260 |
+
timestamp += duration
|
| 261 |
+
frame_idx += 1
|
| 262 |
+
|
| 263 |
+
finally:
|
| 264 |
+
im.seek(cur_idx)
|
| 265 |
+
|
| 266 |
+
# Force encoder to flush frames
|
| 267 |
+
enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0)
|
| 268 |
+
|
| 269 |
+
# Get the final output from the encoder
|
| 270 |
+
data = enc.assemble(icc_profile, exif, xmp)
|
| 271 |
+
if data is None:
|
| 272 |
+
msg = "cannot write file as WebP (encoder returned None)"
|
| 273 |
+
raise OSError(msg)
|
| 274 |
+
|
| 275 |
+
fp.write(data)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 279 |
+
lossless = im.encoderinfo.get("lossless", False)
|
| 280 |
+
quality = im.encoderinfo.get("quality", 80)
|
| 281 |
+
alpha_quality = im.encoderinfo.get("alpha_quality", 100)
|
| 282 |
+
icc_profile = im.encoderinfo.get("icc_profile") or ""
|
| 283 |
+
exif = im.encoderinfo.get("exif", b"")
|
| 284 |
+
if isinstance(exif, Image.Exif):
|
| 285 |
+
exif = exif.tobytes()
|
| 286 |
+
if exif.startswith(b"Exif\x00\x00"):
|
| 287 |
+
exif = exif[6:]
|
| 288 |
+
xmp = im.encoderinfo.get("xmp", "")
|
| 289 |
+
method = im.encoderinfo.get("method", 4)
|
| 290 |
+
exact = 1 if im.encoderinfo.get("exact") else 0
|
| 291 |
+
|
| 292 |
+
im = _convert_frame(im)
|
| 293 |
+
|
| 294 |
+
data = _webp.WebPEncode(
|
| 295 |
+
im.getim(),
|
| 296 |
+
lossless,
|
| 297 |
+
float(quality),
|
| 298 |
+
float(alpha_quality),
|
| 299 |
+
icc_profile,
|
| 300 |
+
method,
|
| 301 |
+
exact,
|
| 302 |
+
exif,
|
| 303 |
+
xmp,
|
| 304 |
+
)
|
| 305 |
+
if data is None:
|
| 306 |
+
msg = "cannot write file as WebP (encoder returned None)"
|
| 307 |
+
raise OSError(msg)
|
| 308 |
+
|
| 309 |
+
fp.write(data)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
|
| 313 |
+
if SUPPORTED:
|
| 314 |
+
Image.register_save(WebPImageFile.format, _save)
|
| 315 |
+
Image.register_save_all(WebPImageFile.format, _save_all)
|
| 316 |
+
Image.register_extension(WebPImageFile.format, ".webp")
|
| 317 |
+
Image.register_mime(WebPImageFile.format, "image/webp")
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# WMF stub codec
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1996-12-14 fl Created
|
| 9 |
+
# 2004-02-22 fl Turned into a stub driver
|
| 10 |
+
# 2004-02-23 fl Added EMF support
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
# WMF/EMF reference documentation:
|
| 18 |
+
# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf
|
| 19 |
+
# http://wvware.sourceforge.net/caolan/index.html
|
| 20 |
+
# http://wvware.sourceforge.net/caolan/ora-wmf.html
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from typing import IO
|
| 24 |
+
|
| 25 |
+
from . import Image, ImageFile
|
| 26 |
+
from ._binary import i16le as word
|
| 27 |
+
from ._binary import si16le as short
|
| 28 |
+
from ._binary import si32le as _long
|
| 29 |
+
|
| 30 |
+
_handler = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 34 |
+
"""
|
| 35 |
+
Install application-specific WMF image handler.
|
| 36 |
+
|
| 37 |
+
:param handler: Handler object.
|
| 38 |
+
"""
|
| 39 |
+
global _handler
|
| 40 |
+
_handler = handler
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if hasattr(Image.core, "drawwmf"):
|
| 44 |
+
# install default handler (windows only)
|
| 45 |
+
|
| 46 |
+
class WmfHandler(ImageFile.StubHandler):
|
| 47 |
+
def open(self, im: ImageFile.StubImageFile) -> None:
|
| 48 |
+
im._mode = "RGB"
|
| 49 |
+
self.bbox = im.info["wmf_bbox"]
|
| 50 |
+
|
| 51 |
+
def load(self, im: ImageFile.StubImageFile) -> Image.Image:
|
| 52 |
+
assert im.fp is not None
|
| 53 |
+
im.fp.seek(0) # rewind
|
| 54 |
+
return Image.frombytes(
|
| 55 |
+
"RGB",
|
| 56 |
+
im.size,
|
| 57 |
+
Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
|
| 58 |
+
"raw",
|
| 59 |
+
"BGR",
|
| 60 |
+
(im.size[0] * 3 + 3) & -4,
|
| 61 |
+
-1,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
register_handler(WmfHandler())
|
| 65 |
+
|
| 66 |
+
#
|
| 67 |
+
# --------------------------------------------------------------------
|
| 68 |
+
# Read WMF file
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _accept(prefix: bytes) -> bool:
|
| 72 |
+
return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
##
|
| 76 |
+
# Image plugin for Windows metafiles.
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class WmfStubImageFile(ImageFile.StubImageFile):
|
| 80 |
+
format = "WMF"
|
| 81 |
+
format_description = "Windows Metafile"
|
| 82 |
+
|
| 83 |
+
def _open(self) -> None:
|
| 84 |
+
# check placeable header
|
| 85 |
+
assert self.fp is not None
|
| 86 |
+
s = self.fp.read(44)
|
| 87 |
+
|
| 88 |
+
if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
|
| 89 |
+
# placeable windows metafile
|
| 90 |
+
|
| 91 |
+
# get units per inch
|
| 92 |
+
inch = word(s, 14)
|
| 93 |
+
if inch == 0:
|
| 94 |
+
msg = "Invalid inch"
|
| 95 |
+
raise ValueError(msg)
|
| 96 |
+
self._inch: tuple[float, float] = inch, inch
|
| 97 |
+
|
| 98 |
+
# get bounding box
|
| 99 |
+
x0 = short(s, 6)
|
| 100 |
+
y0 = short(s, 8)
|
| 101 |
+
x1 = short(s, 10)
|
| 102 |
+
y1 = short(s, 12)
|
| 103 |
+
|
| 104 |
+
# normalize size to 72 dots per inch
|
| 105 |
+
self.info["dpi"] = 72
|
| 106 |
+
size = (
|
| 107 |
+
(x1 - x0) * self.info["dpi"] // inch,
|
| 108 |
+
(y1 - y0) * self.info["dpi"] // inch,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 112 |
+
|
| 113 |
+
# sanity check (standard metafile header)
|
| 114 |
+
if s[22:26] != b"\x01\x00\t\x00":
|
| 115 |
+
msg = "Unsupported WMF file format"
|
| 116 |
+
raise SyntaxError(msg)
|
| 117 |
+
|
| 118 |
+
elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
|
| 119 |
+
# enhanced metafile
|
| 120 |
+
|
| 121 |
+
# get bounding box
|
| 122 |
+
x0 = _long(s, 8)
|
| 123 |
+
y0 = _long(s, 12)
|
| 124 |
+
x1 = _long(s, 16)
|
| 125 |
+
y1 = _long(s, 20)
|
| 126 |
+
|
| 127 |
+
# get frame (in 0.01 millimeter units)
|
| 128 |
+
frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
|
| 129 |
+
|
| 130 |
+
size = x1 - x0, y1 - y0
|
| 131 |
+
|
| 132 |
+
# calculate dots per inch from bbox and frame
|
| 133 |
+
xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
|
| 134 |
+
ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
|
| 135 |
+
|
| 136 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 137 |
+
|
| 138 |
+
if xdpi == ydpi:
|
| 139 |
+
self.info["dpi"] = xdpi
|
| 140 |
+
else:
|
| 141 |
+
self.info["dpi"] = xdpi, ydpi
|
| 142 |
+
self._inch = xdpi, ydpi
|
| 143 |
+
|
| 144 |
+
else:
|
| 145 |
+
msg = "Unsupported file format"
|
| 146 |
+
raise SyntaxError(msg)
|
| 147 |
+
|
| 148 |
+
self._mode = "RGB"
|
| 149 |
+
self._size = size
|
| 150 |
+
|
| 151 |
+
loader = self._load()
|
| 152 |
+
if loader:
|
| 153 |
+
loader.open(self)
|
| 154 |
+
|
| 155 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 156 |
+
return _handler
|
| 157 |
+
|
| 158 |
+
def load(
|
| 159 |
+
self, dpi: float | tuple[float, float] | None = None
|
| 160 |
+
) -> Image.core.PixelAccess | None:
|
| 161 |
+
if dpi is not None:
|
| 162 |
+
self.info["dpi"] = dpi
|
| 163 |
+
x0, y0, x1, y1 = self.info["wmf_bbox"]
|
| 164 |
+
if not isinstance(dpi, tuple):
|
| 165 |
+
dpi = dpi, dpi
|
| 166 |
+
self._size = (
|
| 167 |
+
int((x1 - x0) * dpi[0] / self._inch[0]),
|
| 168 |
+
int((y1 - y0) * dpi[1] / self._inch[1]),
|
| 169 |
+
)
|
| 170 |
+
return super().load()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 174 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 175 |
+
msg = "WMF save handler not installed"
|
| 176 |
+
raise OSError(msg)
|
| 177 |
+
_handler.save(im, fp, filename)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
#
|
| 181 |
+
# --------------------------------------------------------------------
|
| 182 |
+
# Registry stuff
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
|
| 186 |
+
Image.register_save(WmfStubImageFile.format, _save)
|
| 187 |
+
|
| 188 |
+
Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])
|
workspace/outputs/audit_venv/lib/python3.11/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 |
+
w, h = s.strip().split(maxsplit=2)[:2]
|
| 70 |
+
|
| 71 |
+
self._mode = "P"
|
| 72 |
+
self._size = int(w), int(h)
|
| 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)
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/XbmImagePlugin.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# XBM File handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-09-08 fl Created
|
| 9 |
+
# 1996-11-01 fl Added save support
|
| 10 |
+
# 1997-07-07 fl Made header parser more tolerant
|
| 11 |
+
# 1997-07-22 fl Fixed yet another parser bug
|
| 12 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
|
| 13 |
+
# 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog)
|
| 14 |
+
# 2004-02-24 fl Allow some whitespace before first #define
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) 1997-2004 by Secret Labs AB
|
| 17 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh
|
| 18 |
+
#
|
| 19 |
+
# See the README file for information on usage and redistribution.
|
| 20 |
+
#
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
from typing import IO
|
| 25 |
+
|
| 26 |
+
from . import Image, ImageFile
|
| 27 |
+
|
| 28 |
+
# XBM header
|
| 29 |
+
xbm_head = re.compile(
|
| 30 |
+
rb"\s*#define[ \t]+.*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"
|
| 31 |
+
b"#define[ \t]+.*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"
|
| 32 |
+
b"(?P<hotspot>"
|
| 33 |
+
b"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"
|
| 34 |
+
b"#define[ \t]+[^_]*_y_hot[ \t]+(?P<yhot>[0-9]+)[\r\n]+"
|
| 35 |
+
b")?"
|
| 36 |
+
rb"[\000-\377]*_bits\[]"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _accept(prefix: bytes) -> bool:
|
| 41 |
+
return prefix.lstrip().startswith(b"#define")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
##
|
| 45 |
+
# Image plugin for X11 bitmaps.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class XbmImageFile(ImageFile.ImageFile):
|
| 49 |
+
format = "XBM"
|
| 50 |
+
format_description = "X11 Bitmap"
|
| 51 |
+
|
| 52 |
+
def _open(self) -> None:
|
| 53 |
+
assert self.fp is not None
|
| 54 |
+
|
| 55 |
+
m = xbm_head.match(self.fp.read(512))
|
| 56 |
+
|
| 57 |
+
if not m:
|
| 58 |
+
msg = "not a XBM file"
|
| 59 |
+
raise SyntaxError(msg)
|
| 60 |
+
|
| 61 |
+
xsize = int(m.group("width"))
|
| 62 |
+
ysize = int(m.group("height"))
|
| 63 |
+
|
| 64 |
+
if m.group("hotspot"):
|
| 65 |
+
self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot")))
|
| 66 |
+
|
| 67 |
+
self._mode = "1"
|
| 68 |
+
self._size = xsize, ysize
|
| 69 |
+
|
| 70 |
+
self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end())]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 74 |
+
if im.mode != "1":
|
| 75 |
+
msg = f"cannot write mode {im.mode} as XBM"
|
| 76 |
+
raise OSError(msg)
|
| 77 |
+
|
| 78 |
+
fp.write(f"#define im_width {im.size[0]}\n".encode("ascii"))
|
| 79 |
+
fp.write(f"#define im_height {im.size[1]}\n".encode("ascii"))
|
| 80 |
+
|
| 81 |
+
hotspot = im.encoderinfo.get("hotspot")
|
| 82 |
+
if hotspot:
|
| 83 |
+
fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii"))
|
| 84 |
+
fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii"))
|
| 85 |
+
|
| 86 |
+
fp.write(b"static char im_bits[] = {\n")
|
| 87 |
+
|
| 88 |
+
ImageFile._save(im, fp, [ImageFile._Tile("xbm", (0, 0) + im.size)])
|
| 89 |
+
|
| 90 |
+
fp.write(b"};\n")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
Image.register_open(XbmImageFile.format, XbmImageFile, _accept)
|
| 94 |
+
Image.register_save(XbmImageFile.format, _save)
|
| 95 |
+
|
| 96 |
+
Image.register_extension(XbmImageFile.format, ".xbm")
|
| 97 |
+
|
| 98 |
+
Image.register_mime(XbmImageFile.format, "image/xbm")
|
workspace/outputs/audit_venv/lib/python3.11/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")
|
workspace/outputs/audit_venv/lib/python3.11/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
|
workspace/outputs/audit_venv/lib/python3.11/site-packages/PIL/__main__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from .features import pilinfo
|
| 6 |
+
|
| 7 |
+
pilinfo(supported_formats="--report" not in sys.argv)
|