Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- lib/python3.10/site-packages/PIL/BdfFontFile.py +133 -0
- lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py +76 -0
- lib/python3.10/site-packages/PIL/ContainerIO.py +173 -0
- lib/python3.10/site-packages/PIL/DdsImagePlugin.py +573 -0
- lib/python3.10/site-packages/PIL/FtexImagePlugin.py +115 -0
- lib/python3.10/site-packages/PIL/GdImageFile.py +102 -0
- lib/python3.10/site-packages/PIL/GimpGradientFile.py +149 -0
- lib/python3.10/site-packages/PIL/Hdf5StubImagePlugin.py +76 -0
- lib/python3.10/site-packages/PIL/ImageChops.py +311 -0
- lib/python3.10/site-packages/PIL/ImageCms.py +1125 -0
- lib/python3.10/site-packages/PIL/ImageColor.py +320 -0
- lib/python3.10/site-packages/PIL/ImageDraw.py +1218 -0
- lib/python3.10/site-packages/PIL/ImageDraw2.py +243 -0
- lib/python3.10/site-packages/PIL/ImageFilter.py +605 -0
- lib/python3.10/site-packages/PIL/ImageGrab.py +183 -0
- lib/python3.10/site-packages/PIL/ImageMorph.py +265 -0
- lib/python3.10/site-packages/PIL/ImagePath.py +20 -0
- lib/python3.10/site-packages/PIL/ImageShow.py +360 -0
- lib/python3.10/site-packages/PIL/McIdasImagePlugin.py +80 -0
- lib/python3.10/site-packages/PIL/MicImagePlugin.py +107 -0
- lib/python3.10/site-packages/PIL/MpoImagePlugin.py +190 -0
- lib/python3.10/site-packages/PIL/PcfFontFile.py +254 -0
- lib/python3.10/site-packages/PIL/PdfImagePlugin.py +311 -0
- lib/python3.10/site-packages/PIL/PsdImagePlugin.py +332 -0
- lib/python3.10/site-packages/PIL/TiffImagePlugin.py +2297 -0
- lib/python3.10/site-packages/PIL/TiffTags.py +562 -0
- lib/python3.10/site-packages/PIL/WmfImagePlugin.py +184 -0
- lib/python3.10/site-packages/PIL/XbmImagePlugin.py +98 -0
- lib/python3.10/site-packages/PIL/__main__.py +7 -0
- lib/python3.10/site-packages/PIL/_deprecate.py +69 -0
- lib/python3.10/site-packages/PIL/_imagingmath.pyi +3 -0
- lib/python3.10/site-packages/PIL/_imagingmorph.cpython-310-x86_64-linux-gnu.so +0 -0
- lib/python3.10/site-packages/PIL/_imagingmorph.pyi +3 -0
- lib/python3.10/site-packages/PIL/_imagingtk.cpython-310-x86_64-linux-gnu.so +0 -0
- lib/python3.10/site-packages/PIL/_imagingtk.pyi +3 -0
- lib/python3.10/site-packages/PIL/_webp.cpython-310-x86_64-linux-gnu.so +0 -0
- lib/python3.10/site-packages/PIL/_webp.pyi +3 -0
- lib/python3.10/site-packages/PIL/features.py +357 -0
- lib/python3.10/site-packages/PIL/report.py +5 -0
- lib/python3.10/site-packages/av/codec/hwaccel.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/av/filter/context.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/av/filter/link.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/av/filter/loudnorm.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/AUTHORS +4 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/INSTALLER +1 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/LICENSE +42 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/METADATA +32 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/RECORD +33 -0
- lib/python3.10/site-packages/gitdb-4.0.12.dist-info/REQUESTED +0 -0
.gitattributes
CHANGED
|
@@ -108,3 +108,7 @@ lib/python3.10/site-packages/av/filter/filter.cpython-310-x86_64-linux-gnu.so fi
|
|
| 108 |
lib/python3.10/site-packages/av/filter/pad.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 109 |
lib/python3.10/site-packages/av/filter/graph.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 110 |
lib/python3.10/site-packages/av/audio/format.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
lib/python3.10/site-packages/av/filter/pad.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 109 |
lib/python3.10/site-packages/av/filter/graph.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 110 |
lib/python3.10/site-packages/av/audio/format.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 111 |
+
lib/python3.10/site-packages/av/filter/link.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 112 |
+
lib/python3.10/site-packages/av/codec/hwaccel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 113 |
+
lib/python3.10/site-packages/av/filter/context.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 114 |
+
lib/python3.10/site-packages/av/filter/loudnorm.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
lib/python3.10/site-packages/PIL/BdfFontFile.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# bitmap distribution font (bdf) file parser
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1996-05-16 fl created (as bdf2pil)
|
| 9 |
+
# 1997-08-25 fl converted to FontFile driver
|
| 10 |
+
# 2001-05-25 fl removed bogus __init__ call
|
| 11 |
+
# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
|
| 12 |
+
# 2003-04-22 fl more robustification (from Graham Dumpleton)
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 15 |
+
# Copyright (c) 1997-2003 by Fredrik Lundh.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
Parse X Bitmap Distribution Format (BDF)
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
from typing import BinaryIO
|
| 26 |
+
|
| 27 |
+
from . import FontFile, Image
|
| 28 |
+
|
| 29 |
+
bdf_slant = {
|
| 30 |
+
"R": "Roman",
|
| 31 |
+
"I": "Italic",
|
| 32 |
+
"O": "Oblique",
|
| 33 |
+
"RI": "Reverse Italic",
|
| 34 |
+
"RO": "Reverse Oblique",
|
| 35 |
+
"OT": "Other",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def bdf_char(
|
| 42 |
+
f: BinaryIO,
|
| 43 |
+
) -> (
|
| 44 |
+
tuple[
|
| 45 |
+
str,
|
| 46 |
+
int,
|
| 47 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
|
| 48 |
+
Image.Image,
|
| 49 |
+
]
|
| 50 |
+
| None
|
| 51 |
+
):
|
| 52 |
+
# skip to STARTCHAR
|
| 53 |
+
while True:
|
| 54 |
+
s = f.readline()
|
| 55 |
+
if not s:
|
| 56 |
+
return None
|
| 57 |
+
if s[:9] == b"STARTCHAR":
|
| 58 |
+
break
|
| 59 |
+
id = s[9:].strip().decode("ascii")
|
| 60 |
+
|
| 61 |
+
# load symbol properties
|
| 62 |
+
props = {}
|
| 63 |
+
while True:
|
| 64 |
+
s = f.readline()
|
| 65 |
+
if not s or s[:6] == b"BITMAP":
|
| 66 |
+
break
|
| 67 |
+
i = s.find(b" ")
|
| 68 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
| 69 |
+
|
| 70 |
+
# load bitmap
|
| 71 |
+
bitmap = bytearray()
|
| 72 |
+
while True:
|
| 73 |
+
s = f.readline()
|
| 74 |
+
if not s or s[:7] == b"ENDCHAR":
|
| 75 |
+
break
|
| 76 |
+
bitmap += s[:-1]
|
| 77 |
+
|
| 78 |
+
# The word BBX
|
| 79 |
+
# followed by the width in x (BBw), height in y (BBh),
|
| 80 |
+
# and x and y displacement (BBxoff0, BByoff0)
|
| 81 |
+
# of the lower left corner from the origin of the character.
|
| 82 |
+
width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
|
| 83 |
+
|
| 84 |
+
# The word DWIDTH
|
| 85 |
+
# followed by the width in x and y of the character in device pixels.
|
| 86 |
+
dwx, dwy = (int(p) for p in props["DWIDTH"].split())
|
| 87 |
+
|
| 88 |
+
bbox = (
|
| 89 |
+
(dwx, dwy),
|
| 90 |
+
(x_disp, -y_disp - height, width + x_disp, -y_disp),
|
| 91 |
+
(0, 0, width, height),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
|
| 96 |
+
except ValueError:
|
| 97 |
+
# deal with zero-width characters
|
| 98 |
+
im = Image.new("1", (width, height))
|
| 99 |
+
|
| 100 |
+
return id, int(props["ENCODING"]), bbox, im
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class BdfFontFile(FontFile.FontFile):
|
| 104 |
+
"""Font file plugin for the X11 BDF format."""
|
| 105 |
+
|
| 106 |
+
def __init__(self, fp: BinaryIO) -> None:
|
| 107 |
+
super().__init__()
|
| 108 |
+
|
| 109 |
+
s = fp.readline()
|
| 110 |
+
if s[:13] != b"STARTFONT 2.1":
|
| 111 |
+
msg = "not a valid BDF file"
|
| 112 |
+
raise SyntaxError(msg)
|
| 113 |
+
|
| 114 |
+
props = {}
|
| 115 |
+
comments = []
|
| 116 |
+
|
| 117 |
+
while True:
|
| 118 |
+
s = fp.readline()
|
| 119 |
+
if not s or s[:13] == b"ENDPROPERTIES":
|
| 120 |
+
break
|
| 121 |
+
i = s.find(b" ")
|
| 122 |
+
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
|
| 123 |
+
if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
|
| 124 |
+
if s.find(b"LogicalFontDescription") < 0:
|
| 125 |
+
comments.append(s[i + 1 : -1].decode("ascii"))
|
| 126 |
+
|
| 127 |
+
while True:
|
| 128 |
+
c = bdf_char(fp)
|
| 129 |
+
if not c:
|
| 130 |
+
break
|
| 131 |
+
id, ch, (xy, dst, src), im = c
|
| 132 |
+
if 0 <= ch < len(self.glyph):
|
| 133 |
+
self.glyph[ch] = xy, dst, src, im
|
lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# BUFR stub adapter
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
| 8 |
+
#
|
| 9 |
+
# See the README file for information on usage and redistribution.
|
| 10 |
+
#
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import IO
|
| 14 |
+
|
| 15 |
+
from . import Image, ImageFile
|
| 16 |
+
|
| 17 |
+
_handler = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 21 |
+
"""
|
| 22 |
+
Install application-specific BUFR image handler.
|
| 23 |
+
|
| 24 |
+
:param handler: Handler object.
|
| 25 |
+
"""
|
| 26 |
+
global _handler
|
| 27 |
+
_handler = handler
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# --------------------------------------------------------------------
|
| 31 |
+
# Image adapter
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class BufrStubImageFile(ImageFile.StubImageFile):
|
| 39 |
+
format = "BUFR"
|
| 40 |
+
format_description = "BUFR"
|
| 41 |
+
|
| 42 |
+
def _open(self) -> None:
|
| 43 |
+
offset = self.fp.tell()
|
| 44 |
+
|
| 45 |
+
if not _accept(self.fp.read(4)):
|
| 46 |
+
msg = "Not a BUFR file"
|
| 47 |
+
raise SyntaxError(msg)
|
| 48 |
+
|
| 49 |
+
self.fp.seek(offset)
|
| 50 |
+
|
| 51 |
+
# make something up
|
| 52 |
+
self._mode = "F"
|
| 53 |
+
self._size = 1, 1
|
| 54 |
+
|
| 55 |
+
loader = self._load()
|
| 56 |
+
if loader:
|
| 57 |
+
loader.open(self)
|
| 58 |
+
|
| 59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 60 |
+
return _handler
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 65 |
+
msg = "BUFR save handler not installed"
|
| 66 |
+
raise OSError(msg)
|
| 67 |
+
_handler.save(im, fp, filename)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --------------------------------------------------------------------
|
| 71 |
+
# Registry
|
| 72 |
+
|
| 73 |
+
Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
|
| 74 |
+
Image.register_save(BufrStubImageFile.format, _save)
|
| 75 |
+
|
| 76 |
+
Image.register_extension(BufrStubImageFile.format, ".bufr")
|
lib/python3.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a class to read from a container file
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-06-18 fl Created
|
| 9 |
+
# 1995-09-07 fl Added readline(), readlines()
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
| 12 |
+
# Copyright (c) 1995 by Fredrik Lundh
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
from collections.abc import Iterable
|
| 20 |
+
from typing import IO, AnyStr, NoReturn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ContainerIO(IO[AnyStr]):
|
| 24 |
+
"""
|
| 25 |
+
A file object that provides read access to a part of an existing
|
| 26 |
+
file (for example a TAR file).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
|
| 30 |
+
"""
|
| 31 |
+
Create file object.
|
| 32 |
+
|
| 33 |
+
:param file: Existing file.
|
| 34 |
+
:param offset: Start of region, in bytes.
|
| 35 |
+
:param length: Size of region, in bytes.
|
| 36 |
+
"""
|
| 37 |
+
self.fh: IO[AnyStr] = file
|
| 38 |
+
self.pos = 0
|
| 39 |
+
self.offset = offset
|
| 40 |
+
self.length = length
|
| 41 |
+
self.fh.seek(offset)
|
| 42 |
+
|
| 43 |
+
##
|
| 44 |
+
# Always false.
|
| 45 |
+
|
| 46 |
+
def isatty(self) -> bool:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
def seekable(self) -> bool:
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
def seek(self, offset: int, mode: int = io.SEEK_SET) -> int:
|
| 53 |
+
"""
|
| 54 |
+
Move file pointer.
|
| 55 |
+
|
| 56 |
+
:param offset: Offset in bytes.
|
| 57 |
+
:param mode: Starting position. Use 0 for beginning of region, 1
|
| 58 |
+
for current offset, and 2 for end of region. You cannot move
|
| 59 |
+
the pointer outside the defined region.
|
| 60 |
+
:returns: Offset from start of region, in bytes.
|
| 61 |
+
"""
|
| 62 |
+
if mode == 1:
|
| 63 |
+
self.pos = self.pos + offset
|
| 64 |
+
elif mode == 2:
|
| 65 |
+
self.pos = self.length + offset
|
| 66 |
+
else:
|
| 67 |
+
self.pos = offset
|
| 68 |
+
# clamp
|
| 69 |
+
self.pos = max(0, min(self.pos, self.length))
|
| 70 |
+
self.fh.seek(self.offset + self.pos)
|
| 71 |
+
return self.pos
|
| 72 |
+
|
| 73 |
+
def tell(self) -> int:
|
| 74 |
+
"""
|
| 75 |
+
Get current file pointer.
|
| 76 |
+
|
| 77 |
+
:returns: Offset from start of region, in bytes.
|
| 78 |
+
"""
|
| 79 |
+
return self.pos
|
| 80 |
+
|
| 81 |
+
def readable(self) -> bool:
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def read(self, n: int = -1) -> AnyStr:
|
| 85 |
+
"""
|
| 86 |
+
Read data.
|
| 87 |
+
|
| 88 |
+
:param n: Number of bytes to read. If omitted, zero or negative,
|
| 89 |
+
read until end of region.
|
| 90 |
+
:returns: An 8-bit string.
|
| 91 |
+
"""
|
| 92 |
+
if n > 0:
|
| 93 |
+
n = min(n, self.length - self.pos)
|
| 94 |
+
else:
|
| 95 |
+
n = self.length - self.pos
|
| 96 |
+
if n <= 0: # EOF
|
| 97 |
+
return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
|
| 98 |
+
self.pos = self.pos + n
|
| 99 |
+
return self.fh.read(n)
|
| 100 |
+
|
| 101 |
+
def readline(self, n: int = -1) -> AnyStr:
|
| 102 |
+
"""
|
| 103 |
+
Read a line of text.
|
| 104 |
+
|
| 105 |
+
:param n: Number of bytes to read. If omitted, zero or negative,
|
| 106 |
+
read until end of line.
|
| 107 |
+
:returns: An 8-bit string.
|
| 108 |
+
"""
|
| 109 |
+
s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
|
| 110 |
+
newline_character = b"\n" if "b" in self.fh.mode else "\n"
|
| 111 |
+
while True:
|
| 112 |
+
c = self.read(1)
|
| 113 |
+
if not c:
|
| 114 |
+
break
|
| 115 |
+
s = s + c
|
| 116 |
+
if c == newline_character or len(s) == n:
|
| 117 |
+
break
|
| 118 |
+
return s
|
| 119 |
+
|
| 120 |
+
def readlines(self, n: int | None = -1) -> list[AnyStr]:
|
| 121 |
+
"""
|
| 122 |
+
Read multiple lines of text.
|
| 123 |
+
|
| 124 |
+
:param n: Number of lines to read. If omitted, zero, negative or None,
|
| 125 |
+
read until end of region.
|
| 126 |
+
:returns: A list of 8-bit strings.
|
| 127 |
+
"""
|
| 128 |
+
lines = []
|
| 129 |
+
while True:
|
| 130 |
+
s = self.readline()
|
| 131 |
+
if not s:
|
| 132 |
+
break
|
| 133 |
+
lines.append(s)
|
| 134 |
+
if len(lines) == n:
|
| 135 |
+
break
|
| 136 |
+
return lines
|
| 137 |
+
|
| 138 |
+
def writable(self) -> bool:
|
| 139 |
+
return False
|
| 140 |
+
|
| 141 |
+
def write(self, b: AnyStr) -> NoReturn:
|
| 142 |
+
raise NotImplementedError()
|
| 143 |
+
|
| 144 |
+
def writelines(self, lines: Iterable[AnyStr]) -> NoReturn:
|
| 145 |
+
raise NotImplementedError()
|
| 146 |
+
|
| 147 |
+
def truncate(self, size: int | None = None) -> int:
|
| 148 |
+
raise NotImplementedError()
|
| 149 |
+
|
| 150 |
+
def __enter__(self) -> ContainerIO[AnyStr]:
|
| 151 |
+
return self
|
| 152 |
+
|
| 153 |
+
def __exit__(self, *args: object) -> None:
|
| 154 |
+
self.close()
|
| 155 |
+
|
| 156 |
+
def __iter__(self) -> ContainerIO[AnyStr]:
|
| 157 |
+
return self
|
| 158 |
+
|
| 159 |
+
def __next__(self) -> AnyStr:
|
| 160 |
+
line = self.readline()
|
| 161 |
+
if not line:
|
| 162 |
+
msg = "end of region"
|
| 163 |
+
raise StopIteration(msg)
|
| 164 |
+
return line
|
| 165 |
+
|
| 166 |
+
def fileno(self) -> int:
|
| 167 |
+
return self.fh.fileno()
|
| 168 |
+
|
| 169 |
+
def flush(self) -> None:
|
| 170 |
+
self.fh.flush()
|
| 171 |
+
|
| 172 |
+
def close(self) -> None:
|
| 173 |
+
self.fh.close()
|
lib/python3.10/site-packages/PIL/DdsImagePlugin.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A Pillow loader for .dds files (S3TC-compressed aka DXTC)
|
| 3 |
+
Jerome Leclanche <jerome@leclan.ch>
|
| 4 |
+
|
| 5 |
+
Documentation:
|
| 6 |
+
https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
|
| 7 |
+
|
| 8 |
+
The contents of this file are hereby released in the public domain (CC0)
|
| 9 |
+
Full text of the CC0 license:
|
| 10 |
+
https://creativecommons.org/publicdomain/zero/1.0/
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import io
|
| 16 |
+
import struct
|
| 17 |
+
import sys
|
| 18 |
+
from enum import IntEnum, IntFlag
|
| 19 |
+
from typing import IO
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile, ImagePalette
|
| 22 |
+
from ._binary import i32le as i32
|
| 23 |
+
from ._binary import o8
|
| 24 |
+
from ._binary import o32le as o32
|
| 25 |
+
|
| 26 |
+
# Magic ("DDS ")
|
| 27 |
+
DDS_MAGIC = 0x20534444
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# DDS flags
|
| 31 |
+
class DDSD(IntFlag):
|
| 32 |
+
CAPS = 0x1
|
| 33 |
+
HEIGHT = 0x2
|
| 34 |
+
WIDTH = 0x4
|
| 35 |
+
PITCH = 0x8
|
| 36 |
+
PIXELFORMAT = 0x1000
|
| 37 |
+
MIPMAPCOUNT = 0x20000
|
| 38 |
+
LINEARSIZE = 0x80000
|
| 39 |
+
DEPTH = 0x800000
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# DDS caps
|
| 43 |
+
class DDSCAPS(IntFlag):
|
| 44 |
+
COMPLEX = 0x8
|
| 45 |
+
TEXTURE = 0x1000
|
| 46 |
+
MIPMAP = 0x400000
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class DDSCAPS2(IntFlag):
|
| 50 |
+
CUBEMAP = 0x200
|
| 51 |
+
CUBEMAP_POSITIVEX = 0x400
|
| 52 |
+
CUBEMAP_NEGATIVEX = 0x800
|
| 53 |
+
CUBEMAP_POSITIVEY = 0x1000
|
| 54 |
+
CUBEMAP_NEGATIVEY = 0x2000
|
| 55 |
+
CUBEMAP_POSITIVEZ = 0x4000
|
| 56 |
+
CUBEMAP_NEGATIVEZ = 0x8000
|
| 57 |
+
VOLUME = 0x200000
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Pixel Format
|
| 61 |
+
class DDPF(IntFlag):
|
| 62 |
+
ALPHAPIXELS = 0x1
|
| 63 |
+
ALPHA = 0x2
|
| 64 |
+
FOURCC = 0x4
|
| 65 |
+
PALETTEINDEXED8 = 0x20
|
| 66 |
+
RGB = 0x40
|
| 67 |
+
LUMINANCE = 0x20000
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# dxgiformat.h
|
| 71 |
+
class DXGI_FORMAT(IntEnum):
|
| 72 |
+
UNKNOWN = 0
|
| 73 |
+
R32G32B32A32_TYPELESS = 1
|
| 74 |
+
R32G32B32A32_FLOAT = 2
|
| 75 |
+
R32G32B32A32_UINT = 3
|
| 76 |
+
R32G32B32A32_SINT = 4
|
| 77 |
+
R32G32B32_TYPELESS = 5
|
| 78 |
+
R32G32B32_FLOAT = 6
|
| 79 |
+
R32G32B32_UINT = 7
|
| 80 |
+
R32G32B32_SINT = 8
|
| 81 |
+
R16G16B16A16_TYPELESS = 9
|
| 82 |
+
R16G16B16A16_FLOAT = 10
|
| 83 |
+
R16G16B16A16_UNORM = 11
|
| 84 |
+
R16G16B16A16_UINT = 12
|
| 85 |
+
R16G16B16A16_SNORM = 13
|
| 86 |
+
R16G16B16A16_SINT = 14
|
| 87 |
+
R32G32_TYPELESS = 15
|
| 88 |
+
R32G32_FLOAT = 16
|
| 89 |
+
R32G32_UINT = 17
|
| 90 |
+
R32G32_SINT = 18
|
| 91 |
+
R32G8X24_TYPELESS = 19
|
| 92 |
+
D32_FLOAT_S8X24_UINT = 20
|
| 93 |
+
R32_FLOAT_X8X24_TYPELESS = 21
|
| 94 |
+
X32_TYPELESS_G8X24_UINT = 22
|
| 95 |
+
R10G10B10A2_TYPELESS = 23
|
| 96 |
+
R10G10B10A2_UNORM = 24
|
| 97 |
+
R10G10B10A2_UINT = 25
|
| 98 |
+
R11G11B10_FLOAT = 26
|
| 99 |
+
R8G8B8A8_TYPELESS = 27
|
| 100 |
+
R8G8B8A8_UNORM = 28
|
| 101 |
+
R8G8B8A8_UNORM_SRGB = 29
|
| 102 |
+
R8G8B8A8_UINT = 30
|
| 103 |
+
R8G8B8A8_SNORM = 31
|
| 104 |
+
R8G8B8A8_SINT = 32
|
| 105 |
+
R16G16_TYPELESS = 33
|
| 106 |
+
R16G16_FLOAT = 34
|
| 107 |
+
R16G16_UNORM = 35
|
| 108 |
+
R16G16_UINT = 36
|
| 109 |
+
R16G16_SNORM = 37
|
| 110 |
+
R16G16_SINT = 38
|
| 111 |
+
R32_TYPELESS = 39
|
| 112 |
+
D32_FLOAT = 40
|
| 113 |
+
R32_FLOAT = 41
|
| 114 |
+
R32_UINT = 42
|
| 115 |
+
R32_SINT = 43
|
| 116 |
+
R24G8_TYPELESS = 44
|
| 117 |
+
D24_UNORM_S8_UINT = 45
|
| 118 |
+
R24_UNORM_X8_TYPELESS = 46
|
| 119 |
+
X24_TYPELESS_G8_UINT = 47
|
| 120 |
+
R8G8_TYPELESS = 48
|
| 121 |
+
R8G8_UNORM = 49
|
| 122 |
+
R8G8_UINT = 50
|
| 123 |
+
R8G8_SNORM = 51
|
| 124 |
+
R8G8_SINT = 52
|
| 125 |
+
R16_TYPELESS = 53
|
| 126 |
+
R16_FLOAT = 54
|
| 127 |
+
D16_UNORM = 55
|
| 128 |
+
R16_UNORM = 56
|
| 129 |
+
R16_UINT = 57
|
| 130 |
+
R16_SNORM = 58
|
| 131 |
+
R16_SINT = 59
|
| 132 |
+
R8_TYPELESS = 60
|
| 133 |
+
R8_UNORM = 61
|
| 134 |
+
R8_UINT = 62
|
| 135 |
+
R8_SNORM = 63
|
| 136 |
+
R8_SINT = 64
|
| 137 |
+
A8_UNORM = 65
|
| 138 |
+
R1_UNORM = 66
|
| 139 |
+
R9G9B9E5_SHAREDEXP = 67
|
| 140 |
+
R8G8_B8G8_UNORM = 68
|
| 141 |
+
G8R8_G8B8_UNORM = 69
|
| 142 |
+
BC1_TYPELESS = 70
|
| 143 |
+
BC1_UNORM = 71
|
| 144 |
+
BC1_UNORM_SRGB = 72
|
| 145 |
+
BC2_TYPELESS = 73
|
| 146 |
+
BC2_UNORM = 74
|
| 147 |
+
BC2_UNORM_SRGB = 75
|
| 148 |
+
BC3_TYPELESS = 76
|
| 149 |
+
BC3_UNORM = 77
|
| 150 |
+
BC3_UNORM_SRGB = 78
|
| 151 |
+
BC4_TYPELESS = 79
|
| 152 |
+
BC4_UNORM = 80
|
| 153 |
+
BC4_SNORM = 81
|
| 154 |
+
BC5_TYPELESS = 82
|
| 155 |
+
BC5_UNORM = 83
|
| 156 |
+
BC5_SNORM = 84
|
| 157 |
+
B5G6R5_UNORM = 85
|
| 158 |
+
B5G5R5A1_UNORM = 86
|
| 159 |
+
B8G8R8A8_UNORM = 87
|
| 160 |
+
B8G8R8X8_UNORM = 88
|
| 161 |
+
R10G10B10_XR_BIAS_A2_UNORM = 89
|
| 162 |
+
B8G8R8A8_TYPELESS = 90
|
| 163 |
+
B8G8R8A8_UNORM_SRGB = 91
|
| 164 |
+
B8G8R8X8_TYPELESS = 92
|
| 165 |
+
B8G8R8X8_UNORM_SRGB = 93
|
| 166 |
+
BC6H_TYPELESS = 94
|
| 167 |
+
BC6H_UF16 = 95
|
| 168 |
+
BC6H_SF16 = 96
|
| 169 |
+
BC7_TYPELESS = 97
|
| 170 |
+
BC7_UNORM = 98
|
| 171 |
+
BC7_UNORM_SRGB = 99
|
| 172 |
+
AYUV = 100
|
| 173 |
+
Y410 = 101
|
| 174 |
+
Y416 = 102
|
| 175 |
+
NV12 = 103
|
| 176 |
+
P010 = 104
|
| 177 |
+
P016 = 105
|
| 178 |
+
OPAQUE_420 = 106
|
| 179 |
+
YUY2 = 107
|
| 180 |
+
Y210 = 108
|
| 181 |
+
Y216 = 109
|
| 182 |
+
NV11 = 110
|
| 183 |
+
AI44 = 111
|
| 184 |
+
IA44 = 112
|
| 185 |
+
P8 = 113
|
| 186 |
+
A8P8 = 114
|
| 187 |
+
B4G4R4A4_UNORM = 115
|
| 188 |
+
P208 = 130
|
| 189 |
+
V208 = 131
|
| 190 |
+
V408 = 132
|
| 191 |
+
SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189
|
| 192 |
+
SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class D3DFMT(IntEnum):
|
| 196 |
+
UNKNOWN = 0
|
| 197 |
+
R8G8B8 = 20
|
| 198 |
+
A8R8G8B8 = 21
|
| 199 |
+
X8R8G8B8 = 22
|
| 200 |
+
R5G6B5 = 23
|
| 201 |
+
X1R5G5B5 = 24
|
| 202 |
+
A1R5G5B5 = 25
|
| 203 |
+
A4R4G4B4 = 26
|
| 204 |
+
R3G3B2 = 27
|
| 205 |
+
A8 = 28
|
| 206 |
+
A8R3G3B2 = 29
|
| 207 |
+
X4R4G4B4 = 30
|
| 208 |
+
A2B10G10R10 = 31
|
| 209 |
+
A8B8G8R8 = 32
|
| 210 |
+
X8B8G8R8 = 33
|
| 211 |
+
G16R16 = 34
|
| 212 |
+
A2R10G10B10 = 35
|
| 213 |
+
A16B16G16R16 = 36
|
| 214 |
+
A8P8 = 40
|
| 215 |
+
P8 = 41
|
| 216 |
+
L8 = 50
|
| 217 |
+
A8L8 = 51
|
| 218 |
+
A4L4 = 52
|
| 219 |
+
V8U8 = 60
|
| 220 |
+
L6V5U5 = 61
|
| 221 |
+
X8L8V8U8 = 62
|
| 222 |
+
Q8W8V8U8 = 63
|
| 223 |
+
V16U16 = 64
|
| 224 |
+
A2W10V10U10 = 67
|
| 225 |
+
D16_LOCKABLE = 70
|
| 226 |
+
D32 = 71
|
| 227 |
+
D15S1 = 73
|
| 228 |
+
D24S8 = 75
|
| 229 |
+
D24X8 = 77
|
| 230 |
+
D24X4S4 = 79
|
| 231 |
+
D16 = 80
|
| 232 |
+
D32F_LOCKABLE = 82
|
| 233 |
+
D24FS8 = 83
|
| 234 |
+
D32_LOCKABLE = 84
|
| 235 |
+
S8_LOCKABLE = 85
|
| 236 |
+
L16 = 81
|
| 237 |
+
VERTEXDATA = 100
|
| 238 |
+
INDEX16 = 101
|
| 239 |
+
INDEX32 = 102
|
| 240 |
+
Q16W16V16U16 = 110
|
| 241 |
+
R16F = 111
|
| 242 |
+
G16R16F = 112
|
| 243 |
+
A16B16G16R16F = 113
|
| 244 |
+
R32F = 114
|
| 245 |
+
G32R32F = 115
|
| 246 |
+
A32B32G32R32F = 116
|
| 247 |
+
CxV8U8 = 117
|
| 248 |
+
A1 = 118
|
| 249 |
+
A2B10G10R10_XR_BIAS = 119
|
| 250 |
+
BINARYBUFFER = 199
|
| 251 |
+
|
| 252 |
+
UYVY = i32(b"UYVY")
|
| 253 |
+
R8G8_B8G8 = i32(b"RGBG")
|
| 254 |
+
YUY2 = i32(b"YUY2")
|
| 255 |
+
G8R8_G8B8 = i32(b"GRGB")
|
| 256 |
+
DXT1 = i32(b"DXT1")
|
| 257 |
+
DXT2 = i32(b"DXT2")
|
| 258 |
+
DXT3 = i32(b"DXT3")
|
| 259 |
+
DXT4 = i32(b"DXT4")
|
| 260 |
+
DXT5 = i32(b"DXT5")
|
| 261 |
+
DX10 = i32(b"DX10")
|
| 262 |
+
BC4S = i32(b"BC4S")
|
| 263 |
+
BC4U = i32(b"BC4U")
|
| 264 |
+
BC5S = i32(b"BC5S")
|
| 265 |
+
BC5U = i32(b"BC5U")
|
| 266 |
+
ATI1 = i32(b"ATI1")
|
| 267 |
+
ATI2 = i32(b"ATI2")
|
| 268 |
+
MULTI2_ARGB8 = i32(b"MET1")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# Backward compatibility layer
|
| 272 |
+
module = sys.modules[__name__]
|
| 273 |
+
for item in DDSD:
|
| 274 |
+
assert item.name is not None
|
| 275 |
+
setattr(module, f"DDSD_{item.name}", item.value)
|
| 276 |
+
for item1 in DDSCAPS:
|
| 277 |
+
assert item1.name is not None
|
| 278 |
+
setattr(module, f"DDSCAPS_{item1.name}", item1.value)
|
| 279 |
+
for item2 in DDSCAPS2:
|
| 280 |
+
assert item2.name is not None
|
| 281 |
+
setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
|
| 282 |
+
for item3 in DDPF:
|
| 283 |
+
assert item3.name is not None
|
| 284 |
+
setattr(module, f"DDPF_{item3.name}", item3.value)
|
| 285 |
+
|
| 286 |
+
DDS_FOURCC = DDPF.FOURCC
|
| 287 |
+
DDS_RGB = DDPF.RGB
|
| 288 |
+
DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
|
| 289 |
+
DDS_LUMINANCE = DDPF.LUMINANCE
|
| 290 |
+
DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
|
| 291 |
+
DDS_ALPHA = DDPF.ALPHA
|
| 292 |
+
DDS_PAL8 = DDPF.PALETTEINDEXED8
|
| 293 |
+
|
| 294 |
+
DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
|
| 295 |
+
DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
|
| 296 |
+
DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
|
| 297 |
+
DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
|
| 298 |
+
DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
|
| 299 |
+
|
| 300 |
+
DDS_HEIGHT = DDSD.HEIGHT
|
| 301 |
+
DDS_WIDTH = DDSD.WIDTH
|
| 302 |
+
|
| 303 |
+
DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
|
| 304 |
+
DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
|
| 305 |
+
DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
|
| 306 |
+
|
| 307 |
+
DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
|
| 308 |
+
DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
|
| 309 |
+
DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
|
| 310 |
+
DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
|
| 311 |
+
DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
|
| 312 |
+
DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
|
| 313 |
+
|
| 314 |
+
DXT1_FOURCC = D3DFMT.DXT1
|
| 315 |
+
DXT3_FOURCC = D3DFMT.DXT3
|
| 316 |
+
DXT5_FOURCC = D3DFMT.DXT5
|
| 317 |
+
|
| 318 |
+
DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
|
| 319 |
+
DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
|
| 320 |
+
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
|
| 321 |
+
DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
|
| 322 |
+
DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
|
| 323 |
+
DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
|
| 324 |
+
DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
|
| 325 |
+
DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
|
| 326 |
+
DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
|
| 327 |
+
DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
|
| 328 |
+
DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class DdsImageFile(ImageFile.ImageFile):
|
| 332 |
+
format = "DDS"
|
| 333 |
+
format_description = "DirectDraw Surface"
|
| 334 |
+
|
| 335 |
+
def _open(self) -> None:
|
| 336 |
+
if not _accept(self.fp.read(4)):
|
| 337 |
+
msg = "not a DDS file"
|
| 338 |
+
raise SyntaxError(msg)
|
| 339 |
+
(header_size,) = struct.unpack("<I", self.fp.read(4))
|
| 340 |
+
if header_size != 124:
|
| 341 |
+
msg = f"Unsupported header size {repr(header_size)}"
|
| 342 |
+
raise OSError(msg)
|
| 343 |
+
header_bytes = self.fp.read(header_size - 4)
|
| 344 |
+
if len(header_bytes) != 120:
|
| 345 |
+
msg = f"Incomplete header: {len(header_bytes)} bytes"
|
| 346 |
+
raise OSError(msg)
|
| 347 |
+
header = io.BytesIO(header_bytes)
|
| 348 |
+
|
| 349 |
+
flags, height, width = struct.unpack("<3I", header.read(12))
|
| 350 |
+
self._size = (width, height)
|
| 351 |
+
extents = (0, 0) + self.size
|
| 352 |
+
|
| 353 |
+
pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
|
| 354 |
+
struct.unpack("<11I", header.read(44)) # reserved
|
| 355 |
+
|
| 356 |
+
# pixel format
|
| 357 |
+
pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header.read(16))
|
| 358 |
+
n = 0
|
| 359 |
+
rawmode = None
|
| 360 |
+
if pfflags & DDPF.RGB:
|
| 361 |
+
# Texture contains uncompressed RGB data
|
| 362 |
+
if pfflags & DDPF.ALPHAPIXELS:
|
| 363 |
+
self._mode = "RGBA"
|
| 364 |
+
mask_count = 4
|
| 365 |
+
else:
|
| 366 |
+
self._mode = "RGB"
|
| 367 |
+
mask_count = 3
|
| 368 |
+
|
| 369 |
+
masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4))
|
| 370 |
+
self.tile = [ImageFile._Tile("dds_rgb", extents, 0, (bitcount, masks))]
|
| 371 |
+
return
|
| 372 |
+
elif pfflags & DDPF.LUMINANCE:
|
| 373 |
+
if bitcount == 8:
|
| 374 |
+
self._mode = "L"
|
| 375 |
+
elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
|
| 376 |
+
self._mode = "LA"
|
| 377 |
+
else:
|
| 378 |
+
msg = f"Unsupported bitcount {bitcount} for {pfflags}"
|
| 379 |
+
raise OSError(msg)
|
| 380 |
+
elif pfflags & DDPF.PALETTEINDEXED8:
|
| 381 |
+
self._mode = "P"
|
| 382 |
+
self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
|
| 383 |
+
self.palette.mode = "RGBA"
|
| 384 |
+
elif pfflags & DDPF.FOURCC:
|
| 385 |
+
offset = header_size + 4
|
| 386 |
+
if fourcc == D3DFMT.DXT1:
|
| 387 |
+
self._mode = "RGBA"
|
| 388 |
+
self.pixel_format = "DXT1"
|
| 389 |
+
n = 1
|
| 390 |
+
elif fourcc == D3DFMT.DXT3:
|
| 391 |
+
self._mode = "RGBA"
|
| 392 |
+
self.pixel_format = "DXT3"
|
| 393 |
+
n = 2
|
| 394 |
+
elif fourcc == D3DFMT.DXT5:
|
| 395 |
+
self._mode = "RGBA"
|
| 396 |
+
self.pixel_format = "DXT5"
|
| 397 |
+
n = 3
|
| 398 |
+
elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
|
| 399 |
+
self._mode = "L"
|
| 400 |
+
self.pixel_format = "BC4"
|
| 401 |
+
n = 4
|
| 402 |
+
elif fourcc == D3DFMT.BC5S:
|
| 403 |
+
self._mode = "RGB"
|
| 404 |
+
self.pixel_format = "BC5S"
|
| 405 |
+
n = 5
|
| 406 |
+
elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
|
| 407 |
+
self._mode = "RGB"
|
| 408 |
+
self.pixel_format = "BC5"
|
| 409 |
+
n = 5
|
| 410 |
+
elif fourcc == D3DFMT.DX10:
|
| 411 |
+
offset += 20
|
| 412 |
+
# ignoring flags which pertain to volume textures and cubemaps
|
| 413 |
+
(dxgi_format,) = struct.unpack("<I", self.fp.read(4))
|
| 414 |
+
self.fp.read(16)
|
| 415 |
+
if dxgi_format in (
|
| 416 |
+
DXGI_FORMAT.BC1_UNORM,
|
| 417 |
+
DXGI_FORMAT.BC1_TYPELESS,
|
| 418 |
+
):
|
| 419 |
+
self._mode = "RGBA"
|
| 420 |
+
self.pixel_format = "BC1"
|
| 421 |
+
n = 1
|
| 422 |
+
elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
|
| 423 |
+
self._mode = "L"
|
| 424 |
+
self.pixel_format = "BC4"
|
| 425 |
+
n = 4
|
| 426 |
+
elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
|
| 427 |
+
self._mode = "RGB"
|
| 428 |
+
self.pixel_format = "BC5"
|
| 429 |
+
n = 5
|
| 430 |
+
elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
|
| 431 |
+
self._mode = "RGB"
|
| 432 |
+
self.pixel_format = "BC5S"
|
| 433 |
+
n = 5
|
| 434 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
|
| 435 |
+
self._mode = "RGB"
|
| 436 |
+
self.pixel_format = "BC6H"
|
| 437 |
+
n = 6
|
| 438 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
|
| 439 |
+
self._mode = "RGB"
|
| 440 |
+
self.pixel_format = "BC6HS"
|
| 441 |
+
n = 6
|
| 442 |
+
elif dxgi_format in (
|
| 443 |
+
DXGI_FORMAT.BC7_TYPELESS,
|
| 444 |
+
DXGI_FORMAT.BC7_UNORM,
|
| 445 |
+
DXGI_FORMAT.BC7_UNORM_SRGB,
|
| 446 |
+
):
|
| 447 |
+
self._mode = "RGBA"
|
| 448 |
+
self.pixel_format = "BC7"
|
| 449 |
+
n = 7
|
| 450 |
+
if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
|
| 451 |
+
self.info["gamma"] = 1 / 2.2
|
| 452 |
+
elif dxgi_format in (
|
| 453 |
+
DXGI_FORMAT.R8G8B8A8_TYPELESS,
|
| 454 |
+
DXGI_FORMAT.R8G8B8A8_UNORM,
|
| 455 |
+
DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
|
| 456 |
+
):
|
| 457 |
+
self._mode = "RGBA"
|
| 458 |
+
if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
|
| 459 |
+
self.info["gamma"] = 1 / 2.2
|
| 460 |
+
else:
|
| 461 |
+
msg = f"Unimplemented DXGI format {dxgi_format}"
|
| 462 |
+
raise NotImplementedError(msg)
|
| 463 |
+
else:
|
| 464 |
+
msg = f"Unimplemented pixel format {repr(fourcc)}"
|
| 465 |
+
raise NotImplementedError(msg)
|
| 466 |
+
else:
|
| 467 |
+
msg = f"Unknown pixel format flags {pfflags}"
|
| 468 |
+
raise NotImplementedError(msg)
|
| 469 |
+
|
| 470 |
+
if n:
|
| 471 |
+
self.tile = [
|
| 472 |
+
ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
|
| 473 |
+
]
|
| 474 |
+
else:
|
| 475 |
+
self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
|
| 476 |
+
|
| 477 |
+
def load_seek(self, pos: int) -> None:
|
| 478 |
+
pass
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class DdsRgbDecoder(ImageFile.PyDecoder):
|
| 482 |
+
_pulls_fd = True
|
| 483 |
+
|
| 484 |
+
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
|
| 485 |
+
assert self.fd is not None
|
| 486 |
+
bitcount, masks = self.args
|
| 487 |
+
|
| 488 |
+
# Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
|
| 489 |
+
# Calculate how many zeros each mask is padded with
|
| 490 |
+
mask_offsets = []
|
| 491 |
+
# And the maximum value of each channel without the padding
|
| 492 |
+
mask_totals = []
|
| 493 |
+
for mask in masks:
|
| 494 |
+
offset = 0
|
| 495 |
+
if mask != 0:
|
| 496 |
+
while mask >> (offset + 1) << (offset + 1) == mask:
|
| 497 |
+
offset += 1
|
| 498 |
+
mask_offsets.append(offset)
|
| 499 |
+
mask_totals.append(mask >> offset)
|
| 500 |
+
|
| 501 |
+
data = bytearray()
|
| 502 |
+
bytecount = bitcount // 8
|
| 503 |
+
dest_length = self.state.xsize * self.state.ysize * len(masks)
|
| 504 |
+
while len(data) < dest_length:
|
| 505 |
+
value = int.from_bytes(self.fd.read(bytecount), "little")
|
| 506 |
+
for i, mask in enumerate(masks):
|
| 507 |
+
masked_value = value & mask
|
| 508 |
+
# Remove the zero padding, and scale it to 8 bits
|
| 509 |
+
data += o8(
|
| 510 |
+
int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
|
| 511 |
+
)
|
| 512 |
+
self.set_as_raw(data)
|
| 513 |
+
return -1, 0
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 517 |
+
if im.mode not in ("RGB", "RGBA", "L", "LA"):
|
| 518 |
+
msg = f"cannot write mode {im.mode} as DDS"
|
| 519 |
+
raise OSError(msg)
|
| 520 |
+
|
| 521 |
+
alpha = im.mode[-1] == "A"
|
| 522 |
+
if im.mode[0] == "L":
|
| 523 |
+
pixel_flags = DDPF.LUMINANCE
|
| 524 |
+
rawmode = im.mode
|
| 525 |
+
if alpha:
|
| 526 |
+
rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
|
| 527 |
+
else:
|
| 528 |
+
rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
|
| 529 |
+
else:
|
| 530 |
+
pixel_flags = DDPF.RGB
|
| 531 |
+
rawmode = im.mode[::-1]
|
| 532 |
+
rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
|
| 533 |
+
|
| 534 |
+
if alpha:
|
| 535 |
+
r, g, b, a = im.split()
|
| 536 |
+
im = Image.merge("RGBA", (a, r, g, b))
|
| 537 |
+
if alpha:
|
| 538 |
+
pixel_flags |= DDPF.ALPHAPIXELS
|
| 539 |
+
rgba_mask.append(0xFF000000 if alpha else 0)
|
| 540 |
+
|
| 541 |
+
flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PITCH | DDSD.PIXELFORMAT
|
| 542 |
+
bitcount = len(im.getbands()) * 8
|
| 543 |
+
pitch = (im.width * bitcount + 7) // 8
|
| 544 |
+
|
| 545 |
+
fp.write(
|
| 546 |
+
o32(DDS_MAGIC)
|
| 547 |
+
+ struct.pack(
|
| 548 |
+
"<7I",
|
| 549 |
+
124, # header size
|
| 550 |
+
flags, # flags
|
| 551 |
+
im.height,
|
| 552 |
+
im.width,
|
| 553 |
+
pitch,
|
| 554 |
+
0, # depth
|
| 555 |
+
0, # mipmaps
|
| 556 |
+
)
|
| 557 |
+
+ struct.pack("11I", *((0,) * 11)) # reserved
|
| 558 |
+
# pfsize, pfflags, fourcc, bitcount
|
| 559 |
+
+ struct.pack("<4I", 32, pixel_flags, 0, bitcount)
|
| 560 |
+
+ struct.pack("<4I", *rgba_mask) # dwRGBABitMask
|
| 561 |
+
+ struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
|
| 562 |
+
)
|
| 563 |
+
ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)])
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _accept(prefix: bytes) -> bool:
|
| 567 |
+
return prefix[:4] == b"DDS "
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
|
| 571 |
+
Image.register_decoder("dds_rgb", DdsRgbDecoder)
|
| 572 |
+
Image.register_save(DdsImageFile.format, _save)
|
| 573 |
+
Image.register_extension(DdsImageFile.format, ".dds")
|
lib/python3.10/site-packages/PIL/FtexImagePlugin.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A Pillow loader for .ftc and .ftu files (FTEX)
|
| 3 |
+
Jerome Leclanche <jerome@leclan.ch>
|
| 4 |
+
|
| 5 |
+
The contents of this file are hereby released in the public domain (CC0)
|
| 6 |
+
Full text of the CC0 license:
|
| 7 |
+
https://creativecommons.org/publicdomain/zero/1.0/
|
| 8 |
+
|
| 9 |
+
Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
|
| 10 |
+
|
| 11 |
+
The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
|
| 12 |
+
packed custom format called FTEX. This file format uses file extensions FTC
|
| 13 |
+
and FTU.
|
| 14 |
+
* FTC files are compressed textures (using standard texture compression).
|
| 15 |
+
* FTU files are not compressed.
|
| 16 |
+
Texture File Format
|
| 17 |
+
The FTC and FTU texture files both use the same format. This
|
| 18 |
+
has the following structure:
|
| 19 |
+
{header}
|
| 20 |
+
{format_directory}
|
| 21 |
+
{data}
|
| 22 |
+
Where:
|
| 23 |
+
{header} = {
|
| 24 |
+
u32:magic,
|
| 25 |
+
u32:version,
|
| 26 |
+
u32:width,
|
| 27 |
+
u32:height,
|
| 28 |
+
u32:mipmap_count,
|
| 29 |
+
u32:format_count
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
* The "magic" number is "FTEX".
|
| 33 |
+
* "width" and "height" are the dimensions of the texture.
|
| 34 |
+
* "mipmap_count" is the number of mipmaps in the texture.
|
| 35 |
+
* "format_count" is the number of texture formats (different versions of the
|
| 36 |
+
same texture) in this file.
|
| 37 |
+
|
| 38 |
+
{format_directory} = format_count * { u32:format, u32:where }
|
| 39 |
+
|
| 40 |
+
The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
|
| 41 |
+
uncompressed textures.
|
| 42 |
+
The texture data for a format starts at the position "where" in the file.
|
| 43 |
+
|
| 44 |
+
Each set of texture data in the file has the following structure:
|
| 45 |
+
{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
|
| 46 |
+
* "mipmap_size" is the number of bytes in that mip level. For compressed
|
| 47 |
+
textures this is the size of the texture data compressed with DXT1. For 24 bit
|
| 48 |
+
uncompressed textures, this is 3 * width * height. Following this are the image
|
| 49 |
+
bytes for that mipmap level.
|
| 50 |
+
|
| 51 |
+
Note: All data is stored in little-Endian (Intel) byte order.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
from __future__ import annotations
|
| 55 |
+
|
| 56 |
+
import struct
|
| 57 |
+
from enum import IntEnum
|
| 58 |
+
from io import BytesIO
|
| 59 |
+
|
| 60 |
+
from . import Image, ImageFile
|
| 61 |
+
|
| 62 |
+
MAGIC = b"FTEX"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Format(IntEnum):
|
| 66 |
+
DXT1 = 0
|
| 67 |
+
UNCOMPRESSED = 1
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class FtexImageFile(ImageFile.ImageFile):
|
| 71 |
+
format = "FTEX"
|
| 72 |
+
format_description = "Texture File Format (IW2:EOC)"
|
| 73 |
+
|
| 74 |
+
def _open(self) -> None:
|
| 75 |
+
if not _accept(self.fp.read(4)):
|
| 76 |
+
msg = "not an FTEX file"
|
| 77 |
+
raise SyntaxError(msg)
|
| 78 |
+
struct.unpack("<i", self.fp.read(4)) # version
|
| 79 |
+
self._size = struct.unpack("<2i", self.fp.read(8))
|
| 80 |
+
mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
|
| 81 |
+
|
| 82 |
+
self._mode = "RGB"
|
| 83 |
+
|
| 84 |
+
# Only support single-format files.
|
| 85 |
+
# I don't know of any multi-format file.
|
| 86 |
+
assert format_count == 1
|
| 87 |
+
|
| 88 |
+
format, where = struct.unpack("<2i", self.fp.read(8))
|
| 89 |
+
self.fp.seek(where)
|
| 90 |
+
(mipmap_size,) = struct.unpack("<i", self.fp.read(4))
|
| 91 |
+
|
| 92 |
+
data = self.fp.read(mipmap_size)
|
| 93 |
+
|
| 94 |
+
if format == Format.DXT1:
|
| 95 |
+
self._mode = "RGBA"
|
| 96 |
+
self.tile = [ImageFile._Tile("bcn", (0, 0) + self.size, 0, (1,))]
|
| 97 |
+
elif format == Format.UNCOMPRESSED:
|
| 98 |
+
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, "RGB")]
|
| 99 |
+
else:
|
| 100 |
+
msg = f"Invalid texture compression format: {repr(format)}"
|
| 101 |
+
raise ValueError(msg)
|
| 102 |
+
|
| 103 |
+
self.fp.close()
|
| 104 |
+
self.fp = BytesIO(data)
|
| 105 |
+
|
| 106 |
+
def load_seek(self, pos: int) -> None:
|
| 107 |
+
pass
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _accept(prefix: bytes) -> bool:
|
| 111 |
+
return prefix[:4] == MAGIC
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
Image.register_open(FtexImageFile.format, FtexImageFile, _accept)
|
| 115 |
+
Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
|
lib/python3.10/site-packages/PIL/GdImageFile.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# GD file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-12 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 11 |
+
# Copyright (c) 1996 by Fredrik Lundh.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
.. note::
|
| 19 |
+
This format cannot be automatically recognized, so the
|
| 20 |
+
class is not registered for use with :py:func:`PIL.Image.open()`. To open a
|
| 21 |
+
gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
|
| 22 |
+
|
| 23 |
+
.. warning::
|
| 24 |
+
THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
|
| 25 |
+
implementation is provided for convenience and demonstrational
|
| 26 |
+
purposes only.
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
from typing import IO
|
| 31 |
+
|
| 32 |
+
from . import ImageFile, ImagePalette, UnidentifiedImageError
|
| 33 |
+
from ._binary import i16be as i16
|
| 34 |
+
from ._binary import i32be as i32
|
| 35 |
+
from ._typing import StrOrBytesPath
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GdImageFile(ImageFile.ImageFile):
|
| 39 |
+
"""
|
| 40 |
+
Image plugin for the GD uncompressed format. Note that this format
|
| 41 |
+
is not supported by the standard :py:func:`PIL.Image.open()` function. To use
|
| 42 |
+
this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
|
| 43 |
+
use the :py:func:`PIL.GdImageFile.open()` function.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
format = "GD"
|
| 47 |
+
format_description = "GD uncompressed images"
|
| 48 |
+
|
| 49 |
+
def _open(self) -> None:
|
| 50 |
+
# Header
|
| 51 |
+
assert self.fp is not None
|
| 52 |
+
|
| 53 |
+
s = self.fp.read(1037)
|
| 54 |
+
|
| 55 |
+
if i16(s) not in [65534, 65535]:
|
| 56 |
+
msg = "Not a valid GD 2.x .gd file"
|
| 57 |
+
raise SyntaxError(msg)
|
| 58 |
+
|
| 59 |
+
self._mode = "L" # FIXME: "P"
|
| 60 |
+
self._size = i16(s, 2), i16(s, 4)
|
| 61 |
+
|
| 62 |
+
true_color = s[6]
|
| 63 |
+
true_color_offset = 2 if true_color else 0
|
| 64 |
+
|
| 65 |
+
# transparency index
|
| 66 |
+
tindex = i32(s, 7 + true_color_offset)
|
| 67 |
+
if tindex < 256:
|
| 68 |
+
self.info["transparency"] = tindex
|
| 69 |
+
|
| 70 |
+
self.palette = ImagePalette.raw(
|
| 71 |
+
"XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
self.tile = [
|
| 75 |
+
ImageFile._Tile(
|
| 76 |
+
"raw",
|
| 77 |
+
(0, 0) + self.size,
|
| 78 |
+
7 + true_color_offset + 4 + 256 * 4,
|
| 79 |
+
"L",
|
| 80 |
+
)
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
|
| 85 |
+
"""
|
| 86 |
+
Load texture from a GD image file.
|
| 87 |
+
|
| 88 |
+
:param fp: GD file name, or an opened file handle.
|
| 89 |
+
:param mode: Optional mode. In this version, if the mode argument
|
| 90 |
+
is given, it must be "r".
|
| 91 |
+
:returns: An image instance.
|
| 92 |
+
:raises OSError: If the image could not be read.
|
| 93 |
+
"""
|
| 94 |
+
if mode != "r":
|
| 95 |
+
msg = "bad mode"
|
| 96 |
+
raise ValueError(msg)
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
return GdImageFile(fp)
|
| 100 |
+
except SyntaxError as e:
|
| 101 |
+
msg = "cannot identify this image file"
|
| 102 |
+
raise UnidentifiedImageError(msg) from e
|
lib/python3.10/site-packages/PIL/GimpGradientFile.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# stuff to read (and render) GIMP gradient files
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 97-08-23 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
Stuff to translate curve segments to palette values (derived from
|
| 18 |
+
the corresponding code in GIMP, written by Federico Mena Quintero.
|
| 19 |
+
See the GIMP distribution for more information.)
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from math import log, pi, sin, sqrt
|
| 24 |
+
from typing import IO, Callable
|
| 25 |
+
|
| 26 |
+
from ._binary import o8
|
| 27 |
+
|
| 28 |
+
EPSILON = 1e-10
|
| 29 |
+
"""""" # Enable auto-doc for data member
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def linear(middle: float, pos: float) -> float:
|
| 33 |
+
if pos <= middle:
|
| 34 |
+
if middle < EPSILON:
|
| 35 |
+
return 0.0
|
| 36 |
+
else:
|
| 37 |
+
return 0.5 * pos / middle
|
| 38 |
+
else:
|
| 39 |
+
pos = pos - middle
|
| 40 |
+
middle = 1.0 - middle
|
| 41 |
+
if middle < EPSILON:
|
| 42 |
+
return 1.0
|
| 43 |
+
else:
|
| 44 |
+
return 0.5 + 0.5 * pos / middle
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def curved(middle: float, pos: float) -> float:
|
| 48 |
+
return pos ** (log(0.5) / log(max(middle, EPSILON)))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def sine(middle: float, pos: float) -> float:
|
| 52 |
+
return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def sphere_increasing(middle: float, pos: float) -> float:
|
| 56 |
+
return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def sphere_decreasing(middle: float, pos: float) -> float:
|
| 60 |
+
return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
|
| 64 |
+
"""""" # Enable auto-doc for data member
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class GradientFile:
|
| 68 |
+
gradient: (
|
| 69 |
+
list[
|
| 70 |
+
tuple[
|
| 71 |
+
float,
|
| 72 |
+
float,
|
| 73 |
+
float,
|
| 74 |
+
list[float],
|
| 75 |
+
list[float],
|
| 76 |
+
Callable[[float, float], float],
|
| 77 |
+
]
|
| 78 |
+
]
|
| 79 |
+
| None
|
| 80 |
+
) = None
|
| 81 |
+
|
| 82 |
+
def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
|
| 83 |
+
assert self.gradient is not None
|
| 84 |
+
palette = []
|
| 85 |
+
|
| 86 |
+
ix = 0
|
| 87 |
+
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
| 88 |
+
|
| 89 |
+
for i in range(entries):
|
| 90 |
+
x = i / (entries - 1)
|
| 91 |
+
|
| 92 |
+
while x1 < x:
|
| 93 |
+
ix += 1
|
| 94 |
+
x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
|
| 95 |
+
|
| 96 |
+
w = x1 - x0
|
| 97 |
+
|
| 98 |
+
if w < EPSILON:
|
| 99 |
+
scale = segment(0.5, 0.5)
|
| 100 |
+
else:
|
| 101 |
+
scale = segment((xm - x0) / w, (x - x0) / w)
|
| 102 |
+
|
| 103 |
+
# expand to RGBA
|
| 104 |
+
r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
|
| 105 |
+
g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
|
| 106 |
+
b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
|
| 107 |
+
a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
|
| 108 |
+
|
| 109 |
+
# add to palette
|
| 110 |
+
palette.append(r + g + b + a)
|
| 111 |
+
|
| 112 |
+
return b"".join(palette), "RGBA"
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class GimpGradientFile(GradientFile):
|
| 116 |
+
"""File handler for GIMP's gradient format."""
|
| 117 |
+
|
| 118 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 119 |
+
if fp.readline()[:13] != b"GIMP Gradient":
|
| 120 |
+
msg = "not a GIMP gradient file"
|
| 121 |
+
raise SyntaxError(msg)
|
| 122 |
+
|
| 123 |
+
line = fp.readline()
|
| 124 |
+
|
| 125 |
+
# GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
|
| 126 |
+
if line.startswith(b"Name: "):
|
| 127 |
+
line = fp.readline().strip()
|
| 128 |
+
|
| 129 |
+
count = int(line)
|
| 130 |
+
|
| 131 |
+
self.gradient = []
|
| 132 |
+
|
| 133 |
+
for i in range(count):
|
| 134 |
+
s = fp.readline().split()
|
| 135 |
+
w = [float(x) for x in s[:11]]
|
| 136 |
+
|
| 137 |
+
x0, x1 = w[0], w[2]
|
| 138 |
+
xm = w[1]
|
| 139 |
+
rgb0 = w[3:7]
|
| 140 |
+
rgb1 = w[7:11]
|
| 141 |
+
|
| 142 |
+
segment = SEGMENTS[int(s[11])]
|
| 143 |
+
cspace = int(s[12])
|
| 144 |
+
|
| 145 |
+
if cspace != 0:
|
| 146 |
+
msg = "cannot handle HSV colour space"
|
| 147 |
+
raise OSError(msg)
|
| 148 |
+
|
| 149 |
+
self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
|
lib/python3.10/site-packages/PIL/Hdf5StubImagePlugin.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# HDF5 stub adapter
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 2000-2003 by Fredrik Lundh
|
| 8 |
+
#
|
| 9 |
+
# See the README file for information on usage and redistribution.
|
| 10 |
+
#
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import IO
|
| 14 |
+
|
| 15 |
+
from . import Image, ImageFile
|
| 16 |
+
|
| 17 |
+
_handler = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 21 |
+
"""
|
| 22 |
+
Install application-specific HDF5 image handler.
|
| 23 |
+
|
| 24 |
+
:param handler: Handler object.
|
| 25 |
+
"""
|
| 26 |
+
global _handler
|
| 27 |
+
_handler = handler
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# --------------------------------------------------------------------
|
| 31 |
+
# Image adapter
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return prefix[:8] == b"\x89HDF\r\n\x1a\n"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class HDF5StubImageFile(ImageFile.StubImageFile):
|
| 39 |
+
format = "HDF5"
|
| 40 |
+
format_description = "HDF5"
|
| 41 |
+
|
| 42 |
+
def _open(self) -> None:
|
| 43 |
+
offset = self.fp.tell()
|
| 44 |
+
|
| 45 |
+
if not _accept(self.fp.read(8)):
|
| 46 |
+
msg = "Not an HDF file"
|
| 47 |
+
raise SyntaxError(msg)
|
| 48 |
+
|
| 49 |
+
self.fp.seek(offset)
|
| 50 |
+
|
| 51 |
+
# make something up
|
| 52 |
+
self._mode = "F"
|
| 53 |
+
self._size = 1, 1
|
| 54 |
+
|
| 55 |
+
loader = self._load()
|
| 56 |
+
if loader:
|
| 57 |
+
loader.open(self)
|
| 58 |
+
|
| 59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 60 |
+
return _handler
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 65 |
+
msg = "HDF5 save handler not installed"
|
| 66 |
+
raise OSError(msg)
|
| 67 |
+
_handler.save(im, fp, filename)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --------------------------------------------------------------------
|
| 71 |
+
# Registry
|
| 72 |
+
|
| 73 |
+
Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
|
| 74 |
+
Image.register_save(HDF5StubImageFile.format, _save)
|
| 75 |
+
|
| 76 |
+
Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
|
lib/python3.10/site-packages/PIL/ImageChops.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# standard channel operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-03-24 fl Created
|
| 9 |
+
# 1996-08-13 fl Added logical operations (for "1" images)
|
| 10 |
+
# 2000-10-12 fl Added offset method (from Image.py)
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 1997-2000 by Secret Labs AB
|
| 13 |
+
# Copyright (c) 1996-2000 by Fredrik Lundh
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from . import Image
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def constant(image: Image.Image, value: int) -> Image.Image:
|
| 24 |
+
"""Fill a channel with a given gray level.
|
| 25 |
+
|
| 26 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
return Image.new("L", image.size, value)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def duplicate(image: Image.Image) -> Image.Image:
|
| 33 |
+
"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
|
| 34 |
+
|
| 35 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
return image.copy()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def invert(image: Image.Image) -> Image.Image:
|
| 42 |
+
"""
|
| 43 |
+
Invert an image (channel). ::
|
| 44 |
+
|
| 45 |
+
out = MAX - image
|
| 46 |
+
|
| 47 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
image.load()
|
| 51 |
+
return image._new(image.im.chop_invert())
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 55 |
+
"""
|
| 56 |
+
Compares the two images, pixel by pixel, and returns a new image containing
|
| 57 |
+
the lighter values. ::
|
| 58 |
+
|
| 59 |
+
out = max(image1, image2)
|
| 60 |
+
|
| 61 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
image1.load()
|
| 65 |
+
image2.load()
|
| 66 |
+
return image1._new(image1.im.chop_lighter(image2.im))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 70 |
+
"""
|
| 71 |
+
Compares the two images, pixel by pixel, and returns a new image containing
|
| 72 |
+
the darker values. ::
|
| 73 |
+
|
| 74 |
+
out = min(image1, image2)
|
| 75 |
+
|
| 76 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
image1.load()
|
| 80 |
+
image2.load()
|
| 81 |
+
return image1._new(image1.im.chop_darker(image2.im))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 85 |
+
"""
|
| 86 |
+
Returns the absolute value of the pixel-by-pixel difference between the two
|
| 87 |
+
images. ::
|
| 88 |
+
|
| 89 |
+
out = abs(image1 - image2)
|
| 90 |
+
|
| 91 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
image1.load()
|
| 95 |
+
image2.load()
|
| 96 |
+
return image1._new(image1.im.chop_difference(image2.im))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 100 |
+
"""
|
| 101 |
+
Superimposes two images on top of each other.
|
| 102 |
+
|
| 103 |
+
If you multiply an image with a solid black image, the result is black. If
|
| 104 |
+
you multiply with a solid white image, the image is unaffected. ::
|
| 105 |
+
|
| 106 |
+
out = image1 * image2 / MAX
|
| 107 |
+
|
| 108 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
image1.load()
|
| 112 |
+
image2.load()
|
| 113 |
+
return image1._new(image1.im.chop_multiply(image2.im))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 117 |
+
"""
|
| 118 |
+
Superimposes two inverted images on top of each other. ::
|
| 119 |
+
|
| 120 |
+
out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
|
| 121 |
+
|
| 122 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
image1.load()
|
| 126 |
+
image2.load()
|
| 127 |
+
return image1._new(image1.im.chop_screen(image2.im))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 131 |
+
"""
|
| 132 |
+
Superimposes two images on top of each other using the Soft Light algorithm
|
| 133 |
+
|
| 134 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
image1.load()
|
| 138 |
+
image2.load()
|
| 139 |
+
return image1._new(image1.im.chop_soft_light(image2.im))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 143 |
+
"""
|
| 144 |
+
Superimposes two images on top of each other using the Hard Light algorithm
|
| 145 |
+
|
| 146 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
image1.load()
|
| 150 |
+
image2.load()
|
| 151 |
+
return image1._new(image1.im.chop_hard_light(image2.im))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 155 |
+
"""
|
| 156 |
+
Superimposes two images on top of each other using the Overlay algorithm
|
| 157 |
+
|
| 158 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
image1.load()
|
| 162 |
+
image2.load()
|
| 163 |
+
return image1._new(image1.im.chop_overlay(image2.im))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def add(
|
| 167 |
+
image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
|
| 168 |
+
) -> Image.Image:
|
| 169 |
+
"""
|
| 170 |
+
Adds two images, dividing the result by scale and adding the
|
| 171 |
+
offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
|
| 172 |
+
|
| 173 |
+
out = ((image1 + image2) / scale + offset)
|
| 174 |
+
|
| 175 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
image1.load()
|
| 179 |
+
image2.load()
|
| 180 |
+
return image1._new(image1.im.chop_add(image2.im, scale, offset))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def subtract(
|
| 184 |
+
image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
|
| 185 |
+
) -> Image.Image:
|
| 186 |
+
"""
|
| 187 |
+
Subtracts two images, dividing the result by scale and adding the offset.
|
| 188 |
+
If omitted, scale defaults to 1.0, and offset to 0.0. ::
|
| 189 |
+
|
| 190 |
+
out = ((image1 - image2) / scale + offset)
|
| 191 |
+
|
| 192 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
image1.load()
|
| 196 |
+
image2.load()
|
| 197 |
+
return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 201 |
+
"""Add two images, without clipping the result. ::
|
| 202 |
+
|
| 203 |
+
out = ((image1 + image2) % MAX)
|
| 204 |
+
|
| 205 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
image1.load()
|
| 209 |
+
image2.load()
|
| 210 |
+
return image1._new(image1.im.chop_add_modulo(image2.im))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 214 |
+
"""Subtract two images, without clipping the result. ::
|
| 215 |
+
|
| 216 |
+
out = ((image1 - image2) % MAX)
|
| 217 |
+
|
| 218 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
image1.load()
|
| 222 |
+
image2.load()
|
| 223 |
+
return image1._new(image1.im.chop_subtract_modulo(image2.im))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 227 |
+
"""Logical AND between two images.
|
| 228 |
+
|
| 229 |
+
Both of the images must have mode "1". If you would like to perform a
|
| 230 |
+
logical AND on an image with a mode other than "1", try
|
| 231 |
+
:py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
|
| 232 |
+
as the second image. ::
|
| 233 |
+
|
| 234 |
+
out = ((image1 and image2) % MAX)
|
| 235 |
+
|
| 236 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
image1.load()
|
| 240 |
+
image2.load()
|
| 241 |
+
return image1._new(image1.im.chop_and(image2.im))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 245 |
+
"""Logical OR between two images.
|
| 246 |
+
|
| 247 |
+
Both of the images must have mode "1". ::
|
| 248 |
+
|
| 249 |
+
out = ((image1 or image2) % MAX)
|
| 250 |
+
|
| 251 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 252 |
+
"""
|
| 253 |
+
|
| 254 |
+
image1.load()
|
| 255 |
+
image2.load()
|
| 256 |
+
return image1._new(image1.im.chop_or(image2.im))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
|
| 260 |
+
"""Logical XOR between two images.
|
| 261 |
+
|
| 262 |
+
Both of the images must have mode "1". ::
|
| 263 |
+
|
| 264 |
+
out = ((bool(image1) != bool(image2)) % MAX)
|
| 265 |
+
|
| 266 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
image1.load()
|
| 270 |
+
image2.load()
|
| 271 |
+
return image1._new(image1.im.chop_xor(image2.im))
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
|
| 275 |
+
"""Blend images using constant transparency weight. Alias for
|
| 276 |
+
:py:func:`PIL.Image.blend`.
|
| 277 |
+
|
| 278 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
return Image.blend(image1, image2, alpha)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def composite(
|
| 285 |
+
image1: Image.Image, image2: Image.Image, mask: Image.Image
|
| 286 |
+
) -> Image.Image:
|
| 287 |
+
"""Create composite using transparency mask. Alias for
|
| 288 |
+
:py:func:`PIL.Image.composite`.
|
| 289 |
+
|
| 290 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
return Image.composite(image1, image2, mask)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
|
| 297 |
+
"""Returns a copy of the image where data has been offset by the given
|
| 298 |
+
distances. Data wraps around the edges. If ``yoffset`` is omitted, it
|
| 299 |
+
is assumed to be equal to ``xoffset``.
|
| 300 |
+
|
| 301 |
+
:param image: Input image.
|
| 302 |
+
:param xoffset: The horizontal distance.
|
| 303 |
+
:param yoffset: The vertical distance. If omitted, both
|
| 304 |
+
distances are set to the same value.
|
| 305 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
if yoffset is None:
|
| 309 |
+
yoffset = xoffset
|
| 310 |
+
image.load()
|
| 311 |
+
return image._new(image.im.offset(xoffset, yoffset))
|
lib/python3.10/site-packages/PIL/ImageCms.py
ADDED
|
@@ -0,0 +1,1125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The Python Imaging Library.
|
| 2 |
+
# $Id$
|
| 3 |
+
|
| 4 |
+
# Optional color management support, based on Kevin Cazabon's PyCMS
|
| 5 |
+
# library.
|
| 6 |
+
|
| 7 |
+
# Originally released under LGPL. Graciously donated to PIL in
|
| 8 |
+
# March 2009, for distribution under the standard PIL license
|
| 9 |
+
|
| 10 |
+
# History:
|
| 11 |
+
|
| 12 |
+
# 2009-03-08 fl Added to PIL.
|
| 13 |
+
|
| 14 |
+
# Copyright (C) 2002-2003 Kevin Cazabon
|
| 15 |
+
# Copyright (c) 2009 by Fredrik Lundh
|
| 16 |
+
# Copyright (c) 2013 by Eric Soroos
|
| 17 |
+
|
| 18 |
+
# See the README file for information on usage and redistribution. See
|
| 19 |
+
# below for the original description.
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import operator
|
| 23 |
+
import sys
|
| 24 |
+
from enum import IntEnum, IntFlag
|
| 25 |
+
from functools import reduce
|
| 26 |
+
from typing import Any, Literal, SupportsFloat, SupportsInt, Union
|
| 27 |
+
|
| 28 |
+
from . import Image, __version__
|
| 29 |
+
from ._deprecate import deprecate
|
| 30 |
+
from ._typing import SupportsRead
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
from . import _imagingcms as core
|
| 34 |
+
|
| 35 |
+
_CmsProfileCompatible = Union[
|
| 36 |
+
str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile"
|
| 37 |
+
]
|
| 38 |
+
except ImportError as ex:
|
| 39 |
+
# Allow error import for doc purposes, but error out when accessing
|
| 40 |
+
# anything in core.
|
| 41 |
+
from ._util import DeferredError
|
| 42 |
+
|
| 43 |
+
core = DeferredError.new(ex)
|
| 44 |
+
|
| 45 |
+
_DESCRIPTION = """
|
| 46 |
+
pyCMS
|
| 47 |
+
|
| 48 |
+
a Python / PIL interface to the littleCMS ICC Color Management System
|
| 49 |
+
Copyright (C) 2002-2003 Kevin Cazabon
|
| 50 |
+
kevin@cazabon.com
|
| 51 |
+
https://www.cazabon.com
|
| 52 |
+
|
| 53 |
+
pyCMS home page: https://www.cazabon.com/pyCMS
|
| 54 |
+
littleCMS home page: https://www.littlecms.com
|
| 55 |
+
(littleCMS is Copyright (C) 1998-2001 Marti Maria)
|
| 56 |
+
|
| 57 |
+
Originally released under LGPL. Graciously donated to PIL in
|
| 58 |
+
March 2009, for distribution under the standard PIL license
|
| 59 |
+
|
| 60 |
+
The pyCMS.py module provides a "clean" interface between Python/PIL and
|
| 61 |
+
pyCMSdll, taking care of some of the more complex handling of the direct
|
| 62 |
+
pyCMSdll functions, as well as error-checking and making sure that all
|
| 63 |
+
relevant data is kept together.
|
| 64 |
+
|
| 65 |
+
While it is possible to call pyCMSdll functions directly, it's not highly
|
| 66 |
+
recommended.
|
| 67 |
+
|
| 68 |
+
Version History:
|
| 69 |
+
|
| 70 |
+
1.0.0 pil Oct 2013 Port to LCMS 2.
|
| 71 |
+
|
| 72 |
+
0.1.0 pil mod March 10, 2009
|
| 73 |
+
|
| 74 |
+
Renamed display profile to proof profile. The proof
|
| 75 |
+
profile is the profile of the device that is being
|
| 76 |
+
simulated, not the profile of the device which is
|
| 77 |
+
actually used to display/print the final simulation
|
| 78 |
+
(that'd be the output profile) - also see LCMSAPI.txt
|
| 79 |
+
input colorspace -> using 'renderingIntent' -> proof
|
| 80 |
+
colorspace -> using 'proofRenderingIntent' -> output
|
| 81 |
+
colorspace
|
| 82 |
+
|
| 83 |
+
Added LCMS FLAGS support.
|
| 84 |
+
Added FLAGS["SOFTPROOFING"] as default flag for
|
| 85 |
+
buildProofTransform (otherwise the proof profile/intent
|
| 86 |
+
would be ignored).
|
| 87 |
+
|
| 88 |
+
0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
|
| 89 |
+
|
| 90 |
+
0.0.2 alpha Jan 6, 2002
|
| 91 |
+
|
| 92 |
+
Added try/except statements around type() checks of
|
| 93 |
+
potential CObjects... Python won't let you use type()
|
| 94 |
+
on them, and raises a TypeError (stupid, if you ask
|
| 95 |
+
me!)
|
| 96 |
+
|
| 97 |
+
Added buildProofTransformFromOpenProfiles() function.
|
| 98 |
+
Additional fixes in DLL, see DLL code for details.
|
| 99 |
+
|
| 100 |
+
0.0.1 alpha first public release, Dec. 26, 2002
|
| 101 |
+
|
| 102 |
+
Known to-do list with current version (of Python interface, not pyCMSdll):
|
| 103 |
+
|
| 104 |
+
none
|
| 105 |
+
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
_VERSION = "1.0.0 pil"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def __getattr__(name: str) -> Any:
|
| 112 |
+
if name == "DESCRIPTION":
|
| 113 |
+
deprecate("PIL.ImageCms.DESCRIPTION", 12)
|
| 114 |
+
return _DESCRIPTION
|
| 115 |
+
elif name == "VERSION":
|
| 116 |
+
deprecate("PIL.ImageCms.VERSION", 12)
|
| 117 |
+
return _VERSION
|
| 118 |
+
elif name == "FLAGS":
|
| 119 |
+
deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
|
| 120 |
+
return _FLAGS
|
| 121 |
+
msg = f"module '{__name__}' has no attribute '{name}'"
|
| 122 |
+
raise AttributeError(msg)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# --------------------------------------------------------------------.
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
#
|
| 129 |
+
# intent/direction values
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class Intent(IntEnum):
|
| 133 |
+
PERCEPTUAL = 0
|
| 134 |
+
RELATIVE_COLORIMETRIC = 1
|
| 135 |
+
SATURATION = 2
|
| 136 |
+
ABSOLUTE_COLORIMETRIC = 3
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class Direction(IntEnum):
|
| 140 |
+
INPUT = 0
|
| 141 |
+
OUTPUT = 1
|
| 142 |
+
PROOF = 2
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
#
|
| 146 |
+
# flags
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Flags(IntFlag):
|
| 150 |
+
"""Flags and documentation are taken from ``lcms2.h``."""
|
| 151 |
+
|
| 152 |
+
NONE = 0
|
| 153 |
+
NOCACHE = 0x0040
|
| 154 |
+
"""Inhibit 1-pixel cache"""
|
| 155 |
+
NOOPTIMIZE = 0x0100
|
| 156 |
+
"""Inhibit optimizations"""
|
| 157 |
+
NULLTRANSFORM = 0x0200
|
| 158 |
+
"""Don't transform anyway"""
|
| 159 |
+
GAMUTCHECK = 0x1000
|
| 160 |
+
"""Out of Gamut alarm"""
|
| 161 |
+
SOFTPROOFING = 0x4000
|
| 162 |
+
"""Do softproofing"""
|
| 163 |
+
BLACKPOINTCOMPENSATION = 0x2000
|
| 164 |
+
NOWHITEONWHITEFIXUP = 0x0004
|
| 165 |
+
"""Don't fix scum dot"""
|
| 166 |
+
HIGHRESPRECALC = 0x0400
|
| 167 |
+
"""Use more memory to give better accuracy"""
|
| 168 |
+
LOWRESPRECALC = 0x0800
|
| 169 |
+
"""Use less memory to minimize resources"""
|
| 170 |
+
# this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
|
| 171 |
+
USE_8BITS_DEVICELINK = 0x0008
|
| 172 |
+
"""Create 8 bits devicelinks"""
|
| 173 |
+
GUESSDEVICECLASS = 0x0020
|
| 174 |
+
"""Guess device class (for ``transform2devicelink``)"""
|
| 175 |
+
KEEP_SEQUENCE = 0x0080
|
| 176 |
+
"""Keep profile sequence for devicelink creation"""
|
| 177 |
+
FORCE_CLUT = 0x0002
|
| 178 |
+
"""Force CLUT optimization"""
|
| 179 |
+
CLUT_POST_LINEARIZATION = 0x0001
|
| 180 |
+
"""create postlinearization tables if possible"""
|
| 181 |
+
CLUT_PRE_LINEARIZATION = 0x0010
|
| 182 |
+
"""create prelinearization tables if possible"""
|
| 183 |
+
NONEGATIVES = 0x8000
|
| 184 |
+
"""Prevent negative numbers in floating point transforms"""
|
| 185 |
+
COPY_ALPHA = 0x04000000
|
| 186 |
+
"""Alpha channels are copied on ``cmsDoTransform()``"""
|
| 187 |
+
NODEFAULTRESOURCEDEF = 0x01000000
|
| 188 |
+
|
| 189 |
+
_GRIDPOINTS_1 = 1 << 16
|
| 190 |
+
_GRIDPOINTS_2 = 2 << 16
|
| 191 |
+
_GRIDPOINTS_4 = 4 << 16
|
| 192 |
+
_GRIDPOINTS_8 = 8 << 16
|
| 193 |
+
_GRIDPOINTS_16 = 16 << 16
|
| 194 |
+
_GRIDPOINTS_32 = 32 << 16
|
| 195 |
+
_GRIDPOINTS_64 = 64 << 16
|
| 196 |
+
_GRIDPOINTS_128 = 128 << 16
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def GRIDPOINTS(n: int) -> Flags:
|
| 200 |
+
"""
|
| 201 |
+
Fine-tune control over number of gridpoints
|
| 202 |
+
|
| 203 |
+
:param n: :py:class:`int` in range ``0 <= n <= 255``
|
| 204 |
+
"""
|
| 205 |
+
return Flags.NONE | ((n & 0xFF) << 16)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
_MAX_FLAG = reduce(operator.or_, Flags)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
_FLAGS = {
|
| 212 |
+
"MATRIXINPUT": 1,
|
| 213 |
+
"MATRIXOUTPUT": 2,
|
| 214 |
+
"MATRIXONLY": (1 | 2),
|
| 215 |
+
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
|
| 216 |
+
# Don't create prelinearization tables on precalculated transforms
|
| 217 |
+
# (internal use):
|
| 218 |
+
"NOPRELINEARIZATION": 16,
|
| 219 |
+
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
|
| 220 |
+
"NOTCACHE": 64, # Inhibit 1-pixel cache
|
| 221 |
+
"NOTPRECALC": 256,
|
| 222 |
+
"NULLTRANSFORM": 512, # Don't transform anyway
|
| 223 |
+
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
|
| 224 |
+
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
|
| 225 |
+
"WHITEBLACKCOMPENSATION": 8192,
|
| 226 |
+
"BLACKPOINTCOMPENSATION": 8192,
|
| 227 |
+
"GAMUTCHECK": 4096, # Out of Gamut alarm
|
| 228 |
+
"SOFTPROOFING": 16384, # Do softproofing
|
| 229 |
+
"PRESERVEBLACK": 32768, # Black preservation
|
| 230 |
+
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
|
| 231 |
+
"GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# --------------------------------------------------------------------.
|
| 236 |
+
# Experimental PIL-level API
|
| 237 |
+
# --------------------------------------------------------------------.
|
| 238 |
+
|
| 239 |
+
##
|
| 240 |
+
# Profile.
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class ImageCmsProfile:
|
| 244 |
+
def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
|
| 245 |
+
"""
|
| 246 |
+
:param profile: Either a string representing a filename,
|
| 247 |
+
a file like object containing a profile or a
|
| 248 |
+
low-level profile object
|
| 249 |
+
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
if isinstance(profile, str):
|
| 253 |
+
if sys.platform == "win32":
|
| 254 |
+
profile_bytes_path = profile.encode()
|
| 255 |
+
try:
|
| 256 |
+
profile_bytes_path.decode("ascii")
|
| 257 |
+
except UnicodeDecodeError:
|
| 258 |
+
with open(profile, "rb") as f:
|
| 259 |
+
self._set(core.profile_frombytes(f.read()))
|
| 260 |
+
return
|
| 261 |
+
self._set(core.profile_open(profile), profile)
|
| 262 |
+
elif hasattr(profile, "read"):
|
| 263 |
+
self._set(core.profile_frombytes(profile.read()))
|
| 264 |
+
elif isinstance(profile, core.CmsProfile):
|
| 265 |
+
self._set(profile)
|
| 266 |
+
else:
|
| 267 |
+
msg = "Invalid type for Profile" # type: ignore[unreachable]
|
| 268 |
+
raise TypeError(msg)
|
| 269 |
+
|
| 270 |
+
def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
|
| 271 |
+
self.profile = profile
|
| 272 |
+
self.filename = filename
|
| 273 |
+
self.product_name = None # profile.product_name
|
| 274 |
+
self.product_info = None # profile.product_info
|
| 275 |
+
|
| 276 |
+
def tobytes(self) -> bytes:
|
| 277 |
+
"""
|
| 278 |
+
Returns the profile in a format suitable for embedding in
|
| 279 |
+
saved images.
|
| 280 |
+
|
| 281 |
+
:returns: a bytes object containing the ICC profile.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
return core.profile_tobytes(self.profile)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class ImageCmsTransform(Image.ImagePointHandler):
|
| 288 |
+
"""
|
| 289 |
+
Transform. This can be used with the procedural API, or with the standard
|
| 290 |
+
:py:func:`~PIL.Image.Image.point` method.
|
| 291 |
+
|
| 292 |
+
Will return the output profile in the ``output.info['icc_profile']``.
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
def __init__(
|
| 296 |
+
self,
|
| 297 |
+
input: ImageCmsProfile,
|
| 298 |
+
output: ImageCmsProfile,
|
| 299 |
+
input_mode: str,
|
| 300 |
+
output_mode: str,
|
| 301 |
+
intent: Intent = Intent.PERCEPTUAL,
|
| 302 |
+
proof: ImageCmsProfile | None = None,
|
| 303 |
+
proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 304 |
+
flags: Flags = Flags.NONE,
|
| 305 |
+
):
|
| 306 |
+
supported_modes = (
|
| 307 |
+
"RGB",
|
| 308 |
+
"RGBA",
|
| 309 |
+
"RGBX",
|
| 310 |
+
"CMYK",
|
| 311 |
+
"I;16",
|
| 312 |
+
"I;16L",
|
| 313 |
+
"I;16B",
|
| 314 |
+
"YCbCr",
|
| 315 |
+
"LAB",
|
| 316 |
+
"L",
|
| 317 |
+
"1",
|
| 318 |
+
)
|
| 319 |
+
for mode in (input_mode, output_mode):
|
| 320 |
+
if mode not in supported_modes:
|
| 321 |
+
deprecate(
|
| 322 |
+
mode,
|
| 323 |
+
12,
|
| 324 |
+
{
|
| 325 |
+
"L;16": "I;16 or I;16L",
|
| 326 |
+
"L:16B": "I;16B",
|
| 327 |
+
"YCCA": "YCbCr",
|
| 328 |
+
"YCC": "YCbCr",
|
| 329 |
+
}.get(mode),
|
| 330 |
+
)
|
| 331 |
+
if proof is None:
|
| 332 |
+
self.transform = core.buildTransform(
|
| 333 |
+
input.profile, output.profile, input_mode, output_mode, intent, flags
|
| 334 |
+
)
|
| 335 |
+
else:
|
| 336 |
+
self.transform = core.buildProofTransform(
|
| 337 |
+
input.profile,
|
| 338 |
+
output.profile,
|
| 339 |
+
proof.profile,
|
| 340 |
+
input_mode,
|
| 341 |
+
output_mode,
|
| 342 |
+
intent,
|
| 343 |
+
proof_intent,
|
| 344 |
+
flags,
|
| 345 |
+
)
|
| 346 |
+
# Note: inputMode and outputMode are for pyCMS compatibility only
|
| 347 |
+
self.input_mode = self.inputMode = input_mode
|
| 348 |
+
self.output_mode = self.outputMode = output_mode
|
| 349 |
+
|
| 350 |
+
self.output_profile = output
|
| 351 |
+
|
| 352 |
+
def point(self, im: Image.Image) -> Image.Image:
|
| 353 |
+
return self.apply(im)
|
| 354 |
+
|
| 355 |
+
def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
|
| 356 |
+
if imOut is None:
|
| 357 |
+
imOut = Image.new(self.output_mode, im.size, None)
|
| 358 |
+
self.transform.apply(im.getim(), imOut.getim())
|
| 359 |
+
imOut.info["icc_profile"] = self.output_profile.tobytes()
|
| 360 |
+
return imOut
|
| 361 |
+
|
| 362 |
+
def apply_in_place(self, im: Image.Image) -> Image.Image:
|
| 363 |
+
if im.mode != self.output_mode:
|
| 364 |
+
msg = "mode mismatch"
|
| 365 |
+
raise ValueError(msg) # wrong output mode
|
| 366 |
+
self.transform.apply(im.getim(), im.getim())
|
| 367 |
+
im.info["icc_profile"] = self.output_profile.tobytes()
|
| 368 |
+
return im
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
|
| 372 |
+
"""
|
| 373 |
+
(experimental) Fetches the profile for the current display device.
|
| 374 |
+
|
| 375 |
+
:returns: ``None`` if the profile is not known.
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
if sys.platform != "win32":
|
| 379 |
+
return None
|
| 380 |
+
|
| 381 |
+
from . import ImageWin # type: ignore[unused-ignore, unreachable]
|
| 382 |
+
|
| 383 |
+
if isinstance(handle, ImageWin.HDC):
|
| 384 |
+
profile = core.get_display_profile_win32(int(handle), 1)
|
| 385 |
+
else:
|
| 386 |
+
profile = core.get_display_profile_win32(int(handle or 0))
|
| 387 |
+
if profile is None:
|
| 388 |
+
return None
|
| 389 |
+
return ImageCmsProfile(profile)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# --------------------------------------------------------------------.
|
| 393 |
+
# pyCMS compatible layer
|
| 394 |
+
# --------------------------------------------------------------------.
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class PyCMSError(Exception):
|
| 398 |
+
"""(pyCMS) Exception class.
|
| 399 |
+
This is used for all errors in the pyCMS API."""
|
| 400 |
+
|
| 401 |
+
pass
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def profileToProfile(
|
| 405 |
+
im: Image.Image,
|
| 406 |
+
inputProfile: _CmsProfileCompatible,
|
| 407 |
+
outputProfile: _CmsProfileCompatible,
|
| 408 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 409 |
+
outputMode: str | None = None,
|
| 410 |
+
inPlace: bool = False,
|
| 411 |
+
flags: Flags = Flags.NONE,
|
| 412 |
+
) -> Image.Image | None:
|
| 413 |
+
"""
|
| 414 |
+
(pyCMS) Applies an ICC transformation to a given image, mapping from
|
| 415 |
+
``inputProfile`` to ``outputProfile``.
|
| 416 |
+
|
| 417 |
+
If the input or output profiles specified are not valid filenames, a
|
| 418 |
+
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
|
| 419 |
+
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
|
| 420 |
+
If an error occurs during application of the profiles,
|
| 421 |
+
a :exc:`PyCMSError` will be raised.
|
| 422 |
+
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
|
| 423 |
+
a :exc:`PyCMSError` will be raised.
|
| 424 |
+
|
| 425 |
+
This function applies an ICC transformation to im from ``inputProfile``'s
|
| 426 |
+
color space to ``outputProfile``'s color space using the specified rendering
|
| 427 |
+
intent to decide how to handle out-of-gamut colors.
|
| 428 |
+
|
| 429 |
+
``outputMode`` can be used to specify that a color mode conversion is to
|
| 430 |
+
be done using these profiles, but the specified profiles must be able
|
| 431 |
+
to handle that mode. I.e., if converting im from RGB to CMYK using
|
| 432 |
+
profiles, the input profile must handle RGB data, and the output
|
| 433 |
+
profile must handle CMYK data.
|
| 434 |
+
|
| 435 |
+
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
|
| 436 |
+
or Image.open(...), etc.)
|
| 437 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 438 |
+
profile you wish to use for this image, or a profile object
|
| 439 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 440 |
+
profile you wish to use for this image, or a profile object
|
| 441 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 442 |
+
wish to use for the transform
|
| 443 |
+
|
| 444 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 445 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 446 |
+
ImageCms.Intent.SATURATION = 2
|
| 447 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 448 |
+
|
| 449 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 450 |
+
they do.
|
| 451 |
+
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
|
| 452 |
+
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
|
| 453 |
+
MUST be the same mode as the input, or omitted completely. If
|
| 454 |
+
omitted, the outputMode will be the same as the mode of the input
|
| 455 |
+
image (im.mode)
|
| 456 |
+
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
|
| 457 |
+
and ``None`` is returned. If ``False`` (default), a new
|
| 458 |
+
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
|
| 459 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 460 |
+
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
|
| 461 |
+
the value of ``inPlace``
|
| 462 |
+
:exception PyCMSError:
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
if outputMode is None:
|
| 466 |
+
outputMode = im.mode
|
| 467 |
+
|
| 468 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 469 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 470 |
+
raise PyCMSError(msg)
|
| 471 |
+
|
| 472 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 473 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 474 |
+
raise PyCMSError(msg)
|
| 475 |
+
|
| 476 |
+
try:
|
| 477 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 478 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 479 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 480 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 481 |
+
transform = ImageCmsTransform(
|
| 482 |
+
inputProfile,
|
| 483 |
+
outputProfile,
|
| 484 |
+
im.mode,
|
| 485 |
+
outputMode,
|
| 486 |
+
renderingIntent,
|
| 487 |
+
flags=flags,
|
| 488 |
+
)
|
| 489 |
+
if inPlace:
|
| 490 |
+
transform.apply_in_place(im)
|
| 491 |
+
imOut = None
|
| 492 |
+
else:
|
| 493 |
+
imOut = transform.apply(im)
|
| 494 |
+
except (OSError, TypeError, ValueError) as v:
|
| 495 |
+
raise PyCMSError(v) from v
|
| 496 |
+
|
| 497 |
+
return imOut
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def getOpenProfile(
|
| 501 |
+
profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
|
| 502 |
+
) -> ImageCmsProfile:
|
| 503 |
+
"""
|
| 504 |
+
(pyCMS) Opens an ICC profile file.
|
| 505 |
+
|
| 506 |
+
The PyCMSProfile object can be passed back into pyCMS for use in creating
|
| 507 |
+
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
|
| 508 |
+
|
| 509 |
+
If ``profileFilename`` is not a valid filename for an ICC profile,
|
| 510 |
+
a :exc:`PyCMSError` will be raised.
|
| 511 |
+
|
| 512 |
+
:param profileFilename: String, as a valid filename path to the ICC profile
|
| 513 |
+
you wish to open, or a file-like object.
|
| 514 |
+
:returns: A CmsProfile class object.
|
| 515 |
+
:exception PyCMSError:
|
| 516 |
+
"""
|
| 517 |
+
|
| 518 |
+
try:
|
| 519 |
+
return ImageCmsProfile(profileFilename)
|
| 520 |
+
except (OSError, TypeError, ValueError) as v:
|
| 521 |
+
raise PyCMSError(v) from v
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def buildTransform(
|
| 525 |
+
inputProfile: _CmsProfileCompatible,
|
| 526 |
+
outputProfile: _CmsProfileCompatible,
|
| 527 |
+
inMode: str,
|
| 528 |
+
outMode: str,
|
| 529 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 530 |
+
flags: Flags = Flags.NONE,
|
| 531 |
+
) -> ImageCmsTransform:
|
| 532 |
+
"""
|
| 533 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 534 |
+
``outputProfile``. Use applyTransform to apply the transform to a given
|
| 535 |
+
image.
|
| 536 |
+
|
| 537 |
+
If the input or output profiles specified are not valid filenames, a
|
| 538 |
+
:exc:`PyCMSError` will be raised. If an error occurs during creation
|
| 539 |
+
of the transform, a :exc:`PyCMSError` will be raised.
|
| 540 |
+
|
| 541 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 542 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 543 |
+
|
| 544 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 545 |
+
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
|
| 546 |
+
with out-of-gamut colors. It will ONLY work for converting images that
|
| 547 |
+
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
|
| 548 |
+
i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 549 |
+
|
| 550 |
+
Building the transform is a fair part of the overhead in
|
| 551 |
+
ImageCms.profileToProfile(), so if you're planning on converting multiple
|
| 552 |
+
images using the same input/output settings, this can save you time.
|
| 553 |
+
Once you have a transform object, it can be used with
|
| 554 |
+
ImageCms.applyProfile() to convert images without the need to re-compute
|
| 555 |
+
the lookup table for the transform.
|
| 556 |
+
|
| 557 |
+
The reason pyCMS returns a class object rather than a handle directly
|
| 558 |
+
to the transform is that it needs to keep track of the PIL input/output
|
| 559 |
+
modes that the transform is meant for. These attributes are stored in
|
| 560 |
+
the ``inMode`` and ``outMode`` attributes of the object (which can be
|
| 561 |
+
manually overridden if you really want to, but I don't know of any
|
| 562 |
+
time that would be of use, or would even work).
|
| 563 |
+
|
| 564 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 565 |
+
profile you wish to use for this transform, or a profile object
|
| 566 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 567 |
+
profile you wish to use for this transform, or a profile object
|
| 568 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 569 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 570 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 571 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 572 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 573 |
+
wish to use for the transform
|
| 574 |
+
|
| 575 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 576 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 577 |
+
ImageCms.Intent.SATURATION = 2
|
| 578 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 579 |
+
|
| 580 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 581 |
+
they do.
|
| 582 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 583 |
+
:returns: A CmsTransform class object.
|
| 584 |
+
:exception PyCMSError:
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 588 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 589 |
+
raise PyCMSError(msg)
|
| 590 |
+
|
| 591 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 592 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 593 |
+
raise PyCMSError(msg)
|
| 594 |
+
|
| 595 |
+
try:
|
| 596 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 597 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 598 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 599 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 600 |
+
return ImageCmsTransform(
|
| 601 |
+
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
|
| 602 |
+
)
|
| 603 |
+
except (OSError, TypeError, ValueError) as v:
|
| 604 |
+
raise PyCMSError(v) from v
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def buildProofTransform(
|
| 608 |
+
inputProfile: _CmsProfileCompatible,
|
| 609 |
+
outputProfile: _CmsProfileCompatible,
|
| 610 |
+
proofProfile: _CmsProfileCompatible,
|
| 611 |
+
inMode: str,
|
| 612 |
+
outMode: str,
|
| 613 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 614 |
+
proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 615 |
+
flags: Flags = Flags.SOFTPROOFING,
|
| 616 |
+
) -> ImageCmsTransform:
|
| 617 |
+
"""
|
| 618 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 619 |
+
``outputProfile``, but tries to simulate the result that would be
|
| 620 |
+
obtained on the ``proofProfile`` device.
|
| 621 |
+
|
| 622 |
+
If the input, output, or proof profiles specified are not valid
|
| 623 |
+
filenames, a :exc:`PyCMSError` will be raised.
|
| 624 |
+
|
| 625 |
+
If an error occurs during creation of the transform,
|
| 626 |
+
a :exc:`PyCMSError` will be raised.
|
| 627 |
+
|
| 628 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 629 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 630 |
+
|
| 631 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 632 |
+
to the ``outputProfile``, but tries to simulate the result that would be
|
| 633 |
+
obtained on the ``proofProfile`` device using ``renderingIntent`` and
|
| 634 |
+
``proofRenderingIntent`` to determine what to do with out-of-gamut
|
| 635 |
+
colors. This is known as "soft-proofing". It will ONLY work for
|
| 636 |
+
converting images that are in ``inMode`` to images that are in outMode
|
| 637 |
+
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 638 |
+
|
| 639 |
+
Usage of the resulting transform object is exactly the same as with
|
| 640 |
+
ImageCms.buildTransform().
|
| 641 |
+
|
| 642 |
+
Proof profiling is generally used when using an output device to get a
|
| 643 |
+
good idea of what the final printed/displayed image would look like on
|
| 644 |
+
the ``proofProfile`` device when it's quicker and easier to use the
|
| 645 |
+
output device for judging color. Generally, this means that the
|
| 646 |
+
output device is a monitor, or a dye-sub printer (etc.), and the simulated
|
| 647 |
+
device is something more expensive, complicated, or time consuming
|
| 648 |
+
(making it difficult to make a real print for color judgement purposes).
|
| 649 |
+
|
| 650 |
+
Soft-proofing basically functions by adjusting the colors on the
|
| 651 |
+
output device to match the colors of the device being simulated. However,
|
| 652 |
+
when the simulated device has a much wider gamut than the output
|
| 653 |
+
device, you may obtain marginal results.
|
| 654 |
+
|
| 655 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 656 |
+
profile you wish to use for this transform, or a profile object
|
| 657 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 658 |
+
(monitor, usually) profile you wish to use for this transform, or a
|
| 659 |
+
profile object
|
| 660 |
+
:param proofProfile: String, as a valid filename path to the ICC proof
|
| 661 |
+
profile you wish to use for this transform, or a profile object
|
| 662 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 663 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 664 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 665 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 666 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 667 |
+
wish to use for the input->proof (simulated) transform
|
| 668 |
+
|
| 669 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 670 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 671 |
+
ImageCms.Intent.SATURATION = 2
|
| 672 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 673 |
+
|
| 674 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 675 |
+
they do.
|
| 676 |
+
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
|
| 677 |
+
you wish to use for proof->output transform
|
| 678 |
+
|
| 679 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 680 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 681 |
+
ImageCms.Intent.SATURATION = 2
|
| 682 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 683 |
+
|
| 684 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 685 |
+
they do.
|
| 686 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 687 |
+
:returns: A CmsTransform class object.
|
| 688 |
+
:exception PyCMSError:
|
| 689 |
+
"""
|
| 690 |
+
|
| 691 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 692 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 693 |
+
raise PyCMSError(msg)
|
| 694 |
+
|
| 695 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 696 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 697 |
+
raise PyCMSError(msg)
|
| 698 |
+
|
| 699 |
+
try:
|
| 700 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 701 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 702 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 703 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 704 |
+
if not isinstance(proofProfile, ImageCmsProfile):
|
| 705 |
+
proofProfile = ImageCmsProfile(proofProfile)
|
| 706 |
+
return ImageCmsTransform(
|
| 707 |
+
inputProfile,
|
| 708 |
+
outputProfile,
|
| 709 |
+
inMode,
|
| 710 |
+
outMode,
|
| 711 |
+
renderingIntent,
|
| 712 |
+
proofProfile,
|
| 713 |
+
proofRenderingIntent,
|
| 714 |
+
flags,
|
| 715 |
+
)
|
| 716 |
+
except (OSError, TypeError, ValueError) as v:
|
| 717 |
+
raise PyCMSError(v) from v
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
buildTransformFromOpenProfiles = buildTransform
|
| 721 |
+
buildProofTransformFromOpenProfiles = buildProofTransform
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def applyTransform(
|
| 725 |
+
im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
|
| 726 |
+
) -> Image.Image | None:
|
| 727 |
+
"""
|
| 728 |
+
(pyCMS) Applies a transform to a given image.
|
| 729 |
+
|
| 730 |
+
If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
|
| 731 |
+
|
| 732 |
+
If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
|
| 733 |
+
:exc:`PyCMSError` is raised.
|
| 734 |
+
|
| 735 |
+
If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
|
| 736 |
+
supported by pyCMSdll or the profiles you used for the transform, a
|
| 737 |
+
:exc:`PyCMSError` is raised.
|
| 738 |
+
|
| 739 |
+
If an error occurs while the transform is being applied,
|
| 740 |
+
a :exc:`PyCMSError` is raised.
|
| 741 |
+
|
| 742 |
+
This function applies a pre-calculated transform (from
|
| 743 |
+
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
|
| 744 |
+
to an image. The transform can be used for multiple images, saving
|
| 745 |
+
considerable calculation time if doing the same conversion multiple times.
|
| 746 |
+
|
| 747 |
+
If you want to modify im in-place instead of receiving a new image as
|
| 748 |
+
the return value, set ``inPlace`` to ``True``. This can only be done if
|
| 749 |
+
``transform.input_mode`` and ``transform.output_mode`` are the same, because we
|
| 750 |
+
can't change the mode in-place (the buffer sizes for some modes are
|
| 751 |
+
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
|
| 752 |
+
object of the same dimensions in mode ``transform.output_mode``.
|
| 753 |
+
|
| 754 |
+
:param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
|
| 755 |
+
as the ``input_mode`` supported by the transform.
|
| 756 |
+
:param transform: A valid CmsTransform class object
|
| 757 |
+
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
|
| 758 |
+
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
|
| 759 |
+
transform applied is returned (and ``im`` is not changed). The default is
|
| 760 |
+
``False``.
|
| 761 |
+
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
|
| 762 |
+
depending on the value of ``inPlace``. The profile will be returned in
|
| 763 |
+
the image's ``info['icc_profile']``.
|
| 764 |
+
:exception PyCMSError:
|
| 765 |
+
"""
|
| 766 |
+
|
| 767 |
+
try:
|
| 768 |
+
if inPlace:
|
| 769 |
+
transform.apply_in_place(im)
|
| 770 |
+
imOut = None
|
| 771 |
+
else:
|
| 772 |
+
imOut = transform.apply(im)
|
| 773 |
+
except (TypeError, ValueError) as v:
|
| 774 |
+
raise PyCMSError(v) from v
|
| 775 |
+
|
| 776 |
+
return imOut
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def createProfile(
|
| 780 |
+
colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
|
| 781 |
+
) -> core.CmsProfile:
|
| 782 |
+
"""
|
| 783 |
+
(pyCMS) Creates a profile.
|
| 784 |
+
|
| 785 |
+
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
|
| 786 |
+
a :exc:`PyCMSError` is raised.
|
| 787 |
+
|
| 788 |
+
If using LAB and ``colorTemp`` is not a positive integer,
|
| 789 |
+
a :exc:`PyCMSError` is raised.
|
| 790 |
+
|
| 791 |
+
If an error occurs while creating the profile,
|
| 792 |
+
a :exc:`PyCMSError` is raised.
|
| 793 |
+
|
| 794 |
+
Use this function to create common profiles on-the-fly instead of
|
| 795 |
+
having to supply a profile on disk and knowing the path to it. It
|
| 796 |
+
returns a normal CmsProfile object that can be passed to
|
| 797 |
+
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
|
| 798 |
+
to images.
|
| 799 |
+
|
| 800 |
+
:param colorSpace: String, the color space of the profile you wish to
|
| 801 |
+
create.
|
| 802 |
+
Currently only "LAB", "XYZ", and "sRGB" are supported.
|
| 803 |
+
:param colorTemp: Positive number for the white point for the profile, in
|
| 804 |
+
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
|
| 805 |
+
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
|
| 806 |
+
profiles, and is ignored for XYZ and sRGB.
|
| 807 |
+
:returns: A CmsProfile class object
|
| 808 |
+
:exception PyCMSError:
|
| 809 |
+
"""
|
| 810 |
+
|
| 811 |
+
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
|
| 812 |
+
msg = (
|
| 813 |
+
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
|
| 814 |
+
)
|
| 815 |
+
raise PyCMSError(msg)
|
| 816 |
+
|
| 817 |
+
if colorSpace == "LAB":
|
| 818 |
+
try:
|
| 819 |
+
colorTemp = float(colorTemp)
|
| 820 |
+
except (TypeError, ValueError) as e:
|
| 821 |
+
msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
|
| 822 |
+
raise PyCMSError(msg) from e
|
| 823 |
+
|
| 824 |
+
try:
|
| 825 |
+
return core.createProfile(colorSpace, colorTemp)
|
| 826 |
+
except (TypeError, ValueError) as v:
|
| 827 |
+
raise PyCMSError(v) from v
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
def getProfileName(profile: _CmsProfileCompatible) -> str:
|
| 831 |
+
"""
|
| 832 |
+
|
| 833 |
+
(pyCMS) Gets the internal product name for the given profile.
|
| 834 |
+
|
| 835 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 836 |
+
a :exc:`PyCMSError` is raised If an error occurs while trying
|
| 837 |
+
to obtain the name tag, a :exc:`PyCMSError` is raised.
|
| 838 |
+
|
| 839 |
+
Use this function to obtain the INTERNAL name of the profile (stored
|
| 840 |
+
in an ICC tag in the profile itself), usually the one used when the
|
| 841 |
+
profile was originally created. Sometimes this tag also contains
|
| 842 |
+
additional information supplied by the creator.
|
| 843 |
+
|
| 844 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 845 |
+
filename of an ICC profile.
|
| 846 |
+
:returns: A string containing the internal name of the profile as stored
|
| 847 |
+
in an ICC tag.
|
| 848 |
+
:exception PyCMSError:
|
| 849 |
+
"""
|
| 850 |
+
|
| 851 |
+
try:
|
| 852 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 853 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 854 |
+
profile = ImageCmsProfile(profile)
|
| 855 |
+
# do it in python, not c.
|
| 856 |
+
# // name was "%s - %s" (model, manufacturer) || Description ,
|
| 857 |
+
# // but if the Model and Manufacturer were the same or the model
|
| 858 |
+
# // was long, Just the model, in 1.x
|
| 859 |
+
model = profile.profile.model
|
| 860 |
+
manufacturer = profile.profile.manufacturer
|
| 861 |
+
|
| 862 |
+
if not (model or manufacturer):
|
| 863 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 864 |
+
if not manufacturer or (model and len(model) > 30):
|
| 865 |
+
return f"{model}\n"
|
| 866 |
+
return f"{model} - {manufacturer}\n"
|
| 867 |
+
|
| 868 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 869 |
+
raise PyCMSError(v) from v
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def getProfileInfo(profile: _CmsProfileCompatible) -> str:
|
| 873 |
+
"""
|
| 874 |
+
(pyCMS) Gets the internal product information for the given profile.
|
| 875 |
+
|
| 876 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 877 |
+
a :exc:`PyCMSError` is raised.
|
| 878 |
+
|
| 879 |
+
If an error occurs while trying to obtain the info tag,
|
| 880 |
+
a :exc:`PyCMSError` is raised.
|
| 881 |
+
|
| 882 |
+
Use this function to obtain the information stored in the profile's
|
| 883 |
+
info tag. This often contains details about the profile, and how it
|
| 884 |
+
was created, as supplied by the creator.
|
| 885 |
+
|
| 886 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 887 |
+
filename of an ICC profile.
|
| 888 |
+
:returns: A string containing the internal profile information stored in
|
| 889 |
+
an ICC tag.
|
| 890 |
+
:exception PyCMSError:
|
| 891 |
+
"""
|
| 892 |
+
|
| 893 |
+
try:
|
| 894 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 895 |
+
profile = ImageCmsProfile(profile)
|
| 896 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 897 |
+
# Python, not C. the white point bits weren't working well,
|
| 898 |
+
# so skipping.
|
| 899 |
+
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
|
| 900 |
+
description = profile.profile.profile_description
|
| 901 |
+
cpright = profile.profile.copyright
|
| 902 |
+
elements = [element for element in (description, cpright) if element]
|
| 903 |
+
return "\r\n\r\n".join(elements) + "\r\n\r\n"
|
| 904 |
+
|
| 905 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 906 |
+
raise PyCMSError(v) from v
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
|
| 910 |
+
"""
|
| 911 |
+
(pyCMS) Gets the copyright for the given profile.
|
| 912 |
+
|
| 913 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 914 |
+
:exc:`PyCMSError` is raised.
|
| 915 |
+
|
| 916 |
+
If an error occurs while trying to obtain the copyright tag,
|
| 917 |
+
a :exc:`PyCMSError` is raised.
|
| 918 |
+
|
| 919 |
+
Use this function to obtain the information stored in the profile's
|
| 920 |
+
copyright tag.
|
| 921 |
+
|
| 922 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 923 |
+
filename of an ICC profile.
|
| 924 |
+
:returns: A string containing the internal profile information stored in
|
| 925 |
+
an ICC tag.
|
| 926 |
+
:exception PyCMSError:
|
| 927 |
+
"""
|
| 928 |
+
try:
|
| 929 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 930 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 931 |
+
profile = ImageCmsProfile(profile)
|
| 932 |
+
return (profile.profile.copyright or "") + "\n"
|
| 933 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 934 |
+
raise PyCMSError(v) from v
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
|
| 938 |
+
"""
|
| 939 |
+
(pyCMS) Gets the manufacturer for the given profile.
|
| 940 |
+
|
| 941 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 942 |
+
:exc:`PyCMSError` is raised.
|
| 943 |
+
|
| 944 |
+
If an error occurs while trying to obtain the manufacturer tag, a
|
| 945 |
+
:exc:`PyCMSError` is raised.
|
| 946 |
+
|
| 947 |
+
Use this function to obtain the information stored in the profile's
|
| 948 |
+
manufacturer tag.
|
| 949 |
+
|
| 950 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 951 |
+
filename of an ICC profile.
|
| 952 |
+
:returns: A string containing the internal profile information stored in
|
| 953 |
+
an ICC tag.
|
| 954 |
+
:exception PyCMSError:
|
| 955 |
+
"""
|
| 956 |
+
try:
|
| 957 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 958 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 959 |
+
profile = ImageCmsProfile(profile)
|
| 960 |
+
return (profile.profile.manufacturer or "") + "\n"
|
| 961 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 962 |
+
raise PyCMSError(v) from v
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def getProfileModel(profile: _CmsProfileCompatible) -> str:
|
| 966 |
+
"""
|
| 967 |
+
(pyCMS) Gets the model for the given profile.
|
| 968 |
+
|
| 969 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 970 |
+
:exc:`PyCMSError` is raised.
|
| 971 |
+
|
| 972 |
+
If an error occurs while trying to obtain the model tag,
|
| 973 |
+
a :exc:`PyCMSError` is raised.
|
| 974 |
+
|
| 975 |
+
Use this function to obtain the information stored in the profile's
|
| 976 |
+
model tag.
|
| 977 |
+
|
| 978 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 979 |
+
filename of an ICC profile.
|
| 980 |
+
:returns: A string containing the internal profile information stored in
|
| 981 |
+
an ICC tag.
|
| 982 |
+
:exception PyCMSError:
|
| 983 |
+
"""
|
| 984 |
+
|
| 985 |
+
try:
|
| 986 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 987 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 988 |
+
profile = ImageCmsProfile(profile)
|
| 989 |
+
return (profile.profile.model or "") + "\n"
|
| 990 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 991 |
+
raise PyCMSError(v) from v
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
def getProfileDescription(profile: _CmsProfileCompatible) -> str:
|
| 995 |
+
"""
|
| 996 |
+
(pyCMS) Gets the description for the given profile.
|
| 997 |
+
|
| 998 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 999 |
+
:exc:`PyCMSError` is raised.
|
| 1000 |
+
|
| 1001 |
+
If an error occurs while trying to obtain the description tag,
|
| 1002 |
+
a :exc:`PyCMSError` is raised.
|
| 1003 |
+
|
| 1004 |
+
Use this function to obtain the information stored in the profile's
|
| 1005 |
+
description tag.
|
| 1006 |
+
|
| 1007 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1008 |
+
filename of an ICC profile.
|
| 1009 |
+
:returns: A string containing the internal profile information stored in an
|
| 1010 |
+
ICC tag.
|
| 1011 |
+
:exception PyCMSError:
|
| 1012 |
+
"""
|
| 1013 |
+
|
| 1014 |
+
try:
|
| 1015 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 1016 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1017 |
+
profile = ImageCmsProfile(profile)
|
| 1018 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 1019 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1020 |
+
raise PyCMSError(v) from v
|
| 1021 |
+
|
| 1022 |
+
|
| 1023 |
+
def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
|
| 1024 |
+
"""
|
| 1025 |
+
(pyCMS) Gets the default intent name for the given profile.
|
| 1026 |
+
|
| 1027 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 1028 |
+
:exc:`PyCMSError` is raised.
|
| 1029 |
+
|
| 1030 |
+
If an error occurs while trying to obtain the default intent, a
|
| 1031 |
+
:exc:`PyCMSError` is raised.
|
| 1032 |
+
|
| 1033 |
+
Use this function to determine the default (and usually best optimized)
|
| 1034 |
+
rendering intent for this profile. Most profiles support multiple
|
| 1035 |
+
rendering intents, but are intended mostly for one type of conversion.
|
| 1036 |
+
If you wish to use a different intent than returned, use
|
| 1037 |
+
ImageCms.isIntentSupported() to verify it will work first.
|
| 1038 |
+
|
| 1039 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1040 |
+
filename of an ICC profile.
|
| 1041 |
+
:returns: Integer 0-3 specifying the default rendering intent for this
|
| 1042 |
+
profile.
|
| 1043 |
+
|
| 1044 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1045 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1046 |
+
ImageCms.Intent.SATURATION = 2
|
| 1047 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1048 |
+
|
| 1049 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1050 |
+
they do.
|
| 1051 |
+
:exception PyCMSError:
|
| 1052 |
+
"""
|
| 1053 |
+
|
| 1054 |
+
try:
|
| 1055 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1056 |
+
profile = ImageCmsProfile(profile)
|
| 1057 |
+
return profile.profile.rendering_intent
|
| 1058 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1059 |
+
raise PyCMSError(v) from v
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
def isIntentSupported(
|
| 1063 |
+
profile: _CmsProfileCompatible, intent: Intent, direction: Direction
|
| 1064 |
+
) -> Literal[-1, 1]:
|
| 1065 |
+
"""
|
| 1066 |
+
(pyCMS) Checks if a given intent is supported.
|
| 1067 |
+
|
| 1068 |
+
Use this function to verify that you can use your desired
|
| 1069 |
+
``intent`` with ``profile``, and that ``profile`` can be used for the
|
| 1070 |
+
input/output/proof profile as you desire.
|
| 1071 |
+
|
| 1072 |
+
Some profiles are created specifically for one "direction", can cannot
|
| 1073 |
+
be used for others. Some profiles can only be used for certain
|
| 1074 |
+
rendering intents, so it's best to either verify this before trying
|
| 1075 |
+
to create a transform with them (using this function), or catch the
|
| 1076 |
+
potential :exc:`PyCMSError` that will occur if they don't
|
| 1077 |
+
support the modes you select.
|
| 1078 |
+
|
| 1079 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1080 |
+
filename of an ICC profile.
|
| 1081 |
+
:param intent: Integer (0-3) specifying the rendering intent you wish to
|
| 1082 |
+
use with this profile
|
| 1083 |
+
|
| 1084 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1085 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1086 |
+
ImageCms.Intent.SATURATION = 2
|
| 1087 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1088 |
+
|
| 1089 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1090 |
+
they do.
|
| 1091 |
+
:param direction: Integer specifying if the profile is to be used for
|
| 1092 |
+
input, output, or proof
|
| 1093 |
+
|
| 1094 |
+
INPUT = 0 (or use ImageCms.Direction.INPUT)
|
| 1095 |
+
OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
|
| 1096 |
+
PROOF = 2 (or use ImageCms.Direction.PROOF)
|
| 1097 |
+
|
| 1098 |
+
:returns: 1 if the intent/direction are supported, -1 if they are not.
|
| 1099 |
+
:exception PyCMSError:
|
| 1100 |
+
"""
|
| 1101 |
+
|
| 1102 |
+
try:
|
| 1103 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1104 |
+
profile = ImageCmsProfile(profile)
|
| 1105 |
+
# FIXME: I get different results for the same data w. different
|
| 1106 |
+
# compilers. Bug in LittleCMS or in the binding?
|
| 1107 |
+
if profile.profile.is_intent_supported(intent, direction):
|
| 1108 |
+
return 1
|
| 1109 |
+
else:
|
| 1110 |
+
return -1
|
| 1111 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1112 |
+
raise PyCMSError(v) from v
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
def versions() -> tuple[str, str | None, str, str]:
|
| 1116 |
+
"""
|
| 1117 |
+
(pyCMS) Fetches versions.
|
| 1118 |
+
"""
|
| 1119 |
+
|
| 1120 |
+
deprecate(
|
| 1121 |
+
"PIL.ImageCms.versions()",
|
| 1122 |
+
12,
|
| 1123 |
+
'(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
|
| 1124 |
+
)
|
| 1125 |
+
return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
|
lib/python3.10/site-packages/PIL/ImageColor.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# map CSS3-style colour description strings to RGB
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2002-10-24 fl Added support for CSS-style color strings
|
| 9 |
+
# 2002-12-15 fl Added RGBA support
|
| 10 |
+
# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
|
| 11 |
+
# 2004-07-19 fl Fixed gray/grey spelling issues
|
| 12 |
+
# 2009-03-05 fl Fixed rounding error in grayscale calculation
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) 2002-2004 by Secret Labs AB
|
| 15 |
+
# Copyright (c) 2002-2004 by Fredrik Lundh
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import re
|
| 22 |
+
from functools import lru_cache
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@lru_cache
|
| 28 |
+
def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
|
| 29 |
+
"""
|
| 30 |
+
Convert a color string to an RGB or RGBA tuple. If the string cannot be
|
| 31 |
+
parsed, this function raises a :py:exc:`ValueError` exception.
|
| 32 |
+
|
| 33 |
+
.. versionadded:: 1.1.4
|
| 34 |
+
|
| 35 |
+
:param color: A color string
|
| 36 |
+
:return: ``(red, green, blue[, alpha])``
|
| 37 |
+
"""
|
| 38 |
+
if len(color) > 100:
|
| 39 |
+
msg = "color specifier is too long"
|
| 40 |
+
raise ValueError(msg)
|
| 41 |
+
color = color.lower()
|
| 42 |
+
|
| 43 |
+
rgb = colormap.get(color, None)
|
| 44 |
+
if rgb:
|
| 45 |
+
if isinstance(rgb, tuple):
|
| 46 |
+
return rgb
|
| 47 |
+
rgb_tuple = getrgb(rgb)
|
| 48 |
+
assert len(rgb_tuple) == 3
|
| 49 |
+
colormap[color] = rgb_tuple
|
| 50 |
+
return rgb_tuple
|
| 51 |
+
|
| 52 |
+
# check for known string formats
|
| 53 |
+
if re.match("#[a-f0-9]{3}$", color):
|
| 54 |
+
return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
|
| 55 |
+
|
| 56 |
+
if re.match("#[a-f0-9]{4}$", color):
|
| 57 |
+
return (
|
| 58 |
+
int(color[1] * 2, 16),
|
| 59 |
+
int(color[2] * 2, 16),
|
| 60 |
+
int(color[3] * 2, 16),
|
| 61 |
+
int(color[4] * 2, 16),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
if re.match("#[a-f0-9]{6}$", color):
|
| 65 |
+
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
|
| 66 |
+
|
| 67 |
+
if re.match("#[a-f0-9]{8}$", color):
|
| 68 |
+
return (
|
| 69 |
+
int(color[1:3], 16),
|
| 70 |
+
int(color[3:5], 16),
|
| 71 |
+
int(color[5:7], 16),
|
| 72 |
+
int(color[7:9], 16),
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
| 76 |
+
if m:
|
| 77 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3))
|
| 78 |
+
|
| 79 |
+
m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
|
| 80 |
+
if m:
|
| 81 |
+
return (
|
| 82 |
+
int((int(m.group(1)) * 255) / 100.0 + 0.5),
|
| 83 |
+
int((int(m.group(2)) * 255) / 100.0 + 0.5),
|
| 84 |
+
int((int(m.group(3)) * 255) / 100.0 + 0.5),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
m = re.match(
|
| 88 |
+
r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
| 89 |
+
)
|
| 90 |
+
if m:
|
| 91 |
+
from colorsys import hls_to_rgb
|
| 92 |
+
|
| 93 |
+
rgb_floats = hls_to_rgb(
|
| 94 |
+
float(m.group(1)) / 360.0,
|
| 95 |
+
float(m.group(3)) / 100.0,
|
| 96 |
+
float(m.group(2)) / 100.0,
|
| 97 |
+
)
|
| 98 |
+
return (
|
| 99 |
+
int(rgb_floats[0] * 255 + 0.5),
|
| 100 |
+
int(rgb_floats[1] * 255 + 0.5),
|
| 101 |
+
int(rgb_floats[2] * 255 + 0.5),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
m = re.match(
|
| 105 |
+
r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
| 106 |
+
)
|
| 107 |
+
if m:
|
| 108 |
+
from colorsys import hsv_to_rgb
|
| 109 |
+
|
| 110 |
+
rgb_floats = hsv_to_rgb(
|
| 111 |
+
float(m.group(1)) / 360.0,
|
| 112 |
+
float(m.group(2)) / 100.0,
|
| 113 |
+
float(m.group(3)) / 100.0,
|
| 114 |
+
)
|
| 115 |
+
return (
|
| 116 |
+
int(rgb_floats[0] * 255 + 0.5),
|
| 117 |
+
int(rgb_floats[1] * 255 + 0.5),
|
| 118 |
+
int(rgb_floats[2] * 255 + 0.5),
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
| 122 |
+
if m:
|
| 123 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
|
| 124 |
+
msg = f"unknown color specifier: {repr(color)}"
|
| 125 |
+
raise ValueError(msg)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@lru_cache
|
| 129 |
+
def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
|
| 130 |
+
"""
|
| 131 |
+
Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
|
| 132 |
+
``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
|
| 133 |
+
not color or a palette image, converts the RGB value to a grayscale value.
|
| 134 |
+
If the string cannot be parsed, this function raises a :py:exc:`ValueError`
|
| 135 |
+
exception.
|
| 136 |
+
|
| 137 |
+
.. versionadded:: 1.1.4
|
| 138 |
+
|
| 139 |
+
:param color: A color string
|
| 140 |
+
:param mode: Convert result to this mode
|
| 141 |
+
:return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
|
| 142 |
+
"""
|
| 143 |
+
# same as getrgb, but converts the result to the given mode
|
| 144 |
+
rgb, alpha = getrgb(color), 255
|
| 145 |
+
if len(rgb) == 4:
|
| 146 |
+
alpha = rgb[3]
|
| 147 |
+
rgb = rgb[:3]
|
| 148 |
+
|
| 149 |
+
if mode == "HSV":
|
| 150 |
+
from colorsys import rgb_to_hsv
|
| 151 |
+
|
| 152 |
+
r, g, b = rgb
|
| 153 |
+
h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
|
| 154 |
+
return int(h * 255), int(s * 255), int(v * 255)
|
| 155 |
+
elif Image.getmodebase(mode) == "L":
|
| 156 |
+
r, g, b = rgb
|
| 157 |
+
# ITU-R Recommendation 601-2 for nonlinear RGB
|
| 158 |
+
# scaled to 24 bits to match the convert's implementation.
|
| 159 |
+
graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
|
| 160 |
+
if mode[-1] == "A":
|
| 161 |
+
return graylevel, alpha
|
| 162 |
+
return graylevel
|
| 163 |
+
elif mode[-1] == "A":
|
| 164 |
+
return rgb + (alpha,)
|
| 165 |
+
return rgb
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
colormap: dict[str, str | tuple[int, int, int]] = {
|
| 169 |
+
# X11 colour table from https://drafts.csswg.org/css-color-4/, with
|
| 170 |
+
# gray/grey spelling issues fixed. This is a superset of HTML 4.0
|
| 171 |
+
# colour names used in CSS 1.
|
| 172 |
+
"aliceblue": "#f0f8ff",
|
| 173 |
+
"antiquewhite": "#faebd7",
|
| 174 |
+
"aqua": "#00ffff",
|
| 175 |
+
"aquamarine": "#7fffd4",
|
| 176 |
+
"azure": "#f0ffff",
|
| 177 |
+
"beige": "#f5f5dc",
|
| 178 |
+
"bisque": "#ffe4c4",
|
| 179 |
+
"black": "#000000",
|
| 180 |
+
"blanchedalmond": "#ffebcd",
|
| 181 |
+
"blue": "#0000ff",
|
| 182 |
+
"blueviolet": "#8a2be2",
|
| 183 |
+
"brown": "#a52a2a",
|
| 184 |
+
"burlywood": "#deb887",
|
| 185 |
+
"cadetblue": "#5f9ea0",
|
| 186 |
+
"chartreuse": "#7fff00",
|
| 187 |
+
"chocolate": "#d2691e",
|
| 188 |
+
"coral": "#ff7f50",
|
| 189 |
+
"cornflowerblue": "#6495ed",
|
| 190 |
+
"cornsilk": "#fff8dc",
|
| 191 |
+
"crimson": "#dc143c",
|
| 192 |
+
"cyan": "#00ffff",
|
| 193 |
+
"darkblue": "#00008b",
|
| 194 |
+
"darkcyan": "#008b8b",
|
| 195 |
+
"darkgoldenrod": "#b8860b",
|
| 196 |
+
"darkgray": "#a9a9a9",
|
| 197 |
+
"darkgrey": "#a9a9a9",
|
| 198 |
+
"darkgreen": "#006400",
|
| 199 |
+
"darkkhaki": "#bdb76b",
|
| 200 |
+
"darkmagenta": "#8b008b",
|
| 201 |
+
"darkolivegreen": "#556b2f",
|
| 202 |
+
"darkorange": "#ff8c00",
|
| 203 |
+
"darkorchid": "#9932cc",
|
| 204 |
+
"darkred": "#8b0000",
|
| 205 |
+
"darksalmon": "#e9967a",
|
| 206 |
+
"darkseagreen": "#8fbc8f",
|
| 207 |
+
"darkslateblue": "#483d8b",
|
| 208 |
+
"darkslategray": "#2f4f4f",
|
| 209 |
+
"darkslategrey": "#2f4f4f",
|
| 210 |
+
"darkturquoise": "#00ced1",
|
| 211 |
+
"darkviolet": "#9400d3",
|
| 212 |
+
"deeppink": "#ff1493",
|
| 213 |
+
"deepskyblue": "#00bfff",
|
| 214 |
+
"dimgray": "#696969",
|
| 215 |
+
"dimgrey": "#696969",
|
| 216 |
+
"dodgerblue": "#1e90ff",
|
| 217 |
+
"firebrick": "#b22222",
|
| 218 |
+
"floralwhite": "#fffaf0",
|
| 219 |
+
"forestgreen": "#228b22",
|
| 220 |
+
"fuchsia": "#ff00ff",
|
| 221 |
+
"gainsboro": "#dcdcdc",
|
| 222 |
+
"ghostwhite": "#f8f8ff",
|
| 223 |
+
"gold": "#ffd700",
|
| 224 |
+
"goldenrod": "#daa520",
|
| 225 |
+
"gray": "#808080",
|
| 226 |
+
"grey": "#808080",
|
| 227 |
+
"green": "#008000",
|
| 228 |
+
"greenyellow": "#adff2f",
|
| 229 |
+
"honeydew": "#f0fff0",
|
| 230 |
+
"hotpink": "#ff69b4",
|
| 231 |
+
"indianred": "#cd5c5c",
|
| 232 |
+
"indigo": "#4b0082",
|
| 233 |
+
"ivory": "#fffff0",
|
| 234 |
+
"khaki": "#f0e68c",
|
| 235 |
+
"lavender": "#e6e6fa",
|
| 236 |
+
"lavenderblush": "#fff0f5",
|
| 237 |
+
"lawngreen": "#7cfc00",
|
| 238 |
+
"lemonchiffon": "#fffacd",
|
| 239 |
+
"lightblue": "#add8e6",
|
| 240 |
+
"lightcoral": "#f08080",
|
| 241 |
+
"lightcyan": "#e0ffff",
|
| 242 |
+
"lightgoldenrodyellow": "#fafad2",
|
| 243 |
+
"lightgreen": "#90ee90",
|
| 244 |
+
"lightgray": "#d3d3d3",
|
| 245 |
+
"lightgrey": "#d3d3d3",
|
| 246 |
+
"lightpink": "#ffb6c1",
|
| 247 |
+
"lightsalmon": "#ffa07a",
|
| 248 |
+
"lightseagreen": "#20b2aa",
|
| 249 |
+
"lightskyblue": "#87cefa",
|
| 250 |
+
"lightslategray": "#778899",
|
| 251 |
+
"lightslategrey": "#778899",
|
| 252 |
+
"lightsteelblue": "#b0c4de",
|
| 253 |
+
"lightyellow": "#ffffe0",
|
| 254 |
+
"lime": "#00ff00",
|
| 255 |
+
"limegreen": "#32cd32",
|
| 256 |
+
"linen": "#faf0e6",
|
| 257 |
+
"magenta": "#ff00ff",
|
| 258 |
+
"maroon": "#800000",
|
| 259 |
+
"mediumaquamarine": "#66cdaa",
|
| 260 |
+
"mediumblue": "#0000cd",
|
| 261 |
+
"mediumorchid": "#ba55d3",
|
| 262 |
+
"mediumpurple": "#9370db",
|
| 263 |
+
"mediumseagreen": "#3cb371",
|
| 264 |
+
"mediumslateblue": "#7b68ee",
|
| 265 |
+
"mediumspringgreen": "#00fa9a",
|
| 266 |
+
"mediumturquoise": "#48d1cc",
|
| 267 |
+
"mediumvioletred": "#c71585",
|
| 268 |
+
"midnightblue": "#191970",
|
| 269 |
+
"mintcream": "#f5fffa",
|
| 270 |
+
"mistyrose": "#ffe4e1",
|
| 271 |
+
"moccasin": "#ffe4b5",
|
| 272 |
+
"navajowhite": "#ffdead",
|
| 273 |
+
"navy": "#000080",
|
| 274 |
+
"oldlace": "#fdf5e6",
|
| 275 |
+
"olive": "#808000",
|
| 276 |
+
"olivedrab": "#6b8e23",
|
| 277 |
+
"orange": "#ffa500",
|
| 278 |
+
"orangered": "#ff4500",
|
| 279 |
+
"orchid": "#da70d6",
|
| 280 |
+
"palegoldenrod": "#eee8aa",
|
| 281 |
+
"palegreen": "#98fb98",
|
| 282 |
+
"paleturquoise": "#afeeee",
|
| 283 |
+
"palevioletred": "#db7093",
|
| 284 |
+
"papayawhip": "#ffefd5",
|
| 285 |
+
"peachpuff": "#ffdab9",
|
| 286 |
+
"peru": "#cd853f",
|
| 287 |
+
"pink": "#ffc0cb",
|
| 288 |
+
"plum": "#dda0dd",
|
| 289 |
+
"powderblue": "#b0e0e6",
|
| 290 |
+
"purple": "#800080",
|
| 291 |
+
"rebeccapurple": "#663399",
|
| 292 |
+
"red": "#ff0000",
|
| 293 |
+
"rosybrown": "#bc8f8f",
|
| 294 |
+
"royalblue": "#4169e1",
|
| 295 |
+
"saddlebrown": "#8b4513",
|
| 296 |
+
"salmon": "#fa8072",
|
| 297 |
+
"sandybrown": "#f4a460",
|
| 298 |
+
"seagreen": "#2e8b57",
|
| 299 |
+
"seashell": "#fff5ee",
|
| 300 |
+
"sienna": "#a0522d",
|
| 301 |
+
"silver": "#c0c0c0",
|
| 302 |
+
"skyblue": "#87ceeb",
|
| 303 |
+
"slateblue": "#6a5acd",
|
| 304 |
+
"slategray": "#708090",
|
| 305 |
+
"slategrey": "#708090",
|
| 306 |
+
"snow": "#fffafa",
|
| 307 |
+
"springgreen": "#00ff7f",
|
| 308 |
+
"steelblue": "#4682b4",
|
| 309 |
+
"tan": "#d2b48c",
|
| 310 |
+
"teal": "#008080",
|
| 311 |
+
"thistle": "#d8bfd8",
|
| 312 |
+
"tomato": "#ff6347",
|
| 313 |
+
"turquoise": "#40e0d0",
|
| 314 |
+
"violet": "#ee82ee",
|
| 315 |
+
"wheat": "#f5deb3",
|
| 316 |
+
"white": "#ffffff",
|
| 317 |
+
"whitesmoke": "#f5f5f5",
|
| 318 |
+
"yellow": "#ffff00",
|
| 319 |
+
"yellowgreen": "#9acd32",
|
| 320 |
+
}
|
lib/python3.10/site-packages/PIL/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# drawing interface operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-13 fl Created (experimental)
|
| 9 |
+
# 1996-08-07 fl Filled polygons, ellipses.
|
| 10 |
+
# 1996-08-13 fl Added text support
|
| 11 |
+
# 1998-06-28 fl Handle I and F images
|
| 12 |
+
# 1998-12-29 fl Added arc; use arc primitive to draw ellipses
|
| 13 |
+
# 1999-01-10 fl Added shape stuff (experimental)
|
| 14 |
+
# 1999-02-06 fl Added bitmap support
|
| 15 |
+
# 1999-02-11 fl Changed all primitives to take options
|
| 16 |
+
# 1999-02-20 fl Fixed backwards compatibility
|
| 17 |
+
# 2000-10-12 fl Copy on write, when necessary
|
| 18 |
+
# 2001-02-18 fl Use default ink for bitmap/text also in fill mode
|
| 19 |
+
# 2002-10-24 fl Added support for CSS-style color strings
|
| 20 |
+
# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
|
| 21 |
+
# 2002-12-11 fl Refactored low-level drawing API (work in progress)
|
| 22 |
+
# 2004-08-26 fl Made Draw() a factory function, added getdraw() support
|
| 23 |
+
# 2004-09-04 fl Added width support to line primitive
|
| 24 |
+
# 2004-09-10 fl Added font mode handling
|
| 25 |
+
# 2006-06-19 fl Added font bearing support (getmask2)
|
| 26 |
+
#
|
| 27 |
+
# Copyright (c) 1997-2006 by Secret Labs AB
|
| 28 |
+
# Copyright (c) 1996-2006 by Fredrik Lundh
|
| 29 |
+
#
|
| 30 |
+
# See the README file for information on usage and redistribution.
|
| 31 |
+
#
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import math
|
| 35 |
+
import struct
|
| 36 |
+
from collections.abc import Sequence
|
| 37 |
+
from types import ModuleType
|
| 38 |
+
from typing import TYPE_CHECKING, Any, AnyStr, Callable, Union, cast
|
| 39 |
+
|
| 40 |
+
from . import Image, ImageColor
|
| 41 |
+
from ._deprecate import deprecate
|
| 42 |
+
from ._typing import Coords
|
| 43 |
+
|
| 44 |
+
# experimental access to the outline API
|
| 45 |
+
Outline: Callable[[], Image.core._Outline] | None
|
| 46 |
+
try:
|
| 47 |
+
Outline = Image.core.outline
|
| 48 |
+
except AttributeError:
|
| 49 |
+
Outline = None
|
| 50 |
+
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
from . import ImageDraw2, ImageFont
|
| 53 |
+
|
| 54 |
+
_Ink = Union[float, tuple[int, ...], str]
|
| 55 |
+
|
| 56 |
+
"""
|
| 57 |
+
A simple 2D drawing interface for PIL images.
|
| 58 |
+
<p>
|
| 59 |
+
Application code should use the <b>Draw</b> factory, instead of
|
| 60 |
+
directly.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ImageDraw:
|
| 65 |
+
font: (
|
| 66 |
+
ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
|
| 67 |
+
) = None
|
| 68 |
+
|
| 69 |
+
def __init__(self, im: Image.Image, mode: str | None = None) -> None:
|
| 70 |
+
"""
|
| 71 |
+
Create a drawing instance.
|
| 72 |
+
|
| 73 |
+
:param im: The image to draw in.
|
| 74 |
+
:param mode: Optional mode to use for color values. For RGB
|
| 75 |
+
images, this argument can be RGB or RGBA (to blend the
|
| 76 |
+
drawing into the image). For all other modes, this argument
|
| 77 |
+
must be the same as the image mode. If omitted, the mode
|
| 78 |
+
defaults to the mode of the image.
|
| 79 |
+
"""
|
| 80 |
+
im.load()
|
| 81 |
+
if im.readonly:
|
| 82 |
+
im._copy() # make it writeable
|
| 83 |
+
blend = 0
|
| 84 |
+
if mode is None:
|
| 85 |
+
mode = im.mode
|
| 86 |
+
if mode != im.mode:
|
| 87 |
+
if mode == "RGBA" and im.mode == "RGB":
|
| 88 |
+
blend = 1
|
| 89 |
+
else:
|
| 90 |
+
msg = "mode mismatch"
|
| 91 |
+
raise ValueError(msg)
|
| 92 |
+
if mode == "P":
|
| 93 |
+
self.palette = im.palette
|
| 94 |
+
else:
|
| 95 |
+
self.palette = None
|
| 96 |
+
self._image = im
|
| 97 |
+
self.im = im.im
|
| 98 |
+
self.draw = Image.core.draw(self.im, blend)
|
| 99 |
+
self.mode = mode
|
| 100 |
+
if mode in ("I", "F"):
|
| 101 |
+
self.ink = self.draw.draw_ink(1)
|
| 102 |
+
else:
|
| 103 |
+
self.ink = self.draw.draw_ink(-1)
|
| 104 |
+
if mode in ("1", "P", "I", "F"):
|
| 105 |
+
# FIXME: fix Fill2 to properly support matte for I+F images
|
| 106 |
+
self.fontmode = "1"
|
| 107 |
+
else:
|
| 108 |
+
self.fontmode = "L" # aliasing is okay for other modes
|
| 109 |
+
self.fill = False
|
| 110 |
+
|
| 111 |
+
def getfont(
|
| 112 |
+
self,
|
| 113 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
| 114 |
+
"""
|
| 115 |
+
Get the current default font.
|
| 116 |
+
|
| 117 |
+
To set the default font for this ImageDraw instance::
|
| 118 |
+
|
| 119 |
+
from PIL import ImageDraw, ImageFont
|
| 120 |
+
draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
| 121 |
+
|
| 122 |
+
To set the default font for all future ImageDraw instances::
|
| 123 |
+
|
| 124 |
+
from PIL import ImageDraw, ImageFont
|
| 125 |
+
ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
|
| 126 |
+
|
| 127 |
+
If the current default font is ``None``,
|
| 128 |
+
it is initialized with ``ImageFont.load_default()``.
|
| 129 |
+
|
| 130 |
+
:returns: An image font."""
|
| 131 |
+
if not self.font:
|
| 132 |
+
# FIXME: should add a font repository
|
| 133 |
+
from . import ImageFont
|
| 134 |
+
|
| 135 |
+
self.font = ImageFont.load_default()
|
| 136 |
+
return self.font
|
| 137 |
+
|
| 138 |
+
def _getfont(
|
| 139 |
+
self, font_size: float | None
|
| 140 |
+
) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
|
| 141 |
+
if font_size is not None:
|
| 142 |
+
from . import ImageFont
|
| 143 |
+
|
| 144 |
+
return ImageFont.load_default(font_size)
|
| 145 |
+
else:
|
| 146 |
+
return self.getfont()
|
| 147 |
+
|
| 148 |
+
def _getink(
|
| 149 |
+
self, ink: _Ink | None, fill: _Ink | None = None
|
| 150 |
+
) -> tuple[int | None, int | None]:
|
| 151 |
+
result_ink = None
|
| 152 |
+
result_fill = None
|
| 153 |
+
if ink is None and fill is None:
|
| 154 |
+
if self.fill:
|
| 155 |
+
result_fill = self.ink
|
| 156 |
+
else:
|
| 157 |
+
result_ink = self.ink
|
| 158 |
+
else:
|
| 159 |
+
if ink is not None:
|
| 160 |
+
if isinstance(ink, str):
|
| 161 |
+
ink = ImageColor.getcolor(ink, self.mode)
|
| 162 |
+
if self.palette and isinstance(ink, tuple):
|
| 163 |
+
ink = self.palette.getcolor(ink, self._image)
|
| 164 |
+
result_ink = self.draw.draw_ink(ink)
|
| 165 |
+
if fill is not None:
|
| 166 |
+
if isinstance(fill, str):
|
| 167 |
+
fill = ImageColor.getcolor(fill, self.mode)
|
| 168 |
+
if self.palette and isinstance(fill, tuple):
|
| 169 |
+
fill = self.palette.getcolor(fill, self._image)
|
| 170 |
+
result_fill = self.draw.draw_ink(fill)
|
| 171 |
+
return result_ink, result_fill
|
| 172 |
+
|
| 173 |
+
def arc(
|
| 174 |
+
self,
|
| 175 |
+
xy: Coords,
|
| 176 |
+
start: float,
|
| 177 |
+
end: float,
|
| 178 |
+
fill: _Ink | None = None,
|
| 179 |
+
width: int = 1,
|
| 180 |
+
) -> None:
|
| 181 |
+
"""Draw an arc."""
|
| 182 |
+
ink, fill = self._getink(fill)
|
| 183 |
+
if ink is not None:
|
| 184 |
+
self.draw.draw_arc(xy, start, end, ink, width)
|
| 185 |
+
|
| 186 |
+
def bitmap(
|
| 187 |
+
self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
|
| 188 |
+
) -> None:
|
| 189 |
+
"""Draw a bitmap."""
|
| 190 |
+
bitmap.load()
|
| 191 |
+
ink, fill = self._getink(fill)
|
| 192 |
+
if ink is None:
|
| 193 |
+
ink = fill
|
| 194 |
+
if ink is not None:
|
| 195 |
+
self.draw.draw_bitmap(xy, bitmap.im, ink)
|
| 196 |
+
|
| 197 |
+
def chord(
|
| 198 |
+
self,
|
| 199 |
+
xy: Coords,
|
| 200 |
+
start: float,
|
| 201 |
+
end: float,
|
| 202 |
+
fill: _Ink | None = None,
|
| 203 |
+
outline: _Ink | None = None,
|
| 204 |
+
width: int = 1,
|
| 205 |
+
) -> None:
|
| 206 |
+
"""Draw a chord."""
|
| 207 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 208 |
+
if fill_ink is not None:
|
| 209 |
+
self.draw.draw_chord(xy, start, end, fill_ink, 1)
|
| 210 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 211 |
+
self.draw.draw_chord(xy, start, end, ink, 0, width)
|
| 212 |
+
|
| 213 |
+
def ellipse(
|
| 214 |
+
self,
|
| 215 |
+
xy: Coords,
|
| 216 |
+
fill: _Ink | None = None,
|
| 217 |
+
outline: _Ink | None = None,
|
| 218 |
+
width: int = 1,
|
| 219 |
+
) -> None:
|
| 220 |
+
"""Draw an ellipse."""
|
| 221 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 222 |
+
if fill_ink is not None:
|
| 223 |
+
self.draw.draw_ellipse(xy, fill_ink, 1)
|
| 224 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 225 |
+
self.draw.draw_ellipse(xy, ink, 0, width)
|
| 226 |
+
|
| 227 |
+
def circle(
|
| 228 |
+
self,
|
| 229 |
+
xy: Sequence[float],
|
| 230 |
+
radius: float,
|
| 231 |
+
fill: _Ink | None = None,
|
| 232 |
+
outline: _Ink | None = None,
|
| 233 |
+
width: int = 1,
|
| 234 |
+
) -> None:
|
| 235 |
+
"""Draw a circle given center coordinates and a radius."""
|
| 236 |
+
ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
|
| 237 |
+
self.ellipse(ellipse_xy, fill, outline, width)
|
| 238 |
+
|
| 239 |
+
def line(
|
| 240 |
+
self,
|
| 241 |
+
xy: Coords,
|
| 242 |
+
fill: _Ink | None = None,
|
| 243 |
+
width: int = 0,
|
| 244 |
+
joint: str | None = None,
|
| 245 |
+
) -> None:
|
| 246 |
+
"""Draw a line, or a connected sequence of line segments."""
|
| 247 |
+
ink = self._getink(fill)[0]
|
| 248 |
+
if ink is not None:
|
| 249 |
+
self.draw.draw_lines(xy, ink, width)
|
| 250 |
+
if joint == "curve" and width > 4:
|
| 251 |
+
points: Sequence[Sequence[float]]
|
| 252 |
+
if isinstance(xy[0], (list, tuple)):
|
| 253 |
+
points = cast(Sequence[Sequence[float]], xy)
|
| 254 |
+
else:
|
| 255 |
+
points = [
|
| 256 |
+
cast(Sequence[float], tuple(xy[i : i + 2]))
|
| 257 |
+
for i in range(0, len(xy), 2)
|
| 258 |
+
]
|
| 259 |
+
for i in range(1, len(points) - 1):
|
| 260 |
+
point = points[i]
|
| 261 |
+
angles = [
|
| 262 |
+
math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
|
| 263 |
+
% 360
|
| 264 |
+
for start, end in (
|
| 265 |
+
(points[i - 1], point),
|
| 266 |
+
(point, points[i + 1]),
|
| 267 |
+
)
|
| 268 |
+
]
|
| 269 |
+
if angles[0] == angles[1]:
|
| 270 |
+
# This is a straight line, so no joint is required
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
def coord_at_angle(
|
| 274 |
+
coord: Sequence[float], angle: float
|
| 275 |
+
) -> tuple[float, ...]:
|
| 276 |
+
x, y = coord
|
| 277 |
+
angle -= 90
|
| 278 |
+
distance = width / 2 - 1
|
| 279 |
+
return tuple(
|
| 280 |
+
p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
|
| 281 |
+
for p, p_d in (
|
| 282 |
+
(x, distance * math.cos(math.radians(angle))),
|
| 283 |
+
(y, distance * math.sin(math.radians(angle))),
|
| 284 |
+
)
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
flipped = (
|
| 288 |
+
angles[1] > angles[0] and angles[1] - 180 > angles[0]
|
| 289 |
+
) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
|
| 290 |
+
coords = [
|
| 291 |
+
(point[0] - width / 2 + 1, point[1] - width / 2 + 1),
|
| 292 |
+
(point[0] + width / 2 - 1, point[1] + width / 2 - 1),
|
| 293 |
+
]
|
| 294 |
+
if flipped:
|
| 295 |
+
start, end = (angles[1] + 90, angles[0] + 90)
|
| 296 |
+
else:
|
| 297 |
+
start, end = (angles[0] - 90, angles[1] - 90)
|
| 298 |
+
self.pieslice(coords, start - 90, end - 90, fill)
|
| 299 |
+
|
| 300 |
+
if width > 8:
|
| 301 |
+
# Cover potential gaps between the line and the joint
|
| 302 |
+
if flipped:
|
| 303 |
+
gap_coords = [
|
| 304 |
+
coord_at_angle(point, angles[0] + 90),
|
| 305 |
+
point,
|
| 306 |
+
coord_at_angle(point, angles[1] + 90),
|
| 307 |
+
]
|
| 308 |
+
else:
|
| 309 |
+
gap_coords = [
|
| 310 |
+
coord_at_angle(point, angles[0] - 90),
|
| 311 |
+
point,
|
| 312 |
+
coord_at_angle(point, angles[1] - 90),
|
| 313 |
+
]
|
| 314 |
+
self.line(gap_coords, fill, width=3)
|
| 315 |
+
|
| 316 |
+
def shape(
|
| 317 |
+
self,
|
| 318 |
+
shape: Image.core._Outline,
|
| 319 |
+
fill: _Ink | None = None,
|
| 320 |
+
outline: _Ink | None = None,
|
| 321 |
+
) -> None:
|
| 322 |
+
"""(Experimental) Draw a shape."""
|
| 323 |
+
shape.close()
|
| 324 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 325 |
+
if fill_ink is not None:
|
| 326 |
+
self.draw.draw_outline(shape, fill_ink, 1)
|
| 327 |
+
if ink is not None and ink != fill_ink:
|
| 328 |
+
self.draw.draw_outline(shape, ink, 0)
|
| 329 |
+
|
| 330 |
+
def pieslice(
|
| 331 |
+
self,
|
| 332 |
+
xy: Coords,
|
| 333 |
+
start: float,
|
| 334 |
+
end: float,
|
| 335 |
+
fill: _Ink | None = None,
|
| 336 |
+
outline: _Ink | None = None,
|
| 337 |
+
width: int = 1,
|
| 338 |
+
) -> None:
|
| 339 |
+
"""Draw a pieslice."""
|
| 340 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 341 |
+
if fill_ink is not None:
|
| 342 |
+
self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
|
| 343 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 344 |
+
self.draw.draw_pieslice(xy, start, end, ink, 0, width)
|
| 345 |
+
|
| 346 |
+
def point(self, xy: Coords, fill: _Ink | None = None) -> None:
|
| 347 |
+
"""Draw one or more individual pixels."""
|
| 348 |
+
ink, fill = self._getink(fill)
|
| 349 |
+
if ink is not None:
|
| 350 |
+
self.draw.draw_points(xy, ink)
|
| 351 |
+
|
| 352 |
+
def polygon(
|
| 353 |
+
self,
|
| 354 |
+
xy: Coords,
|
| 355 |
+
fill: _Ink | None = None,
|
| 356 |
+
outline: _Ink | None = None,
|
| 357 |
+
width: int = 1,
|
| 358 |
+
) -> None:
|
| 359 |
+
"""Draw a polygon."""
|
| 360 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 361 |
+
if fill_ink is not None:
|
| 362 |
+
self.draw.draw_polygon(xy, fill_ink, 1)
|
| 363 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 364 |
+
if width == 1:
|
| 365 |
+
self.draw.draw_polygon(xy, ink, 0, width)
|
| 366 |
+
elif self.im is not None:
|
| 367 |
+
# To avoid expanding the polygon outwards,
|
| 368 |
+
# use the fill as a mask
|
| 369 |
+
mask = Image.new("1", self.im.size)
|
| 370 |
+
mask_ink = self._getink(1)[0]
|
| 371 |
+
|
| 372 |
+
fill_im = mask.copy()
|
| 373 |
+
draw = Draw(fill_im)
|
| 374 |
+
draw.draw.draw_polygon(xy, mask_ink, 1)
|
| 375 |
+
|
| 376 |
+
ink_im = mask.copy()
|
| 377 |
+
draw = Draw(ink_im)
|
| 378 |
+
width = width * 2 - 1
|
| 379 |
+
draw.draw.draw_polygon(xy, mask_ink, 0, width)
|
| 380 |
+
|
| 381 |
+
mask.paste(ink_im, mask=fill_im)
|
| 382 |
+
|
| 383 |
+
im = Image.new(self.mode, self.im.size)
|
| 384 |
+
draw = Draw(im)
|
| 385 |
+
draw.draw.draw_polygon(xy, ink, 0, width)
|
| 386 |
+
self.im.paste(im.im, (0, 0) + im.size, mask.im)
|
| 387 |
+
|
| 388 |
+
def regular_polygon(
|
| 389 |
+
self,
|
| 390 |
+
bounding_circle: Sequence[Sequence[float] | float],
|
| 391 |
+
n_sides: int,
|
| 392 |
+
rotation: float = 0,
|
| 393 |
+
fill: _Ink | None = None,
|
| 394 |
+
outline: _Ink | None = None,
|
| 395 |
+
width: int = 1,
|
| 396 |
+
) -> None:
|
| 397 |
+
"""Draw a regular polygon."""
|
| 398 |
+
xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
|
| 399 |
+
self.polygon(xy, fill, outline, width)
|
| 400 |
+
|
| 401 |
+
def rectangle(
|
| 402 |
+
self,
|
| 403 |
+
xy: Coords,
|
| 404 |
+
fill: _Ink | None = None,
|
| 405 |
+
outline: _Ink | None = None,
|
| 406 |
+
width: int = 1,
|
| 407 |
+
) -> None:
|
| 408 |
+
"""Draw a rectangle."""
|
| 409 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 410 |
+
if fill_ink is not None:
|
| 411 |
+
self.draw.draw_rectangle(xy, fill_ink, 1)
|
| 412 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 413 |
+
self.draw.draw_rectangle(xy, ink, 0, width)
|
| 414 |
+
|
| 415 |
+
def rounded_rectangle(
|
| 416 |
+
self,
|
| 417 |
+
xy: Coords,
|
| 418 |
+
radius: float = 0,
|
| 419 |
+
fill: _Ink | None = None,
|
| 420 |
+
outline: _Ink | None = None,
|
| 421 |
+
width: int = 1,
|
| 422 |
+
*,
|
| 423 |
+
corners: tuple[bool, bool, bool, bool] | None = None,
|
| 424 |
+
) -> None:
|
| 425 |
+
"""Draw a rounded rectangle."""
|
| 426 |
+
if isinstance(xy[0], (list, tuple)):
|
| 427 |
+
(x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
|
| 428 |
+
else:
|
| 429 |
+
x0, y0, x1, y1 = cast(Sequence[float], xy)
|
| 430 |
+
if x1 < x0:
|
| 431 |
+
msg = "x1 must be greater than or equal to x0"
|
| 432 |
+
raise ValueError(msg)
|
| 433 |
+
if y1 < y0:
|
| 434 |
+
msg = "y1 must be greater than or equal to y0"
|
| 435 |
+
raise ValueError(msg)
|
| 436 |
+
if corners is None:
|
| 437 |
+
corners = (True, True, True, True)
|
| 438 |
+
|
| 439 |
+
d = radius * 2
|
| 440 |
+
|
| 441 |
+
x0 = round(x0)
|
| 442 |
+
y0 = round(y0)
|
| 443 |
+
x1 = round(x1)
|
| 444 |
+
y1 = round(y1)
|
| 445 |
+
full_x, full_y = False, False
|
| 446 |
+
if all(corners):
|
| 447 |
+
full_x = d >= x1 - x0 - 1
|
| 448 |
+
if full_x:
|
| 449 |
+
# The two left and two right corners are joined
|
| 450 |
+
d = x1 - x0
|
| 451 |
+
full_y = d >= y1 - y0 - 1
|
| 452 |
+
if full_y:
|
| 453 |
+
# The two top and two bottom corners are joined
|
| 454 |
+
d = y1 - y0
|
| 455 |
+
if full_x and full_y:
|
| 456 |
+
# If all corners are joined, that is a circle
|
| 457 |
+
return self.ellipse(xy, fill, outline, width)
|
| 458 |
+
|
| 459 |
+
if d == 0 or not any(corners):
|
| 460 |
+
# If the corners have no curve,
|
| 461 |
+
# or there are no corners,
|
| 462 |
+
# that is a rectangle
|
| 463 |
+
return self.rectangle(xy, fill, outline, width)
|
| 464 |
+
|
| 465 |
+
r = int(d // 2)
|
| 466 |
+
ink, fill_ink = self._getink(outline, fill)
|
| 467 |
+
|
| 468 |
+
def draw_corners(pieslice: bool) -> None:
|
| 469 |
+
parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
|
| 470 |
+
if full_x:
|
| 471 |
+
# Draw top and bottom halves
|
| 472 |
+
parts = (
|
| 473 |
+
((x0, y0, x0 + d, y0 + d), 180, 360),
|
| 474 |
+
((x0, y1 - d, x0 + d, y1), 0, 180),
|
| 475 |
+
)
|
| 476 |
+
elif full_y:
|
| 477 |
+
# Draw left and right halves
|
| 478 |
+
parts = (
|
| 479 |
+
((x0, y0, x0 + d, y0 + d), 90, 270),
|
| 480 |
+
((x1 - d, y0, x1, y0 + d), 270, 90),
|
| 481 |
+
)
|
| 482 |
+
else:
|
| 483 |
+
# Draw four separate corners
|
| 484 |
+
parts = tuple(
|
| 485 |
+
part
|
| 486 |
+
for i, part in enumerate(
|
| 487 |
+
(
|
| 488 |
+
((x0, y0, x0 + d, y0 + d), 180, 270),
|
| 489 |
+
((x1 - d, y0, x1, y0 + d), 270, 360),
|
| 490 |
+
((x1 - d, y1 - d, x1, y1), 0, 90),
|
| 491 |
+
((x0, y1 - d, x0 + d, y1), 90, 180),
|
| 492 |
+
)
|
| 493 |
+
)
|
| 494 |
+
if corners[i]
|
| 495 |
+
)
|
| 496 |
+
for part in parts:
|
| 497 |
+
if pieslice:
|
| 498 |
+
self.draw.draw_pieslice(*(part + (fill_ink, 1)))
|
| 499 |
+
else:
|
| 500 |
+
self.draw.draw_arc(*(part + (ink, width)))
|
| 501 |
+
|
| 502 |
+
if fill_ink is not None:
|
| 503 |
+
draw_corners(True)
|
| 504 |
+
|
| 505 |
+
if full_x:
|
| 506 |
+
self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
|
| 507 |
+
elif x1 - r - 1 > x0 + r + 1:
|
| 508 |
+
self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
|
| 509 |
+
if not full_x and not full_y:
|
| 510 |
+
left = [x0, y0, x0 + r, y1]
|
| 511 |
+
if corners[0]:
|
| 512 |
+
left[1] += r + 1
|
| 513 |
+
if corners[3]:
|
| 514 |
+
left[3] -= r + 1
|
| 515 |
+
self.draw.draw_rectangle(left, fill_ink, 1)
|
| 516 |
+
|
| 517 |
+
right = [x1 - r, y0, x1, y1]
|
| 518 |
+
if corners[1]:
|
| 519 |
+
right[1] += r + 1
|
| 520 |
+
if corners[2]:
|
| 521 |
+
right[3] -= r + 1
|
| 522 |
+
self.draw.draw_rectangle(right, fill_ink, 1)
|
| 523 |
+
if ink is not None and ink != fill_ink and width != 0:
|
| 524 |
+
draw_corners(False)
|
| 525 |
+
|
| 526 |
+
if not full_x:
|
| 527 |
+
top = [x0, y0, x1, y0 + width - 1]
|
| 528 |
+
if corners[0]:
|
| 529 |
+
top[0] += r + 1
|
| 530 |
+
if corners[1]:
|
| 531 |
+
top[2] -= r + 1
|
| 532 |
+
self.draw.draw_rectangle(top, ink, 1)
|
| 533 |
+
|
| 534 |
+
bottom = [x0, y1 - width + 1, x1, y1]
|
| 535 |
+
if corners[3]:
|
| 536 |
+
bottom[0] += r + 1
|
| 537 |
+
if corners[2]:
|
| 538 |
+
bottom[2] -= r + 1
|
| 539 |
+
self.draw.draw_rectangle(bottom, ink, 1)
|
| 540 |
+
if not full_y:
|
| 541 |
+
left = [x0, y0, x0 + width - 1, y1]
|
| 542 |
+
if corners[0]:
|
| 543 |
+
left[1] += r + 1
|
| 544 |
+
if corners[3]:
|
| 545 |
+
left[3] -= r + 1
|
| 546 |
+
self.draw.draw_rectangle(left, ink, 1)
|
| 547 |
+
|
| 548 |
+
right = [x1 - width + 1, y0, x1, y1]
|
| 549 |
+
if corners[1]:
|
| 550 |
+
right[1] += r + 1
|
| 551 |
+
if corners[2]:
|
| 552 |
+
right[3] -= r + 1
|
| 553 |
+
self.draw.draw_rectangle(right, ink, 1)
|
| 554 |
+
|
| 555 |
+
def _multiline_check(self, text: AnyStr) -> bool:
|
| 556 |
+
split_character = "\n" if isinstance(text, str) else b"\n"
|
| 557 |
+
|
| 558 |
+
return split_character in text
|
| 559 |
+
|
| 560 |
+
def _multiline_split(self, text: AnyStr) -> list[AnyStr]:
|
| 561 |
+
return text.split("\n" if isinstance(text, str) else b"\n")
|
| 562 |
+
|
| 563 |
+
def _multiline_spacing(
|
| 564 |
+
self,
|
| 565 |
+
font: ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont,
|
| 566 |
+
spacing: float,
|
| 567 |
+
stroke_width: float,
|
| 568 |
+
) -> float:
|
| 569 |
+
return (
|
| 570 |
+
self.textbbox((0, 0), "A", font, stroke_width=stroke_width)[3]
|
| 571 |
+
+ stroke_width
|
| 572 |
+
+ spacing
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
def text(
|
| 576 |
+
self,
|
| 577 |
+
xy: tuple[float, float],
|
| 578 |
+
text: AnyStr,
|
| 579 |
+
fill: _Ink | None = None,
|
| 580 |
+
font: (
|
| 581 |
+
ImageFont.ImageFont
|
| 582 |
+
| ImageFont.FreeTypeFont
|
| 583 |
+
| ImageFont.TransposedFont
|
| 584 |
+
| None
|
| 585 |
+
) = None,
|
| 586 |
+
anchor: str | None = None,
|
| 587 |
+
spacing: float = 4,
|
| 588 |
+
align: str = "left",
|
| 589 |
+
direction: str | None = None,
|
| 590 |
+
features: list[str] | None = None,
|
| 591 |
+
language: str | None = None,
|
| 592 |
+
stroke_width: float = 0,
|
| 593 |
+
stroke_fill: _Ink | None = None,
|
| 594 |
+
embedded_color: bool = False,
|
| 595 |
+
*args: Any,
|
| 596 |
+
**kwargs: Any,
|
| 597 |
+
) -> None:
|
| 598 |
+
"""Draw text."""
|
| 599 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
| 600 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
| 601 |
+
raise ValueError(msg)
|
| 602 |
+
|
| 603 |
+
if font is None:
|
| 604 |
+
font = self._getfont(kwargs.get("font_size"))
|
| 605 |
+
|
| 606 |
+
if self._multiline_check(text):
|
| 607 |
+
return self.multiline_text(
|
| 608 |
+
xy,
|
| 609 |
+
text,
|
| 610 |
+
fill,
|
| 611 |
+
font,
|
| 612 |
+
anchor,
|
| 613 |
+
spacing,
|
| 614 |
+
align,
|
| 615 |
+
direction,
|
| 616 |
+
features,
|
| 617 |
+
language,
|
| 618 |
+
stroke_width,
|
| 619 |
+
stroke_fill,
|
| 620 |
+
embedded_color,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
def getink(fill: _Ink | None) -> int:
|
| 624 |
+
ink, fill_ink = self._getink(fill)
|
| 625 |
+
if ink is None:
|
| 626 |
+
assert fill_ink is not None
|
| 627 |
+
return fill_ink
|
| 628 |
+
return ink
|
| 629 |
+
|
| 630 |
+
def draw_text(ink: int, stroke_width: float = 0) -> None:
|
| 631 |
+
mode = self.fontmode
|
| 632 |
+
if stroke_width == 0 and embedded_color:
|
| 633 |
+
mode = "RGBA"
|
| 634 |
+
coord = []
|
| 635 |
+
for i in range(2):
|
| 636 |
+
coord.append(int(xy[i]))
|
| 637 |
+
start = (math.modf(xy[0])[0], math.modf(xy[1])[0])
|
| 638 |
+
try:
|
| 639 |
+
mask, offset = font.getmask2( # type: ignore[union-attr,misc]
|
| 640 |
+
text,
|
| 641 |
+
mode,
|
| 642 |
+
direction=direction,
|
| 643 |
+
features=features,
|
| 644 |
+
language=language,
|
| 645 |
+
stroke_width=stroke_width,
|
| 646 |
+
anchor=anchor,
|
| 647 |
+
ink=ink,
|
| 648 |
+
start=start,
|
| 649 |
+
*args,
|
| 650 |
+
**kwargs,
|
| 651 |
+
)
|
| 652 |
+
coord = [coord[0] + offset[0], coord[1] + offset[1]]
|
| 653 |
+
except AttributeError:
|
| 654 |
+
try:
|
| 655 |
+
mask = font.getmask( # type: ignore[misc]
|
| 656 |
+
text,
|
| 657 |
+
mode,
|
| 658 |
+
direction,
|
| 659 |
+
features,
|
| 660 |
+
language,
|
| 661 |
+
stroke_width,
|
| 662 |
+
anchor,
|
| 663 |
+
ink,
|
| 664 |
+
start=start,
|
| 665 |
+
*args,
|
| 666 |
+
**kwargs,
|
| 667 |
+
)
|
| 668 |
+
except TypeError:
|
| 669 |
+
mask = font.getmask(text)
|
| 670 |
+
if mode == "RGBA":
|
| 671 |
+
# font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
|
| 672 |
+
# extract mask and set text alpha
|
| 673 |
+
color, mask = mask, mask.getband(3)
|
| 674 |
+
ink_alpha = struct.pack("i", ink)[3]
|
| 675 |
+
color.fillband(3, ink_alpha)
|
| 676 |
+
x, y = coord
|
| 677 |
+
if self.im is not None:
|
| 678 |
+
self.im.paste(
|
| 679 |
+
color, (x, y, x + mask.size[0], y + mask.size[1]), mask
|
| 680 |
+
)
|
| 681 |
+
else:
|
| 682 |
+
self.draw.draw_bitmap(coord, mask, ink)
|
| 683 |
+
|
| 684 |
+
ink = getink(fill)
|
| 685 |
+
if ink is not None:
|
| 686 |
+
stroke_ink = None
|
| 687 |
+
if stroke_width:
|
| 688 |
+
stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
|
| 689 |
+
|
| 690 |
+
if stroke_ink is not None:
|
| 691 |
+
# Draw stroked text
|
| 692 |
+
draw_text(stroke_ink, stroke_width)
|
| 693 |
+
|
| 694 |
+
# Draw normal text
|
| 695 |
+
draw_text(ink, 0)
|
| 696 |
+
else:
|
| 697 |
+
# Only draw normal text
|
| 698 |
+
draw_text(ink)
|
| 699 |
+
|
| 700 |
+
def multiline_text(
|
| 701 |
+
self,
|
| 702 |
+
xy: tuple[float, float],
|
| 703 |
+
text: AnyStr,
|
| 704 |
+
fill: _Ink | None = None,
|
| 705 |
+
font: (
|
| 706 |
+
ImageFont.ImageFont
|
| 707 |
+
| ImageFont.FreeTypeFont
|
| 708 |
+
| ImageFont.TransposedFont
|
| 709 |
+
| None
|
| 710 |
+
) = None,
|
| 711 |
+
anchor: str | None = None,
|
| 712 |
+
spacing: float = 4,
|
| 713 |
+
align: str = "left",
|
| 714 |
+
direction: str | None = None,
|
| 715 |
+
features: list[str] | None = None,
|
| 716 |
+
language: str | None = None,
|
| 717 |
+
stroke_width: float = 0,
|
| 718 |
+
stroke_fill: _Ink | None = None,
|
| 719 |
+
embedded_color: bool = False,
|
| 720 |
+
*,
|
| 721 |
+
font_size: float | None = None,
|
| 722 |
+
) -> None:
|
| 723 |
+
if direction == "ttb":
|
| 724 |
+
msg = "ttb direction is unsupported for multiline text"
|
| 725 |
+
raise ValueError(msg)
|
| 726 |
+
|
| 727 |
+
if anchor is None:
|
| 728 |
+
anchor = "la"
|
| 729 |
+
elif len(anchor) != 2:
|
| 730 |
+
msg = "anchor must be a 2 character string"
|
| 731 |
+
raise ValueError(msg)
|
| 732 |
+
elif anchor[1] in "tb":
|
| 733 |
+
msg = "anchor not supported for multiline text"
|
| 734 |
+
raise ValueError(msg)
|
| 735 |
+
|
| 736 |
+
if font is None:
|
| 737 |
+
font = self._getfont(font_size)
|
| 738 |
+
|
| 739 |
+
widths = []
|
| 740 |
+
max_width: float = 0
|
| 741 |
+
lines = self._multiline_split(text)
|
| 742 |
+
line_spacing = self._multiline_spacing(font, spacing, stroke_width)
|
| 743 |
+
for line in lines:
|
| 744 |
+
line_width = self.textlength(
|
| 745 |
+
line, font, direction=direction, features=features, language=language
|
| 746 |
+
)
|
| 747 |
+
widths.append(line_width)
|
| 748 |
+
max_width = max(max_width, line_width)
|
| 749 |
+
|
| 750 |
+
top = xy[1]
|
| 751 |
+
if anchor[1] == "m":
|
| 752 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
| 753 |
+
elif anchor[1] == "d":
|
| 754 |
+
top -= (len(lines) - 1) * line_spacing
|
| 755 |
+
|
| 756 |
+
for idx, line in enumerate(lines):
|
| 757 |
+
left = xy[0]
|
| 758 |
+
width_difference = max_width - widths[idx]
|
| 759 |
+
|
| 760 |
+
# first align left by anchor
|
| 761 |
+
if anchor[0] == "m":
|
| 762 |
+
left -= width_difference / 2.0
|
| 763 |
+
elif anchor[0] == "r":
|
| 764 |
+
left -= width_difference
|
| 765 |
+
|
| 766 |
+
# then align by align parameter
|
| 767 |
+
if align == "left":
|
| 768 |
+
pass
|
| 769 |
+
elif align == "center":
|
| 770 |
+
left += width_difference / 2.0
|
| 771 |
+
elif align == "right":
|
| 772 |
+
left += width_difference
|
| 773 |
+
else:
|
| 774 |
+
msg = 'align must be "left", "center" or "right"'
|
| 775 |
+
raise ValueError(msg)
|
| 776 |
+
|
| 777 |
+
self.text(
|
| 778 |
+
(left, top),
|
| 779 |
+
line,
|
| 780 |
+
fill,
|
| 781 |
+
font,
|
| 782 |
+
anchor,
|
| 783 |
+
direction=direction,
|
| 784 |
+
features=features,
|
| 785 |
+
language=language,
|
| 786 |
+
stroke_width=stroke_width,
|
| 787 |
+
stroke_fill=stroke_fill,
|
| 788 |
+
embedded_color=embedded_color,
|
| 789 |
+
)
|
| 790 |
+
top += line_spacing
|
| 791 |
+
|
| 792 |
+
def textlength(
|
| 793 |
+
self,
|
| 794 |
+
text: AnyStr,
|
| 795 |
+
font: (
|
| 796 |
+
ImageFont.ImageFont
|
| 797 |
+
| ImageFont.FreeTypeFont
|
| 798 |
+
| ImageFont.TransposedFont
|
| 799 |
+
| None
|
| 800 |
+
) = None,
|
| 801 |
+
direction: str | None = None,
|
| 802 |
+
features: list[str] | None = None,
|
| 803 |
+
language: str | None = None,
|
| 804 |
+
embedded_color: bool = False,
|
| 805 |
+
*,
|
| 806 |
+
font_size: float | None = None,
|
| 807 |
+
) -> float:
|
| 808 |
+
"""Get the length of a given string, in pixels with 1/64 precision."""
|
| 809 |
+
if self._multiline_check(text):
|
| 810 |
+
msg = "can't measure length of multiline text"
|
| 811 |
+
raise ValueError(msg)
|
| 812 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
| 813 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
| 814 |
+
raise ValueError(msg)
|
| 815 |
+
|
| 816 |
+
if font is None:
|
| 817 |
+
font = self._getfont(font_size)
|
| 818 |
+
mode = "RGBA" if embedded_color else self.fontmode
|
| 819 |
+
return font.getlength(text, mode, direction, features, language)
|
| 820 |
+
|
| 821 |
+
def textbbox(
|
| 822 |
+
self,
|
| 823 |
+
xy: tuple[float, float],
|
| 824 |
+
text: AnyStr,
|
| 825 |
+
font: (
|
| 826 |
+
ImageFont.ImageFont
|
| 827 |
+
| ImageFont.FreeTypeFont
|
| 828 |
+
| ImageFont.TransposedFont
|
| 829 |
+
| None
|
| 830 |
+
) = None,
|
| 831 |
+
anchor: str | None = None,
|
| 832 |
+
spacing: float = 4,
|
| 833 |
+
align: str = "left",
|
| 834 |
+
direction: str | None = None,
|
| 835 |
+
features: list[str] | None = None,
|
| 836 |
+
language: str | None = None,
|
| 837 |
+
stroke_width: float = 0,
|
| 838 |
+
embedded_color: bool = False,
|
| 839 |
+
*,
|
| 840 |
+
font_size: float | None = None,
|
| 841 |
+
) -> tuple[float, float, float, float]:
|
| 842 |
+
"""Get the bounding box of a given string, in pixels."""
|
| 843 |
+
if embedded_color and self.mode not in ("RGB", "RGBA"):
|
| 844 |
+
msg = "Embedded color supported only in RGB and RGBA modes"
|
| 845 |
+
raise ValueError(msg)
|
| 846 |
+
|
| 847 |
+
if font is None:
|
| 848 |
+
font = self._getfont(font_size)
|
| 849 |
+
|
| 850 |
+
if self._multiline_check(text):
|
| 851 |
+
return self.multiline_textbbox(
|
| 852 |
+
xy,
|
| 853 |
+
text,
|
| 854 |
+
font,
|
| 855 |
+
anchor,
|
| 856 |
+
spacing,
|
| 857 |
+
align,
|
| 858 |
+
direction,
|
| 859 |
+
features,
|
| 860 |
+
language,
|
| 861 |
+
stroke_width,
|
| 862 |
+
embedded_color,
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
mode = "RGBA" if embedded_color else self.fontmode
|
| 866 |
+
bbox = font.getbbox(
|
| 867 |
+
text, mode, direction, features, language, stroke_width, anchor
|
| 868 |
+
)
|
| 869 |
+
return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
|
| 870 |
+
|
| 871 |
+
def multiline_textbbox(
|
| 872 |
+
self,
|
| 873 |
+
xy: tuple[float, float],
|
| 874 |
+
text: AnyStr,
|
| 875 |
+
font: (
|
| 876 |
+
ImageFont.ImageFont
|
| 877 |
+
| ImageFont.FreeTypeFont
|
| 878 |
+
| ImageFont.TransposedFont
|
| 879 |
+
| None
|
| 880 |
+
) = None,
|
| 881 |
+
anchor: str | None = None,
|
| 882 |
+
spacing: float = 4,
|
| 883 |
+
align: str = "left",
|
| 884 |
+
direction: str | None = None,
|
| 885 |
+
features: list[str] | None = None,
|
| 886 |
+
language: str | None = None,
|
| 887 |
+
stroke_width: float = 0,
|
| 888 |
+
embedded_color: bool = False,
|
| 889 |
+
*,
|
| 890 |
+
font_size: float | None = None,
|
| 891 |
+
) -> tuple[float, float, float, float]:
|
| 892 |
+
if direction == "ttb":
|
| 893 |
+
msg = "ttb direction is unsupported for multiline text"
|
| 894 |
+
raise ValueError(msg)
|
| 895 |
+
|
| 896 |
+
if anchor is None:
|
| 897 |
+
anchor = "la"
|
| 898 |
+
elif len(anchor) != 2:
|
| 899 |
+
msg = "anchor must be a 2 character string"
|
| 900 |
+
raise ValueError(msg)
|
| 901 |
+
elif anchor[1] in "tb":
|
| 902 |
+
msg = "anchor not supported for multiline text"
|
| 903 |
+
raise ValueError(msg)
|
| 904 |
+
|
| 905 |
+
if font is None:
|
| 906 |
+
font = self._getfont(font_size)
|
| 907 |
+
|
| 908 |
+
widths = []
|
| 909 |
+
max_width: float = 0
|
| 910 |
+
lines = self._multiline_split(text)
|
| 911 |
+
line_spacing = self._multiline_spacing(font, spacing, stroke_width)
|
| 912 |
+
for line in lines:
|
| 913 |
+
line_width = self.textlength(
|
| 914 |
+
line,
|
| 915 |
+
font,
|
| 916 |
+
direction=direction,
|
| 917 |
+
features=features,
|
| 918 |
+
language=language,
|
| 919 |
+
embedded_color=embedded_color,
|
| 920 |
+
)
|
| 921 |
+
widths.append(line_width)
|
| 922 |
+
max_width = max(max_width, line_width)
|
| 923 |
+
|
| 924 |
+
top = xy[1]
|
| 925 |
+
if anchor[1] == "m":
|
| 926 |
+
top -= (len(lines) - 1) * line_spacing / 2.0
|
| 927 |
+
elif anchor[1] == "d":
|
| 928 |
+
top -= (len(lines) - 1) * line_spacing
|
| 929 |
+
|
| 930 |
+
bbox: tuple[float, float, float, float] | None = None
|
| 931 |
+
|
| 932 |
+
for idx, line in enumerate(lines):
|
| 933 |
+
left = xy[0]
|
| 934 |
+
width_difference = max_width - widths[idx]
|
| 935 |
+
|
| 936 |
+
# first align left by anchor
|
| 937 |
+
if anchor[0] == "m":
|
| 938 |
+
left -= width_difference / 2.0
|
| 939 |
+
elif anchor[0] == "r":
|
| 940 |
+
left -= width_difference
|
| 941 |
+
|
| 942 |
+
# then align by align parameter
|
| 943 |
+
if align == "left":
|
| 944 |
+
pass
|
| 945 |
+
elif align == "center":
|
| 946 |
+
left += width_difference / 2.0
|
| 947 |
+
elif align == "right":
|
| 948 |
+
left += width_difference
|
| 949 |
+
else:
|
| 950 |
+
msg = 'align must be "left", "center" or "right"'
|
| 951 |
+
raise ValueError(msg)
|
| 952 |
+
|
| 953 |
+
bbox_line = self.textbbox(
|
| 954 |
+
(left, top),
|
| 955 |
+
line,
|
| 956 |
+
font,
|
| 957 |
+
anchor,
|
| 958 |
+
direction=direction,
|
| 959 |
+
features=features,
|
| 960 |
+
language=language,
|
| 961 |
+
stroke_width=stroke_width,
|
| 962 |
+
embedded_color=embedded_color,
|
| 963 |
+
)
|
| 964 |
+
if bbox is None:
|
| 965 |
+
bbox = bbox_line
|
| 966 |
+
else:
|
| 967 |
+
bbox = (
|
| 968 |
+
min(bbox[0], bbox_line[0]),
|
| 969 |
+
min(bbox[1], bbox_line[1]),
|
| 970 |
+
max(bbox[2], bbox_line[2]),
|
| 971 |
+
max(bbox[3], bbox_line[3]),
|
| 972 |
+
)
|
| 973 |
+
|
| 974 |
+
top += line_spacing
|
| 975 |
+
|
| 976 |
+
if bbox is None:
|
| 977 |
+
return xy[0], xy[1], xy[0], xy[1]
|
| 978 |
+
return bbox
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
|
| 982 |
+
"""
|
| 983 |
+
A simple 2D drawing interface for PIL images.
|
| 984 |
+
|
| 985 |
+
:param im: The image to draw in.
|
| 986 |
+
:param mode: Optional mode to use for color values. For RGB
|
| 987 |
+
images, this argument can be RGB or RGBA (to blend the
|
| 988 |
+
drawing into the image). For all other modes, this argument
|
| 989 |
+
must be the same as the image mode. If omitted, the mode
|
| 990 |
+
defaults to the mode of the image.
|
| 991 |
+
"""
|
| 992 |
+
try:
|
| 993 |
+
return getattr(im, "getdraw")(mode)
|
| 994 |
+
except AttributeError:
|
| 995 |
+
return ImageDraw(im, mode)
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
def getdraw(
|
| 999 |
+
im: Image.Image | None = None, hints: list[str] | None = None
|
| 1000 |
+
) -> tuple[ImageDraw2.Draw | None, ModuleType]:
|
| 1001 |
+
"""
|
| 1002 |
+
:param im: The image to draw in.
|
| 1003 |
+
:param hints: An optional list of hints. Deprecated.
|
| 1004 |
+
:returns: A (drawing context, drawing resource factory) tuple.
|
| 1005 |
+
"""
|
| 1006 |
+
if hints is not None:
|
| 1007 |
+
deprecate("'hints' parameter", 12)
|
| 1008 |
+
from . import ImageDraw2
|
| 1009 |
+
|
| 1010 |
+
draw = ImageDraw2.Draw(im) if im is not None else None
|
| 1011 |
+
return draw, ImageDraw2
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
def floodfill(
|
| 1015 |
+
image: Image.Image,
|
| 1016 |
+
xy: tuple[int, int],
|
| 1017 |
+
value: float | tuple[int, ...],
|
| 1018 |
+
border: float | tuple[int, ...] | None = None,
|
| 1019 |
+
thresh: float = 0,
|
| 1020 |
+
) -> None:
|
| 1021 |
+
"""
|
| 1022 |
+
.. warning:: This method is experimental.
|
| 1023 |
+
|
| 1024 |
+
Fills a bounded region with a given color.
|
| 1025 |
+
|
| 1026 |
+
:param image: Target image.
|
| 1027 |
+
:param xy: Seed position (a 2-item coordinate tuple). See
|
| 1028 |
+
:ref:`coordinate-system`.
|
| 1029 |
+
:param value: Fill color.
|
| 1030 |
+
:param border: Optional border value. If given, the region consists of
|
| 1031 |
+
pixels with a color different from the border color. If not given,
|
| 1032 |
+
the region consists of pixels having the same color as the seed
|
| 1033 |
+
pixel.
|
| 1034 |
+
:param thresh: Optional threshold value which specifies a maximum
|
| 1035 |
+
tolerable difference of a pixel value from the 'background' in
|
| 1036 |
+
order for it to be replaced. Useful for filling regions of
|
| 1037 |
+
non-homogeneous, but similar, colors.
|
| 1038 |
+
"""
|
| 1039 |
+
# based on an implementation by Eric S. Raymond
|
| 1040 |
+
# amended by yo1995 @20180806
|
| 1041 |
+
pixel = image.load()
|
| 1042 |
+
assert pixel is not None
|
| 1043 |
+
x, y = xy
|
| 1044 |
+
try:
|
| 1045 |
+
background = pixel[x, y]
|
| 1046 |
+
if _color_diff(value, background) <= thresh:
|
| 1047 |
+
return # seed point already has fill color
|
| 1048 |
+
pixel[x, y] = value
|
| 1049 |
+
except (ValueError, IndexError):
|
| 1050 |
+
return # seed point outside image
|
| 1051 |
+
edge = {(x, y)}
|
| 1052 |
+
# use a set to keep record of current and previous edge pixels
|
| 1053 |
+
# to reduce memory consumption
|
| 1054 |
+
full_edge = set()
|
| 1055 |
+
while edge:
|
| 1056 |
+
new_edge = set()
|
| 1057 |
+
for x, y in edge: # 4 adjacent method
|
| 1058 |
+
for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
| 1059 |
+
# If already processed, or if a coordinate is negative, skip
|
| 1060 |
+
if (s, t) in full_edge or s < 0 or t < 0:
|
| 1061 |
+
continue
|
| 1062 |
+
try:
|
| 1063 |
+
p = pixel[s, t]
|
| 1064 |
+
except (ValueError, IndexError):
|
| 1065 |
+
pass
|
| 1066 |
+
else:
|
| 1067 |
+
full_edge.add((s, t))
|
| 1068 |
+
if border is None:
|
| 1069 |
+
fill = _color_diff(p, background) <= thresh
|
| 1070 |
+
else:
|
| 1071 |
+
fill = p not in (value, border)
|
| 1072 |
+
if fill:
|
| 1073 |
+
pixel[s, t] = value
|
| 1074 |
+
new_edge.add((s, t))
|
| 1075 |
+
full_edge = edge # discard pixels processed
|
| 1076 |
+
edge = new_edge
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
def _compute_regular_polygon_vertices(
|
| 1080 |
+
bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
|
| 1081 |
+
) -> list[tuple[float, float]]:
|
| 1082 |
+
"""
|
| 1083 |
+
Generate a list of vertices for a 2D regular polygon.
|
| 1084 |
+
|
| 1085 |
+
:param bounding_circle: The bounding circle is a sequence defined
|
| 1086 |
+
by a point and radius. The polygon is inscribed in this circle.
|
| 1087 |
+
(e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
|
| 1088 |
+
:param n_sides: Number of sides
|
| 1089 |
+
(e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
|
| 1090 |
+
:param rotation: Apply an arbitrary rotation to the polygon
|
| 1091 |
+
(e.g. ``rotation=90``, applies a 90 degree rotation)
|
| 1092 |
+
:return: List of regular polygon vertices
|
| 1093 |
+
(e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
|
| 1094 |
+
|
| 1095 |
+
How are the vertices computed?
|
| 1096 |
+
1. Compute the following variables
|
| 1097 |
+
- theta: Angle between the apothem & the nearest polygon vertex
|
| 1098 |
+
- side_length: Length of each polygon edge
|
| 1099 |
+
- centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
|
| 1100 |
+
- polygon_radius: Polygon radius (last element of bounding_circle)
|
| 1101 |
+
- angles: Location of each polygon vertex in polar grid
|
| 1102 |
+
(e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
|
| 1103 |
+
|
| 1104 |
+
2. For each angle in angles, get the polygon vertex at that angle
|
| 1105 |
+
The vertex is computed using the equation below.
|
| 1106 |
+
X= xcos(φ) + ysin(φ)
|
| 1107 |
+
Y= −xsin(φ) + ycos(φ)
|
| 1108 |
+
|
| 1109 |
+
Note:
|
| 1110 |
+
φ = angle in degrees
|
| 1111 |
+
x = 0
|
| 1112 |
+
y = polygon_radius
|
| 1113 |
+
|
| 1114 |
+
The formula above assumes rotation around the origin.
|
| 1115 |
+
In our case, we are rotating around the centroid.
|
| 1116 |
+
To account for this, we use the formula below
|
| 1117 |
+
X = xcos(φ) + ysin(φ) + centroid_x
|
| 1118 |
+
Y = −xsin(φ) + ycos(φ) + centroid_y
|
| 1119 |
+
"""
|
| 1120 |
+
# 1. Error Handling
|
| 1121 |
+
# 1.1 Check `n_sides` has an appropriate value
|
| 1122 |
+
if not isinstance(n_sides, int):
|
| 1123 |
+
msg = "n_sides should be an int" # type: ignore[unreachable]
|
| 1124 |
+
raise TypeError(msg)
|
| 1125 |
+
if n_sides < 3:
|
| 1126 |
+
msg = "n_sides should be an int > 2"
|
| 1127 |
+
raise ValueError(msg)
|
| 1128 |
+
|
| 1129 |
+
# 1.2 Check `bounding_circle` has an appropriate value
|
| 1130 |
+
if not isinstance(bounding_circle, (list, tuple)):
|
| 1131 |
+
msg = "bounding_circle should be a sequence"
|
| 1132 |
+
raise TypeError(msg)
|
| 1133 |
+
|
| 1134 |
+
if len(bounding_circle) == 3:
|
| 1135 |
+
if not all(isinstance(i, (int, float)) for i in bounding_circle):
|
| 1136 |
+
msg = "bounding_circle should only contain numeric data"
|
| 1137 |
+
raise ValueError(msg)
|
| 1138 |
+
|
| 1139 |
+
*centroid, polygon_radius = cast(list[float], list(bounding_circle))
|
| 1140 |
+
elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
|
| 1141 |
+
if not all(
|
| 1142 |
+
isinstance(i, (int, float)) for i in bounding_circle[0]
|
| 1143 |
+
) or not isinstance(bounding_circle[1], (int, float)):
|
| 1144 |
+
msg = "bounding_circle should only contain numeric data"
|
| 1145 |
+
raise ValueError(msg)
|
| 1146 |
+
|
| 1147 |
+
if len(bounding_circle[0]) != 2:
|
| 1148 |
+
msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
|
| 1149 |
+
raise ValueError(msg)
|
| 1150 |
+
|
| 1151 |
+
centroid = cast(list[float], list(bounding_circle[0]))
|
| 1152 |
+
polygon_radius = cast(float, bounding_circle[1])
|
| 1153 |
+
else:
|
| 1154 |
+
msg = (
|
| 1155 |
+
"bounding_circle should contain 2D coordinates "
|
| 1156 |
+
"and a radius (e.g. (x, y, r) or ((x, y), r) )"
|
| 1157 |
+
)
|
| 1158 |
+
raise ValueError(msg)
|
| 1159 |
+
|
| 1160 |
+
if polygon_radius <= 0:
|
| 1161 |
+
msg = "bounding_circle radius should be > 0"
|
| 1162 |
+
raise ValueError(msg)
|
| 1163 |
+
|
| 1164 |
+
# 1.3 Check `rotation` has an appropriate value
|
| 1165 |
+
if not isinstance(rotation, (int, float)):
|
| 1166 |
+
msg = "rotation should be an int or float" # type: ignore[unreachable]
|
| 1167 |
+
raise ValueError(msg)
|
| 1168 |
+
|
| 1169 |
+
# 2. Define Helper Functions
|
| 1170 |
+
def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
|
| 1171 |
+
return (
|
| 1172 |
+
round(
|
| 1173 |
+
point[0] * math.cos(math.radians(360 - degrees))
|
| 1174 |
+
- point[1] * math.sin(math.radians(360 - degrees))
|
| 1175 |
+
+ centroid[0],
|
| 1176 |
+
2,
|
| 1177 |
+
),
|
| 1178 |
+
round(
|
| 1179 |
+
point[1] * math.cos(math.radians(360 - degrees))
|
| 1180 |
+
+ point[0] * math.sin(math.radians(360 - degrees))
|
| 1181 |
+
+ centroid[1],
|
| 1182 |
+
2,
|
| 1183 |
+
),
|
| 1184 |
+
)
|
| 1185 |
+
|
| 1186 |
+
def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
|
| 1187 |
+
start_point = [polygon_radius, 0]
|
| 1188 |
+
return _apply_rotation(start_point, angle)
|
| 1189 |
+
|
| 1190 |
+
def _get_angles(n_sides: int, rotation: float) -> list[float]:
|
| 1191 |
+
angles = []
|
| 1192 |
+
degrees = 360 / n_sides
|
| 1193 |
+
# Start with the bottom left polygon vertex
|
| 1194 |
+
current_angle = (270 - 0.5 * degrees) + rotation
|
| 1195 |
+
for _ in range(0, n_sides):
|
| 1196 |
+
angles.append(current_angle)
|
| 1197 |
+
current_angle += degrees
|
| 1198 |
+
if current_angle > 360:
|
| 1199 |
+
current_angle -= 360
|
| 1200 |
+
return angles
|
| 1201 |
+
|
| 1202 |
+
# 3. Variable Declarations
|
| 1203 |
+
angles = _get_angles(n_sides, rotation)
|
| 1204 |
+
|
| 1205 |
+
# 4. Compute Vertices
|
| 1206 |
+
return [_compute_polygon_vertex(angle) for angle in angles]
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
def _color_diff(
|
| 1210 |
+
color1: float | tuple[int, ...], color2: float | tuple[int, ...]
|
| 1211 |
+
) -> float:
|
| 1212 |
+
"""
|
| 1213 |
+
Uses 1-norm distance to calculate difference between two values.
|
| 1214 |
+
"""
|
| 1215 |
+
first = color1 if isinstance(color1, tuple) else (color1,)
|
| 1216 |
+
second = color2 if isinstance(color2, tuple) else (color2,)
|
| 1217 |
+
|
| 1218 |
+
return sum(abs(first[i] - second[i]) for i in range(0, len(second)))
|
lib/python3.10/site-packages/PIL/ImageDraw2.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# WCK-style drawing interface operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2003-12-07 fl created
|
| 9 |
+
# 2005-05-15 fl updated; added to PIL as ImageDraw2
|
| 10 |
+
# 2005-05-15 fl added text support
|
| 11 |
+
# 2005-05-20 fl added arc/chord/pieslice support
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 2003-2005 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 2003-2005 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
(Experimental) WCK-style drawing interface operations
|
| 22 |
+
|
| 23 |
+
.. seealso:: :py:mod:`PIL.ImageDraw`
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
from typing import Any, AnyStr, BinaryIO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
|
| 30 |
+
from ._typing import Coords, StrOrBytesPath
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Pen:
|
| 34 |
+
"""Stores an outline color and width."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
|
| 37 |
+
self.color = ImageColor.getrgb(color)
|
| 38 |
+
self.width = width
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Brush:
|
| 42 |
+
"""Stores a fill color"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, color: str, opacity: int = 255) -> None:
|
| 45 |
+
self.color = ImageColor.getrgb(color)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Font:
|
| 49 |
+
"""Stores a TrueType font and color"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
|
| 53 |
+
) -> None:
|
| 54 |
+
# FIXME: add support for bitmap fonts
|
| 55 |
+
self.color = ImageColor.getrgb(color)
|
| 56 |
+
self.font = ImageFont.truetype(file, size)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Draw:
|
| 60 |
+
"""
|
| 61 |
+
(Experimental) WCK-style drawing interface
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
image: Image.Image | str,
|
| 67 |
+
size: tuple[int, int] | list[int] | None = None,
|
| 68 |
+
color: float | tuple[float, ...] | str | None = None,
|
| 69 |
+
) -> None:
|
| 70 |
+
if isinstance(image, str):
|
| 71 |
+
if size is None:
|
| 72 |
+
msg = "If image argument is mode string, size must be a list or tuple"
|
| 73 |
+
raise ValueError(msg)
|
| 74 |
+
image = Image.new(image, size, color)
|
| 75 |
+
self.draw = ImageDraw.Draw(image)
|
| 76 |
+
self.image = image
|
| 77 |
+
self.transform: tuple[float, float, float, float, float, float] | None = None
|
| 78 |
+
|
| 79 |
+
def flush(self) -> Image.Image:
|
| 80 |
+
return self.image
|
| 81 |
+
|
| 82 |
+
def render(
|
| 83 |
+
self,
|
| 84 |
+
op: str,
|
| 85 |
+
xy: Coords,
|
| 86 |
+
pen: Pen | Brush | None,
|
| 87 |
+
brush: Brush | Pen | None = None,
|
| 88 |
+
**kwargs: Any,
|
| 89 |
+
) -> None:
|
| 90 |
+
# handle color arguments
|
| 91 |
+
outline = fill = None
|
| 92 |
+
width = 1
|
| 93 |
+
if isinstance(pen, Pen):
|
| 94 |
+
outline = pen.color
|
| 95 |
+
width = pen.width
|
| 96 |
+
elif isinstance(brush, Pen):
|
| 97 |
+
outline = brush.color
|
| 98 |
+
width = brush.width
|
| 99 |
+
if isinstance(brush, Brush):
|
| 100 |
+
fill = brush.color
|
| 101 |
+
elif isinstance(pen, Brush):
|
| 102 |
+
fill = pen.color
|
| 103 |
+
# handle transformation
|
| 104 |
+
if self.transform:
|
| 105 |
+
path = ImagePath.Path(xy)
|
| 106 |
+
path.transform(self.transform)
|
| 107 |
+
xy = path
|
| 108 |
+
# render the item
|
| 109 |
+
if op in ("arc", "line"):
|
| 110 |
+
kwargs.setdefault("fill", outline)
|
| 111 |
+
else:
|
| 112 |
+
kwargs.setdefault("fill", fill)
|
| 113 |
+
kwargs.setdefault("outline", outline)
|
| 114 |
+
if op == "line":
|
| 115 |
+
kwargs.setdefault("width", width)
|
| 116 |
+
getattr(self.draw, op)(xy, **kwargs)
|
| 117 |
+
|
| 118 |
+
def settransform(self, offset: tuple[float, float]) -> None:
|
| 119 |
+
"""Sets a transformation offset."""
|
| 120 |
+
(xoffset, yoffset) = offset
|
| 121 |
+
self.transform = (1, 0, xoffset, 0, 1, yoffset)
|
| 122 |
+
|
| 123 |
+
def arc(
|
| 124 |
+
self,
|
| 125 |
+
xy: Coords,
|
| 126 |
+
pen: Pen | Brush | None,
|
| 127 |
+
start: float,
|
| 128 |
+
end: float,
|
| 129 |
+
*options: Any,
|
| 130 |
+
) -> None:
|
| 131 |
+
"""
|
| 132 |
+
Draws an arc (a portion of a circle outline) between the start and end
|
| 133 |
+
angles, inside the given bounding box.
|
| 134 |
+
|
| 135 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
| 136 |
+
"""
|
| 137 |
+
self.render("arc", xy, pen, *options, start=start, end=end)
|
| 138 |
+
|
| 139 |
+
def chord(
|
| 140 |
+
self,
|
| 141 |
+
xy: Coords,
|
| 142 |
+
pen: Pen | Brush | None,
|
| 143 |
+
start: float,
|
| 144 |
+
end: float,
|
| 145 |
+
*options: Any,
|
| 146 |
+
) -> None:
|
| 147 |
+
"""
|
| 148 |
+
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
|
| 149 |
+
with a straight line.
|
| 150 |
+
|
| 151 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
| 152 |
+
"""
|
| 153 |
+
self.render("chord", xy, pen, *options, start=start, end=end)
|
| 154 |
+
|
| 155 |
+
def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 156 |
+
"""
|
| 157 |
+
Draws an ellipse inside the given bounding box.
|
| 158 |
+
|
| 159 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
| 160 |
+
"""
|
| 161 |
+
self.render("ellipse", xy, pen, *options)
|
| 162 |
+
|
| 163 |
+
def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 164 |
+
"""
|
| 165 |
+
Draws a line between the coordinates in the ``xy`` list.
|
| 166 |
+
|
| 167 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
| 168 |
+
"""
|
| 169 |
+
self.render("line", xy, pen, *options)
|
| 170 |
+
|
| 171 |
+
def pieslice(
|
| 172 |
+
self,
|
| 173 |
+
xy: Coords,
|
| 174 |
+
pen: Pen | Brush | None,
|
| 175 |
+
start: float,
|
| 176 |
+
end: float,
|
| 177 |
+
*options: Any,
|
| 178 |
+
) -> None:
|
| 179 |
+
"""
|
| 180 |
+
Same as arc, but also draws straight lines between the end points and the
|
| 181 |
+
center of the bounding box.
|
| 182 |
+
|
| 183 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
| 184 |
+
"""
|
| 185 |
+
self.render("pieslice", xy, pen, *options, start=start, end=end)
|
| 186 |
+
|
| 187 |
+
def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 188 |
+
"""
|
| 189 |
+
Draws a polygon.
|
| 190 |
+
|
| 191 |
+
The polygon outline consists of straight lines between the given
|
| 192 |
+
coordinates, plus a straight line between the last and the first
|
| 193 |
+
coordinate.
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
| 197 |
+
"""
|
| 198 |
+
self.render("polygon", xy, pen, *options)
|
| 199 |
+
|
| 200 |
+
def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
|
| 201 |
+
"""
|
| 202 |
+
Draws a rectangle.
|
| 203 |
+
|
| 204 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
| 205 |
+
"""
|
| 206 |
+
self.render("rectangle", xy, pen, *options)
|
| 207 |
+
|
| 208 |
+
def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
|
| 209 |
+
"""
|
| 210 |
+
Draws the string at the given position.
|
| 211 |
+
|
| 212 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
| 213 |
+
"""
|
| 214 |
+
if self.transform:
|
| 215 |
+
path = ImagePath.Path(xy)
|
| 216 |
+
path.transform(self.transform)
|
| 217 |
+
xy = path
|
| 218 |
+
self.draw.text(xy, text, font=font.font, fill=font.color)
|
| 219 |
+
|
| 220 |
+
def textbbox(
|
| 221 |
+
self, xy: tuple[float, float], text: AnyStr, font: Font
|
| 222 |
+
) -> tuple[float, float, float, float]:
|
| 223 |
+
"""
|
| 224 |
+
Returns bounding box (in pixels) of given text.
|
| 225 |
+
|
| 226 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 227 |
+
|
| 228 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
|
| 229 |
+
"""
|
| 230 |
+
if self.transform:
|
| 231 |
+
path = ImagePath.Path(xy)
|
| 232 |
+
path.transform(self.transform)
|
| 233 |
+
xy = path
|
| 234 |
+
return self.draw.textbbox(xy, text, font=font.font)
|
| 235 |
+
|
| 236 |
+
def textlength(self, text: AnyStr, font: Font) -> float:
|
| 237 |
+
"""
|
| 238 |
+
Returns length (in pixels) of given text.
|
| 239 |
+
This is the amount by which following text should be offset.
|
| 240 |
+
|
| 241 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
|
| 242 |
+
"""
|
| 243 |
+
return self.draw.textlength(text, font=font.font)
|
lib/python3.10/site-packages/PIL/ImageFilter.py
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# standard filters
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-11-27 fl Created
|
| 9 |
+
# 2002-06-08 fl Added rank and mode filters
|
| 10 |
+
# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 13 |
+
# Copyright (c) 1995-2002 by Fredrik Lundh.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import abc
|
| 20 |
+
import functools
|
| 21 |
+
from collections.abc import Sequence
|
| 22 |
+
from types import ModuleType
|
| 23 |
+
from typing import TYPE_CHECKING, Any, Callable, cast
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from . import _imaging
|
| 27 |
+
from ._typing import NumpyArray
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Filter:
|
| 31 |
+
@abc.abstractmethod
|
| 32 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MultibandFilter(Filter):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class BuiltinFilter(MultibandFilter):
|
| 41 |
+
filterargs: tuple[Any, ...]
|
| 42 |
+
|
| 43 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 44 |
+
if image.mode == "P":
|
| 45 |
+
msg = "cannot filter palette images"
|
| 46 |
+
raise ValueError(msg)
|
| 47 |
+
return image.filter(*self.filterargs)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Kernel(BuiltinFilter):
|
| 51 |
+
"""
|
| 52 |
+
Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
|
| 53 |
+
point kernels.
|
| 54 |
+
|
| 55 |
+
Kernels can only be applied to "L" and "RGB" images.
|
| 56 |
+
|
| 57 |
+
:param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
|
| 58 |
+
:param kernel: A sequence containing kernel weights. The kernel will be flipped
|
| 59 |
+
vertically before being applied to the image.
|
| 60 |
+
:param scale: Scale factor. If given, the result for each pixel is divided by this
|
| 61 |
+
value. The default is the sum of the kernel weights.
|
| 62 |
+
:param offset: Offset. If given, this value is added to the result, after it has
|
| 63 |
+
been divided by the scale factor.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
name = "Kernel"
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
size: tuple[int, int],
|
| 71 |
+
kernel: Sequence[float],
|
| 72 |
+
scale: float | None = None,
|
| 73 |
+
offset: float = 0,
|
| 74 |
+
) -> None:
|
| 75 |
+
if scale is None:
|
| 76 |
+
# default scale is sum of kernel
|
| 77 |
+
scale = functools.reduce(lambda a, b: a + b, kernel)
|
| 78 |
+
if size[0] * size[1] != len(kernel):
|
| 79 |
+
msg = "not enough coefficients in kernel"
|
| 80 |
+
raise ValueError(msg)
|
| 81 |
+
self.filterargs = size, scale, offset, kernel
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class RankFilter(Filter):
|
| 85 |
+
"""
|
| 86 |
+
Create a rank filter. The rank filter sorts all pixels in
|
| 87 |
+
a window of the given size, and returns the ``rank``'th value.
|
| 88 |
+
|
| 89 |
+
:param size: The kernel size, in pixels.
|
| 90 |
+
:param rank: What pixel value to pick. Use 0 for a min filter,
|
| 91 |
+
``size * size / 2`` for a median filter, ``size * size - 1``
|
| 92 |
+
for a max filter, etc.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
name = "Rank"
|
| 96 |
+
|
| 97 |
+
def __init__(self, size: int, rank: int) -> None:
|
| 98 |
+
self.size = size
|
| 99 |
+
self.rank = rank
|
| 100 |
+
|
| 101 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 102 |
+
if image.mode == "P":
|
| 103 |
+
msg = "cannot filter palette images"
|
| 104 |
+
raise ValueError(msg)
|
| 105 |
+
image = image.expand(self.size // 2, self.size // 2)
|
| 106 |
+
return image.rankfilter(self.size, self.rank)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class MedianFilter(RankFilter):
|
| 110 |
+
"""
|
| 111 |
+
Create a median filter. Picks the median pixel value in a window with the
|
| 112 |
+
given size.
|
| 113 |
+
|
| 114 |
+
:param size: The kernel size, in pixels.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
name = "Median"
|
| 118 |
+
|
| 119 |
+
def __init__(self, size: int = 3) -> None:
|
| 120 |
+
self.size = size
|
| 121 |
+
self.rank = size * size // 2
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class MinFilter(RankFilter):
|
| 125 |
+
"""
|
| 126 |
+
Create a min filter. Picks the lowest pixel value in a window with the
|
| 127 |
+
given size.
|
| 128 |
+
|
| 129 |
+
:param size: The kernel size, in pixels.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
name = "Min"
|
| 133 |
+
|
| 134 |
+
def __init__(self, size: int = 3) -> None:
|
| 135 |
+
self.size = size
|
| 136 |
+
self.rank = 0
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class MaxFilter(RankFilter):
|
| 140 |
+
"""
|
| 141 |
+
Create a max filter. Picks the largest pixel value in a window with the
|
| 142 |
+
given size.
|
| 143 |
+
|
| 144 |
+
:param size: The kernel size, in pixels.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
name = "Max"
|
| 148 |
+
|
| 149 |
+
def __init__(self, size: int = 3) -> None:
|
| 150 |
+
self.size = size
|
| 151 |
+
self.rank = size * size - 1
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class ModeFilter(Filter):
|
| 155 |
+
"""
|
| 156 |
+
Create a mode filter. Picks the most frequent pixel value in a box with the
|
| 157 |
+
given size. Pixel values that occur only once or twice are ignored; if no
|
| 158 |
+
pixel value occurs more than twice, the original pixel value is preserved.
|
| 159 |
+
|
| 160 |
+
:param size: The kernel size, in pixels.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
name = "Mode"
|
| 164 |
+
|
| 165 |
+
def __init__(self, size: int = 3) -> None:
|
| 166 |
+
self.size = size
|
| 167 |
+
|
| 168 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 169 |
+
return image.modefilter(self.size)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class GaussianBlur(MultibandFilter):
|
| 173 |
+
"""Blurs the image with a sequence of extended box filters, which
|
| 174 |
+
approximates a Gaussian kernel. For details on accuracy see
|
| 175 |
+
<https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
|
| 176 |
+
|
| 177 |
+
:param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
|
| 178 |
+
numbers for x and y, or a single number for both.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
name = "GaussianBlur"
|
| 182 |
+
|
| 183 |
+
def __init__(self, radius: float | Sequence[float] = 2) -> None:
|
| 184 |
+
self.radius = radius
|
| 185 |
+
|
| 186 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 187 |
+
xy = self.radius
|
| 188 |
+
if isinstance(xy, (int, float)):
|
| 189 |
+
xy = (xy, xy)
|
| 190 |
+
if xy == (0, 0):
|
| 191 |
+
return image.copy()
|
| 192 |
+
return image.gaussian_blur(xy)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class BoxBlur(MultibandFilter):
|
| 196 |
+
"""Blurs the image by setting each pixel to the average value of the pixels
|
| 197 |
+
in a square box extending radius pixels in each direction.
|
| 198 |
+
Supports float radius of arbitrary size. Uses an optimized implementation
|
| 199 |
+
which runs in linear time relative to the size of the image
|
| 200 |
+
for any radius value.
|
| 201 |
+
|
| 202 |
+
:param radius: Size of the box in a direction. Either a sequence of two numbers for
|
| 203 |
+
x and y, or a single number for both.
|
| 204 |
+
|
| 205 |
+
Radius 0 does not blur, returns an identical image.
|
| 206 |
+
Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
name = "BoxBlur"
|
| 210 |
+
|
| 211 |
+
def __init__(self, radius: float | Sequence[float]) -> None:
|
| 212 |
+
xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
|
| 213 |
+
if xy[0] < 0 or xy[1] < 0:
|
| 214 |
+
msg = "radius must be >= 0"
|
| 215 |
+
raise ValueError(msg)
|
| 216 |
+
self.radius = radius
|
| 217 |
+
|
| 218 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 219 |
+
xy = self.radius
|
| 220 |
+
if isinstance(xy, (int, float)):
|
| 221 |
+
xy = (xy, xy)
|
| 222 |
+
if xy == (0, 0):
|
| 223 |
+
return image.copy()
|
| 224 |
+
return image.box_blur(xy)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class UnsharpMask(MultibandFilter):
|
| 228 |
+
"""Unsharp mask filter.
|
| 229 |
+
|
| 230 |
+
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
|
| 231 |
+
the parameters.
|
| 232 |
+
|
| 233 |
+
:param radius: Blur Radius
|
| 234 |
+
:param percent: Unsharp strength, in percent
|
| 235 |
+
:param threshold: Threshold controls the minimum brightness change that
|
| 236 |
+
will be sharpened
|
| 237 |
+
|
| 238 |
+
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
name = "UnsharpMask"
|
| 243 |
+
|
| 244 |
+
def __init__(
|
| 245 |
+
self, radius: float = 2, percent: int = 150, threshold: int = 3
|
| 246 |
+
) -> None:
|
| 247 |
+
self.radius = radius
|
| 248 |
+
self.percent = percent
|
| 249 |
+
self.threshold = threshold
|
| 250 |
+
|
| 251 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 252 |
+
return image.unsharp_mask(self.radius, self.percent, self.threshold)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class BLUR(BuiltinFilter):
|
| 256 |
+
name = "Blur"
|
| 257 |
+
# fmt: off
|
| 258 |
+
filterargs = (5, 5), 16, 0, (
|
| 259 |
+
1, 1, 1, 1, 1,
|
| 260 |
+
1, 0, 0, 0, 1,
|
| 261 |
+
1, 0, 0, 0, 1,
|
| 262 |
+
1, 0, 0, 0, 1,
|
| 263 |
+
1, 1, 1, 1, 1,
|
| 264 |
+
)
|
| 265 |
+
# fmt: on
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class CONTOUR(BuiltinFilter):
|
| 269 |
+
name = "Contour"
|
| 270 |
+
# fmt: off
|
| 271 |
+
filterargs = (3, 3), 1, 255, (
|
| 272 |
+
-1, -1, -1,
|
| 273 |
+
-1, 8, -1,
|
| 274 |
+
-1, -1, -1,
|
| 275 |
+
)
|
| 276 |
+
# fmt: on
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class DETAIL(BuiltinFilter):
|
| 280 |
+
name = "Detail"
|
| 281 |
+
# fmt: off
|
| 282 |
+
filterargs = (3, 3), 6, 0, (
|
| 283 |
+
0, -1, 0,
|
| 284 |
+
-1, 10, -1,
|
| 285 |
+
0, -1, 0,
|
| 286 |
+
)
|
| 287 |
+
# fmt: on
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class EDGE_ENHANCE(BuiltinFilter):
|
| 291 |
+
name = "Edge-enhance"
|
| 292 |
+
# fmt: off
|
| 293 |
+
filterargs = (3, 3), 2, 0, (
|
| 294 |
+
-1, -1, -1,
|
| 295 |
+
-1, 10, -1,
|
| 296 |
+
-1, -1, -1,
|
| 297 |
+
)
|
| 298 |
+
# fmt: on
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class EDGE_ENHANCE_MORE(BuiltinFilter):
|
| 302 |
+
name = "Edge-enhance More"
|
| 303 |
+
# fmt: off
|
| 304 |
+
filterargs = (3, 3), 1, 0, (
|
| 305 |
+
-1, -1, -1,
|
| 306 |
+
-1, 9, -1,
|
| 307 |
+
-1, -1, -1,
|
| 308 |
+
)
|
| 309 |
+
# fmt: on
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class EMBOSS(BuiltinFilter):
|
| 313 |
+
name = "Emboss"
|
| 314 |
+
# fmt: off
|
| 315 |
+
filterargs = (3, 3), 1, 128, (
|
| 316 |
+
-1, 0, 0,
|
| 317 |
+
0, 1, 0,
|
| 318 |
+
0, 0, 0,
|
| 319 |
+
)
|
| 320 |
+
# fmt: on
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class FIND_EDGES(BuiltinFilter):
|
| 324 |
+
name = "Find Edges"
|
| 325 |
+
# fmt: off
|
| 326 |
+
filterargs = (3, 3), 1, 0, (
|
| 327 |
+
-1, -1, -1,
|
| 328 |
+
-1, 8, -1,
|
| 329 |
+
-1, -1, -1,
|
| 330 |
+
)
|
| 331 |
+
# fmt: on
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class SHARPEN(BuiltinFilter):
|
| 335 |
+
name = "Sharpen"
|
| 336 |
+
# fmt: off
|
| 337 |
+
filterargs = (3, 3), 16, 0, (
|
| 338 |
+
-2, -2, -2,
|
| 339 |
+
-2, 32, -2,
|
| 340 |
+
-2, -2, -2,
|
| 341 |
+
)
|
| 342 |
+
# fmt: on
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
class SMOOTH(BuiltinFilter):
|
| 346 |
+
name = "Smooth"
|
| 347 |
+
# fmt: off
|
| 348 |
+
filterargs = (3, 3), 13, 0, (
|
| 349 |
+
1, 1, 1,
|
| 350 |
+
1, 5, 1,
|
| 351 |
+
1, 1, 1,
|
| 352 |
+
)
|
| 353 |
+
# fmt: on
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class SMOOTH_MORE(BuiltinFilter):
|
| 357 |
+
name = "Smooth More"
|
| 358 |
+
# fmt: off
|
| 359 |
+
filterargs = (5, 5), 100, 0, (
|
| 360 |
+
1, 1, 1, 1, 1,
|
| 361 |
+
1, 5, 5, 5, 1,
|
| 362 |
+
1, 5, 44, 5, 1,
|
| 363 |
+
1, 5, 5, 5, 1,
|
| 364 |
+
1, 1, 1, 1, 1,
|
| 365 |
+
)
|
| 366 |
+
# fmt: on
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class Color3DLUT(MultibandFilter):
|
| 370 |
+
"""Three-dimensional color lookup table.
|
| 371 |
+
|
| 372 |
+
Transforms 3-channel pixels using the values of the channels as coordinates
|
| 373 |
+
in the 3D lookup table and interpolating the nearest elements.
|
| 374 |
+
|
| 375 |
+
This method allows you to apply almost any color transformation
|
| 376 |
+
in constant time by using pre-calculated decimated tables.
|
| 377 |
+
|
| 378 |
+
.. versionadded:: 5.2.0
|
| 379 |
+
|
| 380 |
+
:param size: Size of the table. One int or tuple of (int, int, int).
|
| 381 |
+
Minimal size in any dimension is 2, maximum is 65.
|
| 382 |
+
:param table: Flat lookup table. A list of ``channels * size**3``
|
| 383 |
+
float elements or a list of ``size**3`` channels-sized
|
| 384 |
+
tuples with floats. Channels are changed first,
|
| 385 |
+
then first dimension, then second, then third.
|
| 386 |
+
Value 0.0 corresponds lowest value of output, 1.0 highest.
|
| 387 |
+
:param channels: Number of channels in the table. Could be 3 or 4.
|
| 388 |
+
Default is 3.
|
| 389 |
+
:param target_mode: A mode for the result image. Should have not less
|
| 390 |
+
than ``channels`` channels. Default is ``None``,
|
| 391 |
+
which means that mode wouldn't be changed.
|
| 392 |
+
"""
|
| 393 |
+
|
| 394 |
+
name = "Color 3D LUT"
|
| 395 |
+
|
| 396 |
+
def __init__(
|
| 397 |
+
self,
|
| 398 |
+
size: int | tuple[int, int, int],
|
| 399 |
+
table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
|
| 400 |
+
channels: int = 3,
|
| 401 |
+
target_mode: str | None = None,
|
| 402 |
+
**kwargs: bool,
|
| 403 |
+
) -> None:
|
| 404 |
+
if channels not in (3, 4):
|
| 405 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 406 |
+
raise ValueError(msg)
|
| 407 |
+
self.size = size = self._check_size(size)
|
| 408 |
+
self.channels = channels
|
| 409 |
+
self.mode = target_mode
|
| 410 |
+
|
| 411 |
+
# Hidden flag `_copy_table=False` could be used to avoid extra copying
|
| 412 |
+
# of the table if the table is specially made for the constructor.
|
| 413 |
+
copy_table = kwargs.get("_copy_table", True)
|
| 414 |
+
items = size[0] * size[1] * size[2]
|
| 415 |
+
wrong_size = False
|
| 416 |
+
|
| 417 |
+
numpy: ModuleType | None = None
|
| 418 |
+
if hasattr(table, "shape"):
|
| 419 |
+
try:
|
| 420 |
+
import numpy
|
| 421 |
+
except ImportError:
|
| 422 |
+
pass
|
| 423 |
+
|
| 424 |
+
if numpy and isinstance(table, numpy.ndarray):
|
| 425 |
+
numpy_table: NumpyArray = table
|
| 426 |
+
if copy_table:
|
| 427 |
+
numpy_table = numpy_table.copy()
|
| 428 |
+
|
| 429 |
+
if numpy_table.shape in [
|
| 430 |
+
(items * channels,),
|
| 431 |
+
(items, channels),
|
| 432 |
+
(size[2], size[1], size[0], channels),
|
| 433 |
+
]:
|
| 434 |
+
table = numpy_table.reshape(items * channels)
|
| 435 |
+
else:
|
| 436 |
+
wrong_size = True
|
| 437 |
+
|
| 438 |
+
else:
|
| 439 |
+
if copy_table:
|
| 440 |
+
table = list(table)
|
| 441 |
+
|
| 442 |
+
# Convert to a flat list
|
| 443 |
+
if table and isinstance(table[0], (list, tuple)):
|
| 444 |
+
raw_table = cast(Sequence[Sequence[int]], table)
|
| 445 |
+
flat_table: list[int] = []
|
| 446 |
+
for pixel in raw_table:
|
| 447 |
+
if len(pixel) != channels:
|
| 448 |
+
msg = (
|
| 449 |
+
"The elements of the table should "
|
| 450 |
+
f"have a length of {channels}."
|
| 451 |
+
)
|
| 452 |
+
raise ValueError(msg)
|
| 453 |
+
flat_table.extend(pixel)
|
| 454 |
+
table = flat_table
|
| 455 |
+
|
| 456 |
+
if wrong_size or len(table) != items * channels:
|
| 457 |
+
msg = (
|
| 458 |
+
"The table should have either channels * size**3 float items "
|
| 459 |
+
"or size**3 items of channels-sized tuples with floats. "
|
| 460 |
+
f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
|
| 461 |
+
f"Actual length: {len(table)}"
|
| 462 |
+
)
|
| 463 |
+
raise ValueError(msg)
|
| 464 |
+
self.table = table
|
| 465 |
+
|
| 466 |
+
@staticmethod
|
| 467 |
+
def _check_size(size: Any) -> tuple[int, int, int]:
|
| 468 |
+
try:
|
| 469 |
+
_, _, _ = size
|
| 470 |
+
except ValueError as e:
|
| 471 |
+
msg = "Size should be either an integer or a tuple of three integers."
|
| 472 |
+
raise ValueError(msg) from e
|
| 473 |
+
except TypeError:
|
| 474 |
+
size = (size, size, size)
|
| 475 |
+
size = tuple(int(x) for x in size)
|
| 476 |
+
for size_1d in size:
|
| 477 |
+
if not 2 <= size_1d <= 65:
|
| 478 |
+
msg = "Size should be in [2, 65] range."
|
| 479 |
+
raise ValueError(msg)
|
| 480 |
+
return size
|
| 481 |
+
|
| 482 |
+
@classmethod
|
| 483 |
+
def generate(
|
| 484 |
+
cls,
|
| 485 |
+
size: int | tuple[int, int, int],
|
| 486 |
+
callback: Callable[[float, float, float], tuple[float, ...]],
|
| 487 |
+
channels: int = 3,
|
| 488 |
+
target_mode: str | None = None,
|
| 489 |
+
) -> Color3DLUT:
|
| 490 |
+
"""Generates new LUT using provided callback.
|
| 491 |
+
|
| 492 |
+
:param size: Size of the table. Passed to the constructor.
|
| 493 |
+
:param callback: Function with three parameters which correspond
|
| 494 |
+
three color channels. Will be called ``size**3``
|
| 495 |
+
times with values from 0.0 to 1.0 and should return
|
| 496 |
+
a tuple with ``channels`` elements.
|
| 497 |
+
:param channels: The number of channels which should return callback.
|
| 498 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 499 |
+
lookup table.
|
| 500 |
+
"""
|
| 501 |
+
size_1d, size_2d, size_3d = cls._check_size(size)
|
| 502 |
+
if channels not in (3, 4):
|
| 503 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 504 |
+
raise ValueError(msg)
|
| 505 |
+
|
| 506 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
|
| 507 |
+
idx_out = 0
|
| 508 |
+
for b in range(size_3d):
|
| 509 |
+
for g in range(size_2d):
|
| 510 |
+
for r in range(size_1d):
|
| 511 |
+
table[idx_out : idx_out + channels] = callback(
|
| 512 |
+
r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
|
| 513 |
+
)
|
| 514 |
+
idx_out += channels
|
| 515 |
+
|
| 516 |
+
return cls(
|
| 517 |
+
(size_1d, size_2d, size_3d),
|
| 518 |
+
table,
|
| 519 |
+
channels=channels,
|
| 520 |
+
target_mode=target_mode,
|
| 521 |
+
_copy_table=False,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
def transform(
|
| 525 |
+
self,
|
| 526 |
+
callback: Callable[..., tuple[float, ...]],
|
| 527 |
+
with_normals: bool = False,
|
| 528 |
+
channels: int | None = None,
|
| 529 |
+
target_mode: str | None = None,
|
| 530 |
+
) -> Color3DLUT:
|
| 531 |
+
"""Transforms the table values using provided callback and returns
|
| 532 |
+
a new LUT with altered values.
|
| 533 |
+
|
| 534 |
+
:param callback: A function which takes old lookup table values
|
| 535 |
+
and returns a new set of values. The number
|
| 536 |
+
of arguments which function should take is
|
| 537 |
+
``self.channels`` or ``3 + self.channels``
|
| 538 |
+
if ``with_normals`` flag is set.
|
| 539 |
+
Should return a tuple of ``self.channels`` or
|
| 540 |
+
``channels`` elements if it is set.
|
| 541 |
+
:param with_normals: If true, ``callback`` will be called with
|
| 542 |
+
coordinates in the color cube as the first
|
| 543 |
+
three arguments. Otherwise, ``callback``
|
| 544 |
+
will be called only with actual color values.
|
| 545 |
+
:param channels: The number of channels in the resulting lookup table.
|
| 546 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 547 |
+
lookup table.
|
| 548 |
+
"""
|
| 549 |
+
if channels not in (None, 3, 4):
|
| 550 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 551 |
+
raise ValueError(msg)
|
| 552 |
+
ch_in = self.channels
|
| 553 |
+
ch_out = channels or ch_in
|
| 554 |
+
size_1d, size_2d, size_3d = self.size
|
| 555 |
+
|
| 556 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
|
| 557 |
+
idx_in = 0
|
| 558 |
+
idx_out = 0
|
| 559 |
+
for b in range(size_3d):
|
| 560 |
+
for g in range(size_2d):
|
| 561 |
+
for r in range(size_1d):
|
| 562 |
+
values = self.table[idx_in : idx_in + ch_in]
|
| 563 |
+
if with_normals:
|
| 564 |
+
values = callback(
|
| 565 |
+
r / (size_1d - 1),
|
| 566 |
+
g / (size_2d - 1),
|
| 567 |
+
b / (size_3d - 1),
|
| 568 |
+
*values,
|
| 569 |
+
)
|
| 570 |
+
else:
|
| 571 |
+
values = callback(*values)
|
| 572 |
+
table[idx_out : idx_out + ch_out] = values
|
| 573 |
+
idx_in += ch_in
|
| 574 |
+
idx_out += ch_out
|
| 575 |
+
|
| 576 |
+
return type(self)(
|
| 577 |
+
self.size,
|
| 578 |
+
table,
|
| 579 |
+
channels=ch_out,
|
| 580 |
+
target_mode=target_mode or self.mode,
|
| 581 |
+
_copy_table=False,
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
def __repr__(self) -> str:
|
| 585 |
+
r = [
|
| 586 |
+
f"{self.__class__.__name__} from {self.table.__class__.__name__}",
|
| 587 |
+
"size={:d}x{:d}x{:d}".format(*self.size),
|
| 588 |
+
f"channels={self.channels:d}",
|
| 589 |
+
]
|
| 590 |
+
if self.mode:
|
| 591 |
+
r.append(f"target_mode={self.mode}")
|
| 592 |
+
return "<{}>".format(" ".join(r))
|
| 593 |
+
|
| 594 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 595 |
+
from . import Image
|
| 596 |
+
|
| 597 |
+
return image.color_lut_3d(
|
| 598 |
+
self.mode or image.mode,
|
| 599 |
+
Image.Resampling.BILINEAR,
|
| 600 |
+
self.channels,
|
| 601 |
+
self.size[0],
|
| 602 |
+
self.size[1],
|
| 603 |
+
self.size[2],
|
| 604 |
+
self.table,
|
| 605 |
+
)
|
lib/python3.10/site-packages/PIL/ImageGrab.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# screen grabber
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2001-04-26 fl created
|
| 9 |
+
# 2001-09-17 fl use builtin driver, if present
|
| 10 |
+
# 2002-11-19 fl added grabclipboard support
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 2001-2002 by Secret Labs AB
|
| 13 |
+
# Copyright (c) 2001-2002 by Fredrik Lundh
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import io
|
| 20 |
+
import os
|
| 21 |
+
import shutil
|
| 22 |
+
import subprocess
|
| 23 |
+
import sys
|
| 24 |
+
import tempfile
|
| 25 |
+
|
| 26 |
+
from . import Image
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def grab(
|
| 30 |
+
bbox: tuple[int, int, int, int] | None = None,
|
| 31 |
+
include_layered_windows: bool = False,
|
| 32 |
+
all_screens: bool = False,
|
| 33 |
+
xdisplay: str | None = None,
|
| 34 |
+
) -> Image.Image:
|
| 35 |
+
im: Image.Image
|
| 36 |
+
if xdisplay is None:
|
| 37 |
+
if sys.platform == "darwin":
|
| 38 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 39 |
+
os.close(fh)
|
| 40 |
+
args = ["screencapture"]
|
| 41 |
+
if bbox:
|
| 42 |
+
left, top, right, bottom = bbox
|
| 43 |
+
args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
|
| 44 |
+
subprocess.call(args + ["-x", filepath])
|
| 45 |
+
im = Image.open(filepath)
|
| 46 |
+
im.load()
|
| 47 |
+
os.unlink(filepath)
|
| 48 |
+
if bbox:
|
| 49 |
+
im_resized = im.resize((right - left, bottom - top))
|
| 50 |
+
im.close()
|
| 51 |
+
return im_resized
|
| 52 |
+
return im
|
| 53 |
+
elif sys.platform == "win32":
|
| 54 |
+
offset, size, data = Image.core.grabscreen_win32(
|
| 55 |
+
include_layered_windows, all_screens
|
| 56 |
+
)
|
| 57 |
+
im = Image.frombytes(
|
| 58 |
+
"RGB",
|
| 59 |
+
size,
|
| 60 |
+
data,
|
| 61 |
+
# RGB, 32-bit line padding, origin lower left corner
|
| 62 |
+
"raw",
|
| 63 |
+
"BGR",
|
| 64 |
+
(size[0] * 3 + 3) & -4,
|
| 65 |
+
-1,
|
| 66 |
+
)
|
| 67 |
+
if bbox:
|
| 68 |
+
x0, y0 = offset
|
| 69 |
+
left, top, right, bottom = bbox
|
| 70 |
+
im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
|
| 71 |
+
return im
|
| 72 |
+
# Cast to Optional[str] needed for Windows and macOS.
|
| 73 |
+
display_name: str | None = xdisplay
|
| 74 |
+
try:
|
| 75 |
+
if not Image.core.HAVE_XCB:
|
| 76 |
+
msg = "Pillow was built without XCB support"
|
| 77 |
+
raise OSError(msg)
|
| 78 |
+
size, data = Image.core.grabscreen_x11(display_name)
|
| 79 |
+
except OSError:
|
| 80 |
+
if (
|
| 81 |
+
display_name is None
|
| 82 |
+
and sys.platform not in ("darwin", "win32")
|
| 83 |
+
and shutil.which("gnome-screenshot")
|
| 84 |
+
):
|
| 85 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 86 |
+
os.close(fh)
|
| 87 |
+
subprocess.call(["gnome-screenshot", "-f", filepath])
|
| 88 |
+
im = Image.open(filepath)
|
| 89 |
+
im.load()
|
| 90 |
+
os.unlink(filepath)
|
| 91 |
+
if bbox:
|
| 92 |
+
im_cropped = im.crop(bbox)
|
| 93 |
+
im.close()
|
| 94 |
+
return im_cropped
|
| 95 |
+
return im
|
| 96 |
+
else:
|
| 97 |
+
raise
|
| 98 |
+
else:
|
| 99 |
+
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
|
| 100 |
+
if bbox:
|
| 101 |
+
im = im.crop(bbox)
|
| 102 |
+
return im
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def grabclipboard() -> Image.Image | list[str] | None:
|
| 106 |
+
if sys.platform == "darwin":
|
| 107 |
+
p = subprocess.run(
|
| 108 |
+
["osascript", "-e", "get the clipboard as «class PNGf»"],
|
| 109 |
+
capture_output=True,
|
| 110 |
+
)
|
| 111 |
+
if p.returncode != 0:
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
import binascii
|
| 115 |
+
|
| 116 |
+
data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
|
| 117 |
+
return Image.open(data)
|
| 118 |
+
elif sys.platform == "win32":
|
| 119 |
+
fmt, data = Image.core.grabclipboard_win32()
|
| 120 |
+
if fmt == "file": # CF_HDROP
|
| 121 |
+
import struct
|
| 122 |
+
|
| 123 |
+
o = struct.unpack_from("I", data)[0]
|
| 124 |
+
if data[16] != 0:
|
| 125 |
+
files = data[o:].decode("utf-16le").split("\0")
|
| 126 |
+
else:
|
| 127 |
+
files = data[o:].decode("mbcs").split("\0")
|
| 128 |
+
return files[: files.index("")]
|
| 129 |
+
if isinstance(data, bytes):
|
| 130 |
+
data = io.BytesIO(data)
|
| 131 |
+
if fmt == "png":
|
| 132 |
+
from . import PngImagePlugin
|
| 133 |
+
|
| 134 |
+
return PngImagePlugin.PngImageFile(data)
|
| 135 |
+
elif fmt == "DIB":
|
| 136 |
+
from . import BmpImagePlugin
|
| 137 |
+
|
| 138 |
+
return BmpImagePlugin.DibImageFile(data)
|
| 139 |
+
return None
|
| 140 |
+
else:
|
| 141 |
+
if os.getenv("WAYLAND_DISPLAY"):
|
| 142 |
+
session_type = "wayland"
|
| 143 |
+
elif os.getenv("DISPLAY"):
|
| 144 |
+
session_type = "x11"
|
| 145 |
+
else: # Session type check failed
|
| 146 |
+
session_type = None
|
| 147 |
+
|
| 148 |
+
if shutil.which("wl-paste") and session_type in ("wayland", None):
|
| 149 |
+
args = ["wl-paste", "-t", "image"]
|
| 150 |
+
elif shutil.which("xclip") and session_type in ("x11", None):
|
| 151 |
+
args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
|
| 152 |
+
else:
|
| 153 |
+
msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
|
| 154 |
+
raise NotImplementedError(msg)
|
| 155 |
+
|
| 156 |
+
p = subprocess.run(args, capture_output=True)
|
| 157 |
+
if p.returncode != 0:
|
| 158 |
+
err = p.stderr
|
| 159 |
+
for silent_error in [
|
| 160 |
+
# wl-paste, when the clipboard is empty
|
| 161 |
+
b"Nothing is copied",
|
| 162 |
+
# Ubuntu/Debian wl-paste, when the clipboard is empty
|
| 163 |
+
b"No selection",
|
| 164 |
+
# Ubuntu/Debian wl-paste, when an image isn't available
|
| 165 |
+
b"No suitable type of content copied",
|
| 166 |
+
# wl-paste or Ubuntu/Debian xclip, when an image isn't available
|
| 167 |
+
b" not available",
|
| 168 |
+
# xclip, when an image isn't available
|
| 169 |
+
b"cannot convert ",
|
| 170 |
+
# xclip, when the clipboard isn't initialized
|
| 171 |
+
b"xclip: Error: There is no owner for the ",
|
| 172 |
+
]:
|
| 173 |
+
if silent_error in err:
|
| 174 |
+
return None
|
| 175 |
+
msg = f"{args[0]} error"
|
| 176 |
+
if err:
|
| 177 |
+
msg += f": {err.strip().decode()}"
|
| 178 |
+
raise ChildProcessError(msg)
|
| 179 |
+
|
| 180 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A binary morphology add-on for the Python Imaging Library
|
| 2 |
+
#
|
| 3 |
+
# History:
|
| 4 |
+
# 2014-06-04 Initial version.
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
from . import Image, _imagingmorph
|
| 12 |
+
|
| 13 |
+
LUT_SIZE = 1 << 9
|
| 14 |
+
|
| 15 |
+
# fmt: off
|
| 16 |
+
ROTATION_MATRIX = [
|
| 17 |
+
6, 3, 0,
|
| 18 |
+
7, 4, 1,
|
| 19 |
+
8, 5, 2,
|
| 20 |
+
]
|
| 21 |
+
MIRROR_MATRIX = [
|
| 22 |
+
2, 1, 0,
|
| 23 |
+
5, 4, 3,
|
| 24 |
+
8, 7, 6,
|
| 25 |
+
]
|
| 26 |
+
# fmt: on
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class LutBuilder:
|
| 30 |
+
"""A class for building a MorphLut from a descriptive language
|
| 31 |
+
|
| 32 |
+
The input patterns is a list of a strings sequences like these::
|
| 33 |
+
|
| 34 |
+
4:(...
|
| 35 |
+
.1.
|
| 36 |
+
111)->1
|
| 37 |
+
|
| 38 |
+
(whitespaces including linebreaks are ignored). The option 4
|
| 39 |
+
describes a series of symmetry operations (in this case a
|
| 40 |
+
4-rotation), the pattern is described by:
|
| 41 |
+
|
| 42 |
+
- . or X - Ignore
|
| 43 |
+
- 1 - Pixel is on
|
| 44 |
+
- 0 - Pixel is off
|
| 45 |
+
|
| 46 |
+
The result of the operation is described after "->" string.
|
| 47 |
+
|
| 48 |
+
The default is to return the current pixel value, which is
|
| 49 |
+
returned if no other match is found.
|
| 50 |
+
|
| 51 |
+
Operations:
|
| 52 |
+
|
| 53 |
+
- 4 - 4 way rotation
|
| 54 |
+
- N - Negate
|
| 55 |
+
- 1 - Dummy op for no other operation (an op must always be given)
|
| 56 |
+
- M - Mirroring
|
| 57 |
+
|
| 58 |
+
Example::
|
| 59 |
+
|
| 60 |
+
lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
|
| 61 |
+
lut = lb.build_lut()
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self, patterns: list[str] | None = None, op_name: str | None = None
|
| 67 |
+
) -> None:
|
| 68 |
+
if patterns is not None:
|
| 69 |
+
self.patterns = patterns
|
| 70 |
+
else:
|
| 71 |
+
self.patterns = []
|
| 72 |
+
self.lut: bytearray | None = None
|
| 73 |
+
if op_name is not None:
|
| 74 |
+
known_patterns = {
|
| 75 |
+
"corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
|
| 76 |
+
"dilation4": ["4:(... .0. .1.)->1"],
|
| 77 |
+
"dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
|
| 78 |
+
"erosion4": ["4:(... .1. .0.)->0"],
|
| 79 |
+
"erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
|
| 80 |
+
"edge": [
|
| 81 |
+
"1:(... ... ...)->0",
|
| 82 |
+
"4:(.0. .1. ...)->1",
|
| 83 |
+
"4:(01. .1. ...)->1",
|
| 84 |
+
],
|
| 85 |
+
}
|
| 86 |
+
if op_name not in known_patterns:
|
| 87 |
+
msg = f"Unknown pattern {op_name}!"
|
| 88 |
+
raise Exception(msg)
|
| 89 |
+
|
| 90 |
+
self.patterns = known_patterns[op_name]
|
| 91 |
+
|
| 92 |
+
def add_patterns(self, patterns: list[str]) -> None:
|
| 93 |
+
self.patterns += patterns
|
| 94 |
+
|
| 95 |
+
def build_default_lut(self) -> None:
|
| 96 |
+
symbols = [0, 1]
|
| 97 |
+
m = 1 << 4 # pos of current pixel
|
| 98 |
+
self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
|
| 99 |
+
|
| 100 |
+
def get_lut(self) -> bytearray | None:
|
| 101 |
+
return self.lut
|
| 102 |
+
|
| 103 |
+
def _string_permute(self, pattern: str, permutation: list[int]) -> str:
|
| 104 |
+
"""string_permute takes a pattern and a permutation and returns the
|
| 105 |
+
string permuted according to the permutation list.
|
| 106 |
+
"""
|
| 107 |
+
assert len(permutation) == 9
|
| 108 |
+
return "".join(pattern[p] for p in permutation)
|
| 109 |
+
|
| 110 |
+
def _pattern_permute(
|
| 111 |
+
self, basic_pattern: str, options: str, basic_result: int
|
| 112 |
+
) -> list[tuple[str, int]]:
|
| 113 |
+
"""pattern_permute takes a basic pattern and its result and clones
|
| 114 |
+
the pattern according to the modifications described in the $options
|
| 115 |
+
parameter. It returns a list of all cloned patterns."""
|
| 116 |
+
patterns = [(basic_pattern, basic_result)]
|
| 117 |
+
|
| 118 |
+
# rotations
|
| 119 |
+
if "4" in options:
|
| 120 |
+
res = patterns[-1][1]
|
| 121 |
+
for i in range(4):
|
| 122 |
+
patterns.append(
|
| 123 |
+
(self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
|
| 124 |
+
)
|
| 125 |
+
# mirror
|
| 126 |
+
if "M" in options:
|
| 127 |
+
n = len(patterns)
|
| 128 |
+
for pattern, res in patterns[:n]:
|
| 129 |
+
patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
|
| 130 |
+
|
| 131 |
+
# negate
|
| 132 |
+
if "N" in options:
|
| 133 |
+
n = len(patterns)
|
| 134 |
+
for pattern, res in patterns[:n]:
|
| 135 |
+
# Swap 0 and 1
|
| 136 |
+
pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
|
| 137 |
+
res = 1 - int(res)
|
| 138 |
+
patterns.append((pattern, res))
|
| 139 |
+
|
| 140 |
+
return patterns
|
| 141 |
+
|
| 142 |
+
def build_lut(self) -> bytearray:
|
| 143 |
+
"""Compile all patterns into a morphology lut.
|
| 144 |
+
|
| 145 |
+
TBD :Build based on (file) morphlut:modify_lut
|
| 146 |
+
"""
|
| 147 |
+
self.build_default_lut()
|
| 148 |
+
assert self.lut is not None
|
| 149 |
+
patterns = []
|
| 150 |
+
|
| 151 |
+
# Parse and create symmetries of the patterns strings
|
| 152 |
+
for p in self.patterns:
|
| 153 |
+
m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
|
| 154 |
+
if not m:
|
| 155 |
+
msg = 'Syntax error in pattern "' + p + '"'
|
| 156 |
+
raise Exception(msg)
|
| 157 |
+
options = m.group(1)
|
| 158 |
+
pattern = m.group(2)
|
| 159 |
+
result = int(m.group(3))
|
| 160 |
+
|
| 161 |
+
# Get rid of spaces
|
| 162 |
+
pattern = pattern.replace(" ", "").replace("\n", "")
|
| 163 |
+
|
| 164 |
+
patterns += self._pattern_permute(pattern, options, result)
|
| 165 |
+
|
| 166 |
+
# compile the patterns into regular expressions for speed
|
| 167 |
+
compiled_patterns = []
|
| 168 |
+
for pattern in patterns:
|
| 169 |
+
p = pattern[0].replace(".", "X").replace("X", "[01]")
|
| 170 |
+
compiled_patterns.append((re.compile(p), pattern[1]))
|
| 171 |
+
|
| 172 |
+
# Step through table and find patterns that match.
|
| 173 |
+
# Note that all the patterns are searched. The last one
|
| 174 |
+
# caught overrides
|
| 175 |
+
for i in range(LUT_SIZE):
|
| 176 |
+
# Build the bit pattern
|
| 177 |
+
bitpattern = bin(i)[2:]
|
| 178 |
+
bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
|
| 179 |
+
|
| 180 |
+
for pattern, r in compiled_patterns:
|
| 181 |
+
if pattern.match(bitpattern):
|
| 182 |
+
self.lut[i] = [0, 1][r]
|
| 183 |
+
|
| 184 |
+
return self.lut
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class MorphOp:
|
| 188 |
+
"""A class for binary morphological operators"""
|
| 189 |
+
|
| 190 |
+
def __init__(
|
| 191 |
+
self,
|
| 192 |
+
lut: bytearray | None = None,
|
| 193 |
+
op_name: str | None = None,
|
| 194 |
+
patterns: list[str] | None = None,
|
| 195 |
+
) -> None:
|
| 196 |
+
"""Create a binary morphological operator"""
|
| 197 |
+
self.lut = lut
|
| 198 |
+
if op_name is not None:
|
| 199 |
+
self.lut = LutBuilder(op_name=op_name).build_lut()
|
| 200 |
+
elif patterns is not None:
|
| 201 |
+
self.lut = LutBuilder(patterns=patterns).build_lut()
|
| 202 |
+
|
| 203 |
+
def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
|
| 204 |
+
"""Run a single morphological operation on an image
|
| 205 |
+
|
| 206 |
+
Returns a tuple of the number of changed pixels and the
|
| 207 |
+
morphed image"""
|
| 208 |
+
if self.lut is None:
|
| 209 |
+
msg = "No operator loaded"
|
| 210 |
+
raise Exception(msg)
|
| 211 |
+
|
| 212 |
+
if image.mode != "L":
|
| 213 |
+
msg = "Image mode must be L"
|
| 214 |
+
raise ValueError(msg)
|
| 215 |
+
outimage = Image.new(image.mode, image.size, None)
|
| 216 |
+
count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim())
|
| 217 |
+
return count, outimage
|
| 218 |
+
|
| 219 |
+
def match(self, image: Image.Image) -> list[tuple[int, int]]:
|
| 220 |
+
"""Get a list of coordinates matching the morphological operation on
|
| 221 |
+
an image.
|
| 222 |
+
|
| 223 |
+
Returns a list of tuples of (x,y) coordinates
|
| 224 |
+
of all matching pixels. See :ref:`coordinate-system`."""
|
| 225 |
+
if self.lut is None:
|
| 226 |
+
msg = "No operator loaded"
|
| 227 |
+
raise Exception(msg)
|
| 228 |
+
|
| 229 |
+
if image.mode != "L":
|
| 230 |
+
msg = "Image mode must be L"
|
| 231 |
+
raise ValueError(msg)
|
| 232 |
+
return _imagingmorph.match(bytes(self.lut), image.getim())
|
| 233 |
+
|
| 234 |
+
def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
|
| 235 |
+
"""Get a list of all turned on pixels in a binary image
|
| 236 |
+
|
| 237 |
+
Returns a list of tuples of (x,y) coordinates
|
| 238 |
+
of all matching pixels. See :ref:`coordinate-system`."""
|
| 239 |
+
|
| 240 |
+
if image.mode != "L":
|
| 241 |
+
msg = "Image mode must be L"
|
| 242 |
+
raise ValueError(msg)
|
| 243 |
+
return _imagingmorph.get_on_pixels(image.getim())
|
| 244 |
+
|
| 245 |
+
def load_lut(self, filename: str) -> None:
|
| 246 |
+
"""Load an operator from an mrl file"""
|
| 247 |
+
with open(filename, "rb") as f:
|
| 248 |
+
self.lut = bytearray(f.read())
|
| 249 |
+
|
| 250 |
+
if len(self.lut) != LUT_SIZE:
|
| 251 |
+
self.lut = None
|
| 252 |
+
msg = "Wrong size operator file!"
|
| 253 |
+
raise Exception(msg)
|
| 254 |
+
|
| 255 |
+
def save_lut(self, filename: str) -> None:
|
| 256 |
+
"""Save an operator to an mrl file"""
|
| 257 |
+
if self.lut is None:
|
| 258 |
+
msg = "No operator loaded"
|
| 259 |
+
raise Exception(msg)
|
| 260 |
+
with open(filename, "wb") as f:
|
| 261 |
+
f.write(self.lut)
|
| 262 |
+
|
| 263 |
+
def set_lut(self, lut: bytearray | None) -> None:
|
| 264 |
+
"""Set the lut from an external source"""
|
| 265 |
+
self.lut = lut
|
lib/python3.10/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
|
lib/python3.10/site-packages/PIL/ImageShow.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
# 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 |
+
executable = sys.executable or shutil.which("python3")
|
| 179 |
+
if executable:
|
| 180 |
+
subprocess.Popen(
|
| 181 |
+
[
|
| 182 |
+
executable,
|
| 183 |
+
"-c",
|
| 184 |
+
"import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
|
| 185 |
+
path,
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
return 1
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if sys.platform == "darwin":
|
| 192 |
+
register(MacViewer)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class UnixViewer(Viewer):
|
| 196 |
+
format = "PNG"
|
| 197 |
+
options = {"compress_level": 1, "save_all": True}
|
| 198 |
+
|
| 199 |
+
@abc.abstractmethod
|
| 200 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 204 |
+
command = self.get_command_ex(file, **options)[0]
|
| 205 |
+
return f"{command} {quote(file)}"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class XDGViewer(UnixViewer):
|
| 209 |
+
"""
|
| 210 |
+
The freedesktop.org ``xdg-open`` command.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 214 |
+
command = executable = "xdg-open"
|
| 215 |
+
return command, executable
|
| 216 |
+
|
| 217 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 218 |
+
"""
|
| 219 |
+
Display given file.
|
| 220 |
+
"""
|
| 221 |
+
if not os.path.exists(path):
|
| 222 |
+
raise FileNotFoundError
|
| 223 |
+
subprocess.Popen(["xdg-open", path])
|
| 224 |
+
return 1
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class DisplayViewer(UnixViewer):
|
| 228 |
+
"""
|
| 229 |
+
The ImageMagick ``display`` command.
|
| 230 |
+
This viewer supports the ``title`` parameter.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
def get_command_ex(
|
| 234 |
+
self, file: str, title: str | None = None, **options: Any
|
| 235 |
+
) -> tuple[str, str]:
|
| 236 |
+
command = executable = "display"
|
| 237 |
+
if title:
|
| 238 |
+
command += f" -title {quote(title)}"
|
| 239 |
+
return command, executable
|
| 240 |
+
|
| 241 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 242 |
+
"""
|
| 243 |
+
Display given file.
|
| 244 |
+
"""
|
| 245 |
+
if not os.path.exists(path):
|
| 246 |
+
raise FileNotFoundError
|
| 247 |
+
args = ["display"]
|
| 248 |
+
title = options.get("title")
|
| 249 |
+
if title:
|
| 250 |
+
args += ["-title", title]
|
| 251 |
+
args.append(path)
|
| 252 |
+
|
| 253 |
+
subprocess.Popen(args)
|
| 254 |
+
return 1
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class GmDisplayViewer(UnixViewer):
|
| 258 |
+
"""The GraphicsMagick ``gm display`` command."""
|
| 259 |
+
|
| 260 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 261 |
+
executable = "gm"
|
| 262 |
+
command = "gm display"
|
| 263 |
+
return command, executable
|
| 264 |
+
|
| 265 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 266 |
+
"""
|
| 267 |
+
Display given file.
|
| 268 |
+
"""
|
| 269 |
+
if not os.path.exists(path):
|
| 270 |
+
raise FileNotFoundError
|
| 271 |
+
subprocess.Popen(["gm", "display", path])
|
| 272 |
+
return 1
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class EogViewer(UnixViewer):
|
| 276 |
+
"""The GNOME Image Viewer ``eog`` command."""
|
| 277 |
+
|
| 278 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 279 |
+
executable = "eog"
|
| 280 |
+
command = "eog -n"
|
| 281 |
+
return command, executable
|
| 282 |
+
|
| 283 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 284 |
+
"""
|
| 285 |
+
Display given file.
|
| 286 |
+
"""
|
| 287 |
+
if not os.path.exists(path):
|
| 288 |
+
raise FileNotFoundError
|
| 289 |
+
subprocess.Popen(["eog", "-n", path])
|
| 290 |
+
return 1
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class XVViewer(UnixViewer):
|
| 294 |
+
"""
|
| 295 |
+
The X Viewer ``xv`` command.
|
| 296 |
+
This viewer supports the ``title`` parameter.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
def get_command_ex(
|
| 300 |
+
self, file: str, title: str | None = None, **options: Any
|
| 301 |
+
) -> tuple[str, str]:
|
| 302 |
+
# note: xv is pretty outdated. most modern systems have
|
| 303 |
+
# imagemagick's display command instead.
|
| 304 |
+
command = executable = "xv"
|
| 305 |
+
if title:
|
| 306 |
+
command += f" -name {quote(title)}"
|
| 307 |
+
return command, executable
|
| 308 |
+
|
| 309 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 310 |
+
"""
|
| 311 |
+
Display given file.
|
| 312 |
+
"""
|
| 313 |
+
if not os.path.exists(path):
|
| 314 |
+
raise FileNotFoundError
|
| 315 |
+
args = ["xv"]
|
| 316 |
+
title = options.get("title")
|
| 317 |
+
if title:
|
| 318 |
+
args += ["-name", title]
|
| 319 |
+
args.append(path)
|
| 320 |
+
|
| 321 |
+
subprocess.Popen(args)
|
| 322 |
+
return 1
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if sys.platform not in ("win32", "darwin"): # unixoids
|
| 326 |
+
if shutil.which("xdg-open"):
|
| 327 |
+
register(XDGViewer)
|
| 328 |
+
if shutil.which("display"):
|
| 329 |
+
register(DisplayViewer)
|
| 330 |
+
if shutil.which("gm"):
|
| 331 |
+
register(GmDisplayViewer)
|
| 332 |
+
if shutil.which("eog"):
|
| 333 |
+
register(EogViewer)
|
| 334 |
+
if shutil.which("xv"):
|
| 335 |
+
register(XVViewer)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class IPythonViewer(Viewer):
|
| 339 |
+
"""The viewer for IPython frontends."""
|
| 340 |
+
|
| 341 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
| 342 |
+
ipython_display(image)
|
| 343 |
+
return 1
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
try:
|
| 347 |
+
from IPython.display import display as ipython_display
|
| 348 |
+
except ImportError:
|
| 349 |
+
pass
|
| 350 |
+
else:
|
| 351 |
+
register(IPythonViewer)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
if __name__ == "__main__":
|
| 355 |
+
if len(sys.argv) < 2:
|
| 356 |
+
print("Syntax: python3 ImageShow.py imagefile [title]")
|
| 357 |
+
sys.exit()
|
| 358 |
+
|
| 359 |
+
with Image.open(sys.argv[1]) as im:
|
| 360 |
+
print(show(im, *sys.argv[2:]))
|
lib/python3.10/site-packages/PIL/McIdasImagePlugin.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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[:8] == 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] + list(struct.unpack("!64i", s))
|
| 48 |
+
|
| 49 |
+
# get mode
|
| 50 |
+
if w[11] == 1:
|
| 51 |
+
mode = rawmode = "L"
|
| 52 |
+
elif w[11] == 2:
|
| 53 |
+
# FIXME: add memory map support
|
| 54 |
+
mode = "I"
|
| 55 |
+
rawmode = "I;16B"
|
| 56 |
+
elif w[11] == 4:
|
| 57 |
+
# FIXME: add memory map support
|
| 58 |
+
mode = "I"
|
| 59 |
+
rawmode = "I;32B"
|
| 60 |
+
else:
|
| 61 |
+
msg = "unsupported McIdas format"
|
| 62 |
+
raise SyntaxError(msg)
|
| 63 |
+
|
| 64 |
+
self._mode = mode
|
| 65 |
+
self._size = w[10], w[9]
|
| 66 |
+
|
| 67 |
+
offset = w[34] + w[15]
|
| 68 |
+
stride = w[15] + w[10] * w[11] * w[14]
|
| 69 |
+
|
| 70 |
+
self.tile = [
|
| 71 |
+
ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# --------------------------------------------------------------------
|
| 76 |
+
# registry
|
| 77 |
+
|
| 78 |
+
Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept)
|
| 79 |
+
|
| 80 |
+
# no default extension
|
lib/python3.10/site-packages/PIL/MicImagePlugin.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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[:8] == 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][-4:] == ".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 |
+
self.__fp = self.fp
|
| 71 |
+
self.seek(0)
|
| 72 |
+
|
| 73 |
+
def seek(self, frame: int) -> None:
|
| 74 |
+
if not self._seek_check(frame):
|
| 75 |
+
return
|
| 76 |
+
try:
|
| 77 |
+
filename = self.images[frame]
|
| 78 |
+
except IndexError as e:
|
| 79 |
+
msg = "no such frame"
|
| 80 |
+
raise EOFError(msg) from e
|
| 81 |
+
|
| 82 |
+
self.fp = self.ole.openstream(filename)
|
| 83 |
+
|
| 84 |
+
TiffImagePlugin.TiffImageFile._open(self)
|
| 85 |
+
|
| 86 |
+
self.frame = frame
|
| 87 |
+
|
| 88 |
+
def tell(self) -> int:
|
| 89 |
+
return self.frame
|
| 90 |
+
|
| 91 |
+
def close(self) -> None:
|
| 92 |
+
self.__fp.close()
|
| 93 |
+
self.ole.close()
|
| 94 |
+
super().close()
|
| 95 |
+
|
| 96 |
+
def __exit__(self, *args: object) -> None:
|
| 97 |
+
self.__fp.close()
|
| 98 |
+
self.ole.close()
|
| 99 |
+
super().__exit__()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
#
|
| 103 |
+
# --------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
Image.register_open(MicImageFile.format, MicImageFile, _accept)
|
| 106 |
+
|
| 107 |
+
Image.register_extension(MicImageFile.format, ".mic")
|
lib/python3.10/site-packages/PIL/MpoImagePlugin.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# MPO file handling
|
| 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 itertools
|
| 23 |
+
import os
|
| 24 |
+
import struct
|
| 25 |
+
from typing import IO, Any, cast
|
| 26 |
+
|
| 27 |
+
from . import (
|
| 28 |
+
Image,
|
| 29 |
+
ImageFile,
|
| 30 |
+
ImageSequence,
|
| 31 |
+
JpegImagePlugin,
|
| 32 |
+
TiffImagePlugin,
|
| 33 |
+
)
|
| 34 |
+
from ._binary import o32le
|
| 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 |
+
for imSequence in itertools.chain([im], append_images):
|
| 50 |
+
for im_frame in ImageSequence.Iterator(imSequence):
|
| 51 |
+
if not offsets:
|
| 52 |
+
# APP2 marker
|
| 53 |
+
im_frame.encoderinfo["extra"] = (
|
| 54 |
+
b"\xFF\xE2" + struct.pack(">H", 6 + 82) + b"MPF\0" + b" " * 82
|
| 55 |
+
)
|
| 56 |
+
exif = im_frame.encoderinfo.get("exif")
|
| 57 |
+
if isinstance(exif, Image.Exif):
|
| 58 |
+
exif = exif.tobytes()
|
| 59 |
+
im_frame.encoderinfo["exif"] = exif
|
| 60 |
+
if exif:
|
| 61 |
+
mpf_offset += 4 + len(exif)
|
| 62 |
+
|
| 63 |
+
JpegImagePlugin._save(im_frame, fp, filename)
|
| 64 |
+
offsets.append(fp.tell())
|
| 65 |
+
else:
|
| 66 |
+
im_frame.save(fp, "JPEG")
|
| 67 |
+
offsets.append(fp.tell() - offsets[-1])
|
| 68 |
+
|
| 69 |
+
ifd = TiffImagePlugin.ImageFileDirectory_v2()
|
| 70 |
+
ifd[0xB000] = b"0100"
|
| 71 |
+
ifd[0xB001] = len(offsets)
|
| 72 |
+
|
| 73 |
+
mpentries = b""
|
| 74 |
+
data_offset = 0
|
| 75 |
+
for i, size in enumerate(offsets):
|
| 76 |
+
if i == 0:
|
| 77 |
+
mptype = 0x030000 # Baseline MP Primary Image
|
| 78 |
+
else:
|
| 79 |
+
mptype = 0x000000 # Undefined
|
| 80 |
+
mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)
|
| 81 |
+
if i == 0:
|
| 82 |
+
data_offset -= mpf_offset
|
| 83 |
+
data_offset += size
|
| 84 |
+
ifd[0xB002] = mpentries
|
| 85 |
+
|
| 86 |
+
fp.seek(mpf_offset)
|
| 87 |
+
fp.write(b"II\x2A\x00" + o32le(8) + ifd.tobytes(8))
|
| 88 |
+
fp.seek(0, os.SEEK_END)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
##
|
| 92 |
+
# Image plugin for MPO images.
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class MpoImageFile(JpegImagePlugin.JpegImageFile):
|
| 96 |
+
format = "MPO"
|
| 97 |
+
format_description = "MPO (CIPA DC-007)"
|
| 98 |
+
_close_exclusive_fp_after_loading = False
|
| 99 |
+
|
| 100 |
+
def _open(self) -> None:
|
| 101 |
+
self.fp.seek(0) # prep the fp in order to pass the JPEG test
|
| 102 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 103 |
+
self._after_jpeg_open()
|
| 104 |
+
|
| 105 |
+
def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:
|
| 106 |
+
self.mpinfo = mpheader if mpheader is not None else self._getmp()
|
| 107 |
+
if self.mpinfo is None:
|
| 108 |
+
msg = "Image appears to be a malformed MPO file"
|
| 109 |
+
raise ValueError(msg)
|
| 110 |
+
self.n_frames = self.mpinfo[0xB001]
|
| 111 |
+
self.__mpoffsets = [
|
| 112 |
+
mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
|
| 113 |
+
]
|
| 114 |
+
self.__mpoffsets[0] = 0
|
| 115 |
+
# Note that the following assertion will only be invalid if something
|
| 116 |
+
# gets broken within JpegImagePlugin.
|
| 117 |
+
assert self.n_frames == len(self.__mpoffsets)
|
| 118 |
+
del self.info["mpoffset"] # no longer needed
|
| 119 |
+
self.is_animated = self.n_frames > 1
|
| 120 |
+
self._fp = self.fp # FIXME: hack
|
| 121 |
+
self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
|
| 122 |
+
self.__frame = 0
|
| 123 |
+
self.offset = 0
|
| 124 |
+
# for now we can only handle reading and individual frame extraction
|
| 125 |
+
self.readonly = 1
|
| 126 |
+
|
| 127 |
+
def load_seek(self, pos: int) -> None:
|
| 128 |
+
self._fp.seek(pos)
|
| 129 |
+
|
| 130 |
+
def seek(self, frame: int) -> None:
|
| 131 |
+
if not self._seek_check(frame):
|
| 132 |
+
return
|
| 133 |
+
self.fp = self._fp
|
| 134 |
+
self.offset = self.__mpoffsets[frame]
|
| 135 |
+
|
| 136 |
+
original_exif = self.info.get("exif")
|
| 137 |
+
if "exif" in self.info:
|
| 138 |
+
del self.info["exif"]
|
| 139 |
+
|
| 140 |
+
self.fp.seek(self.offset + 2) # skip SOI marker
|
| 141 |
+
if not self.fp.read(2):
|
| 142 |
+
msg = "No data found for frame"
|
| 143 |
+
raise ValueError(msg)
|
| 144 |
+
self.fp.seek(self.offset)
|
| 145 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 146 |
+
if self.info.get("exif") != original_exif:
|
| 147 |
+
self._reload_exif()
|
| 148 |
+
|
| 149 |
+
self.tile = [
|
| 150 |
+
ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])
|
| 151 |
+
]
|
| 152 |
+
self.__frame = frame
|
| 153 |
+
|
| 154 |
+
def tell(self) -> int:
|
| 155 |
+
return self.__frame
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def adopt(
|
| 159 |
+
jpeg_instance: JpegImagePlugin.JpegImageFile,
|
| 160 |
+
mpheader: dict[int, Any] | None = None,
|
| 161 |
+
) -> MpoImageFile:
|
| 162 |
+
"""
|
| 163 |
+
Transform the instance of JpegImageFile into
|
| 164 |
+
an instance of MpoImageFile.
|
| 165 |
+
After the call, the JpegImageFile is extended
|
| 166 |
+
to be an MpoImageFile.
|
| 167 |
+
|
| 168 |
+
This is essentially useful when opening a JPEG
|
| 169 |
+
file that reveals itself as an MPO, to avoid
|
| 170 |
+
double call to _open.
|
| 171 |
+
"""
|
| 172 |
+
jpeg_instance.__class__ = MpoImageFile
|
| 173 |
+
mpo_instance = cast(MpoImageFile, jpeg_instance)
|
| 174 |
+
mpo_instance._after_jpeg_open(mpheader)
|
| 175 |
+
return mpo_instance
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# ---------------------------------------------------------------------
|
| 179 |
+
# Registry stuff
|
| 180 |
+
|
| 181 |
+
# Note that since MPO shares a factory with JPEG, we do not need to do a
|
| 182 |
+
# separate registration for it here.
|
| 183 |
+
# Image.register_open(MpoImageFile.format,
|
| 184 |
+
# JpegImagePlugin.jpeg_factory, _accept)
|
| 185 |
+
Image.register_save(MpoImageFile.format, _save)
|
| 186 |
+
Image.register_save_all(MpoImageFile.format, _save_all)
|
| 187 |
+
|
| 188 |
+
Image.register_extension(MpoImageFile.format, ".mpo")
|
| 189 |
+
|
| 190 |
+
Image.register_mime(MpoImageFile.format, "image/mpo")
|
lib/python3.10/site-packages/PIL/PcfFontFile.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
from typing import BinaryIO, Callable
|
| 22 |
+
|
| 23 |
+
from . import FontFile, Image
|
| 24 |
+
from ._binary import i8
|
| 25 |
+
from ._binary import i16be as b16
|
| 26 |
+
from ._binary import i16le as l16
|
| 27 |
+
from ._binary import i32be as b32
|
| 28 |
+
from ._binary import i32le as l32
|
| 29 |
+
|
| 30 |
+
# --------------------------------------------------------------------
|
| 31 |
+
# declarations
|
| 32 |
+
|
| 33 |
+
PCF_MAGIC = 0x70636601 # "\x01fcp"
|
| 34 |
+
|
| 35 |
+
PCF_PROPERTIES = 1 << 0
|
| 36 |
+
PCF_ACCELERATORS = 1 << 1
|
| 37 |
+
PCF_METRICS = 1 << 2
|
| 38 |
+
PCF_BITMAPS = 1 << 3
|
| 39 |
+
PCF_INK_METRICS = 1 << 4
|
| 40 |
+
PCF_BDF_ENCODINGS = 1 << 5
|
| 41 |
+
PCF_SWIDTHS = 1 << 6
|
| 42 |
+
PCF_GLYPH_NAMES = 1 << 7
|
| 43 |
+
PCF_BDF_ACCELERATORS = 1 << 8
|
| 44 |
+
|
| 45 |
+
BYTES_PER_ROW: list[Callable[[int], int]] = [
|
| 46 |
+
lambda bits: ((bits + 7) >> 3),
|
| 47 |
+
lambda bits: ((bits + 15) >> 3) & ~1,
|
| 48 |
+
lambda bits: ((bits + 31) >> 3) & ~3,
|
| 49 |
+
lambda bits: ((bits + 63) >> 3) & ~7,
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def sz(s: bytes, o: int) -> bytes:
|
| 54 |
+
return s[o : s.index(b"\0", o)]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PcfFontFile(FontFile.FontFile):
|
| 58 |
+
"""Font file plugin for the X11 PCF format."""
|
| 59 |
+
|
| 60 |
+
name = "name"
|
| 61 |
+
|
| 62 |
+
def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
|
| 63 |
+
self.charset_encoding = charset_encoding
|
| 64 |
+
|
| 65 |
+
magic = l32(fp.read(4))
|
| 66 |
+
if magic != PCF_MAGIC:
|
| 67 |
+
msg = "not a PCF file"
|
| 68 |
+
raise SyntaxError(msg)
|
| 69 |
+
|
| 70 |
+
super().__init__()
|
| 71 |
+
|
| 72 |
+
count = l32(fp.read(4))
|
| 73 |
+
self.toc = {}
|
| 74 |
+
for i in range(count):
|
| 75 |
+
type = l32(fp.read(4))
|
| 76 |
+
self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
|
| 77 |
+
|
| 78 |
+
self.fp = fp
|
| 79 |
+
|
| 80 |
+
self.info = self._load_properties()
|
| 81 |
+
|
| 82 |
+
metrics = self._load_metrics()
|
| 83 |
+
bitmaps = self._load_bitmaps(metrics)
|
| 84 |
+
encoding = self._load_encoding()
|
| 85 |
+
|
| 86 |
+
#
|
| 87 |
+
# create glyph structure
|
| 88 |
+
|
| 89 |
+
for ch, ix in enumerate(encoding):
|
| 90 |
+
if ix is not None:
|
| 91 |
+
(
|
| 92 |
+
xsize,
|
| 93 |
+
ysize,
|
| 94 |
+
left,
|
| 95 |
+
right,
|
| 96 |
+
width,
|
| 97 |
+
ascent,
|
| 98 |
+
descent,
|
| 99 |
+
attributes,
|
| 100 |
+
) = metrics[ix]
|
| 101 |
+
self.glyph[ch] = (
|
| 102 |
+
(width, 0),
|
| 103 |
+
(left, descent - ysize, xsize + left, descent),
|
| 104 |
+
(0, 0, xsize, ysize),
|
| 105 |
+
bitmaps[ix],
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def _getformat(
|
| 109 |
+
self, tag: int
|
| 110 |
+
) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
|
| 111 |
+
format, size, offset = self.toc[tag]
|
| 112 |
+
|
| 113 |
+
fp = self.fp
|
| 114 |
+
fp.seek(offset)
|
| 115 |
+
|
| 116 |
+
format = l32(fp.read(4))
|
| 117 |
+
|
| 118 |
+
if format & 4:
|
| 119 |
+
i16, i32 = b16, b32
|
| 120 |
+
else:
|
| 121 |
+
i16, i32 = l16, l32
|
| 122 |
+
|
| 123 |
+
return fp, format, i16, i32
|
| 124 |
+
|
| 125 |
+
def _load_properties(self) -> dict[bytes, bytes | int]:
|
| 126 |
+
#
|
| 127 |
+
# font properties
|
| 128 |
+
|
| 129 |
+
properties = {}
|
| 130 |
+
|
| 131 |
+
fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
|
| 132 |
+
|
| 133 |
+
nprops = i32(fp.read(4))
|
| 134 |
+
|
| 135 |
+
# read property description
|
| 136 |
+
p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
|
| 137 |
+
|
| 138 |
+
if nprops & 3:
|
| 139 |
+
fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
|
| 140 |
+
|
| 141 |
+
data = fp.read(i32(fp.read(4)))
|
| 142 |
+
|
| 143 |
+
for k, s, v in p:
|
| 144 |
+
property_value: bytes | int = sz(data, v) if s else v
|
| 145 |
+
properties[sz(data, k)] = property_value
|
| 146 |
+
|
| 147 |
+
return properties
|
| 148 |
+
|
| 149 |
+
def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
|
| 150 |
+
#
|
| 151 |
+
# font metrics
|
| 152 |
+
|
| 153 |
+
metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
|
| 154 |
+
|
| 155 |
+
fp, format, i16, i32 = self._getformat(PCF_METRICS)
|
| 156 |
+
|
| 157 |
+
append = metrics.append
|
| 158 |
+
|
| 159 |
+
if (format & 0xFF00) == 0x100:
|
| 160 |
+
# "compressed" metrics
|
| 161 |
+
for i in range(i16(fp.read(2))):
|
| 162 |
+
left = i8(fp.read(1)) - 128
|
| 163 |
+
right = i8(fp.read(1)) - 128
|
| 164 |
+
width = i8(fp.read(1)) - 128
|
| 165 |
+
ascent = i8(fp.read(1)) - 128
|
| 166 |
+
descent = i8(fp.read(1)) - 128
|
| 167 |
+
xsize = right - left
|
| 168 |
+
ysize = ascent + descent
|
| 169 |
+
append((xsize, ysize, left, right, width, ascent, descent, 0))
|
| 170 |
+
|
| 171 |
+
else:
|
| 172 |
+
# "jumbo" metrics
|
| 173 |
+
for i in range(i32(fp.read(4))):
|
| 174 |
+
left = i16(fp.read(2))
|
| 175 |
+
right = i16(fp.read(2))
|
| 176 |
+
width = i16(fp.read(2))
|
| 177 |
+
ascent = i16(fp.read(2))
|
| 178 |
+
descent = i16(fp.read(2))
|
| 179 |
+
attributes = i16(fp.read(2))
|
| 180 |
+
xsize = right - left
|
| 181 |
+
ysize = ascent + descent
|
| 182 |
+
append((xsize, ysize, left, right, width, ascent, descent, attributes))
|
| 183 |
+
|
| 184 |
+
return metrics
|
| 185 |
+
|
| 186 |
+
def _load_bitmaps(
|
| 187 |
+
self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
|
| 188 |
+
) -> list[Image.Image]:
|
| 189 |
+
#
|
| 190 |
+
# bitmap data
|
| 191 |
+
|
| 192 |
+
fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
|
| 193 |
+
|
| 194 |
+
nbitmaps = i32(fp.read(4))
|
| 195 |
+
|
| 196 |
+
if nbitmaps != len(metrics):
|
| 197 |
+
msg = "Wrong number of bitmaps"
|
| 198 |
+
raise OSError(msg)
|
| 199 |
+
|
| 200 |
+
offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
|
| 201 |
+
|
| 202 |
+
bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
|
| 203 |
+
|
| 204 |
+
# byteorder = format & 4 # non-zero => MSB
|
| 205 |
+
bitorder = format & 8 # non-zero => MSB
|
| 206 |
+
padindex = format & 3
|
| 207 |
+
|
| 208 |
+
bitmapsize = bitmap_sizes[padindex]
|
| 209 |
+
offsets.append(bitmapsize)
|
| 210 |
+
|
| 211 |
+
data = fp.read(bitmapsize)
|
| 212 |
+
|
| 213 |
+
pad = BYTES_PER_ROW[padindex]
|
| 214 |
+
mode = "1;R"
|
| 215 |
+
if bitorder:
|
| 216 |
+
mode = "1"
|
| 217 |
+
|
| 218 |
+
bitmaps = []
|
| 219 |
+
for i in range(nbitmaps):
|
| 220 |
+
xsize, ysize = metrics[i][:2]
|
| 221 |
+
b, e = offsets[i : i + 2]
|
| 222 |
+
bitmaps.append(
|
| 223 |
+
Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
return bitmaps
|
| 227 |
+
|
| 228 |
+
def _load_encoding(self) -> list[int | None]:
|
| 229 |
+
fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
|
| 230 |
+
|
| 231 |
+
first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
|
| 232 |
+
first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
|
| 233 |
+
|
| 234 |
+
i16(fp.read(2)) # default
|
| 235 |
+
|
| 236 |
+
nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
|
| 237 |
+
|
| 238 |
+
# map character code to bitmap index
|
| 239 |
+
encoding: list[int | None] = [None] * min(256, nencoding)
|
| 240 |
+
|
| 241 |
+
encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
|
| 242 |
+
|
| 243 |
+
for i in range(first_col, len(encoding)):
|
| 244 |
+
try:
|
| 245 |
+
encoding_offset = encoding_offsets[
|
| 246 |
+
ord(bytearray([i]).decode(self.charset_encoding))
|
| 247 |
+
]
|
| 248 |
+
if encoding_offset != 0xFFFF:
|
| 249 |
+
encoding[i] = encoding_offset
|
| 250 |
+
except UnicodeDecodeError:
|
| 251 |
+
# character is not supported in selected encoding
|
| 252 |
+
pass
|
| 253 |
+
|
| 254 |
+
return encoding
|
lib/python3.10/site-packages/PIL/PdfImagePlugin.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PDF (Acrobat) file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-07-16 fl 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, __version__, 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(f"created by Pillow {__version__} 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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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 |
+
|
| 31 |
+
MODES = {
|
| 32 |
+
# (photoshop mode, bits) -> (pil mode, required channels)
|
| 33 |
+
(0, 1): ("1", 1),
|
| 34 |
+
(0, 8): ("L", 1),
|
| 35 |
+
(1, 8): ("L", 1),
|
| 36 |
+
(2, 8): ("P", 1),
|
| 37 |
+
(3, 8): ("RGB", 3),
|
| 38 |
+
(4, 8): ("CMYK", 4),
|
| 39 |
+
(7, 8): ("L", 1), # FIXME: multilayer
|
| 40 |
+
(8, 8): ("L", 1), # duotone
|
| 41 |
+
(9, 8): ("LAB", 3),
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# --------------------------------------------------------------------.
|
| 46 |
+
# read PSD images
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _accept(prefix: bytes) -> bool:
|
| 50 |
+
return prefix[:4] == b"8BPS"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
##
|
| 54 |
+
# Image plugin for Photoshop images.
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PsdImageFile(ImageFile.ImageFile):
|
| 58 |
+
format = "PSD"
|
| 59 |
+
format_description = "Adobe Photoshop"
|
| 60 |
+
_close_exclusive_fp_after_loading = False
|
| 61 |
+
|
| 62 |
+
def _open(self) -> None:
|
| 63 |
+
read = self.fp.read
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
# header
|
| 67 |
+
|
| 68 |
+
s = read(26)
|
| 69 |
+
if not _accept(s) or i16(s, 4) != 1:
|
| 70 |
+
msg = "not a PSD file"
|
| 71 |
+
raise SyntaxError(msg)
|
| 72 |
+
|
| 73 |
+
psd_bits = i16(s, 22)
|
| 74 |
+
psd_channels = i16(s, 12)
|
| 75 |
+
psd_mode = i16(s, 24)
|
| 76 |
+
|
| 77 |
+
mode, channels = MODES[(psd_mode, psd_bits)]
|
| 78 |
+
|
| 79 |
+
if channels > psd_channels:
|
| 80 |
+
msg = "not enough channels"
|
| 81 |
+
raise OSError(msg)
|
| 82 |
+
if mode == "RGB" and psd_channels == 4:
|
| 83 |
+
mode = "RGBA"
|
| 84 |
+
channels = 4
|
| 85 |
+
|
| 86 |
+
self._mode = mode
|
| 87 |
+
self._size = i32(s, 18), i32(s, 14)
|
| 88 |
+
|
| 89 |
+
#
|
| 90 |
+
# color mode data
|
| 91 |
+
|
| 92 |
+
size = i32(read(4))
|
| 93 |
+
if size:
|
| 94 |
+
data = read(size)
|
| 95 |
+
if mode == "P" and size == 768:
|
| 96 |
+
self.palette = ImagePalette.raw("RGB;L", data)
|
| 97 |
+
|
| 98 |
+
#
|
| 99 |
+
# image resources
|
| 100 |
+
|
| 101 |
+
self.resources = []
|
| 102 |
+
|
| 103 |
+
size = i32(read(4))
|
| 104 |
+
if size:
|
| 105 |
+
# load resources
|
| 106 |
+
end = self.fp.tell() + size
|
| 107 |
+
while self.fp.tell() < end:
|
| 108 |
+
read(4) # signature
|
| 109 |
+
id = i16(read(2))
|
| 110 |
+
name = read(i8(read(1)))
|
| 111 |
+
if not (len(name) & 1):
|
| 112 |
+
read(1) # padding
|
| 113 |
+
data = read(i32(read(4)))
|
| 114 |
+
if len(data) & 1:
|
| 115 |
+
read(1) # padding
|
| 116 |
+
self.resources.append((id, name, data))
|
| 117 |
+
if id == 1039: # ICC profile
|
| 118 |
+
self.info["icc_profile"] = data
|
| 119 |
+
|
| 120 |
+
#
|
| 121 |
+
# layer and mask information
|
| 122 |
+
|
| 123 |
+
self._layers_position = None
|
| 124 |
+
|
| 125 |
+
size = i32(read(4))
|
| 126 |
+
if size:
|
| 127 |
+
end = self.fp.tell() + size
|
| 128 |
+
size = i32(read(4))
|
| 129 |
+
if size:
|
| 130 |
+
self._layers_position = self.fp.tell()
|
| 131 |
+
self._layers_size = size
|
| 132 |
+
self.fp.seek(end)
|
| 133 |
+
self._n_frames: int | None = None
|
| 134 |
+
|
| 135 |
+
#
|
| 136 |
+
# image descriptor
|
| 137 |
+
|
| 138 |
+
self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)
|
| 139 |
+
|
| 140 |
+
# keep the file open
|
| 141 |
+
self._fp = self.fp
|
| 142 |
+
self.frame = 1
|
| 143 |
+
self._min_frame = 1
|
| 144 |
+
|
| 145 |
+
@cached_property
|
| 146 |
+
def layers(
|
| 147 |
+
self,
|
| 148 |
+
) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
|
| 149 |
+
layers = []
|
| 150 |
+
if self._layers_position is not None:
|
| 151 |
+
self._fp.seek(self._layers_position)
|
| 152 |
+
_layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size))
|
| 153 |
+
layers = _layerinfo(_layer_data, self._layers_size)
|
| 154 |
+
self._n_frames = len(layers)
|
| 155 |
+
return layers
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def n_frames(self) -> int:
|
| 159 |
+
if self._n_frames is None:
|
| 160 |
+
self._n_frames = len(self.layers)
|
| 161 |
+
return self._n_frames
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def is_animated(self) -> bool:
|
| 165 |
+
return len(self.layers) > 1
|
| 166 |
+
|
| 167 |
+
def seek(self, layer: int) -> None:
|
| 168 |
+
if not self._seek_check(layer):
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
# seek to given layer (1..max)
|
| 172 |
+
try:
|
| 173 |
+
_, mode, _, tile = self.layers[layer - 1]
|
| 174 |
+
self._mode = mode
|
| 175 |
+
self.tile = tile
|
| 176 |
+
self.frame = layer
|
| 177 |
+
self.fp = self._fp
|
| 178 |
+
except IndexError as e:
|
| 179 |
+
msg = "no such layer"
|
| 180 |
+
raise EOFError(msg) from e
|
| 181 |
+
|
| 182 |
+
def tell(self) -> int:
|
| 183 |
+
# return layer number (0=image, 1..max=layers)
|
| 184 |
+
return self.frame
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _layerinfo(
|
| 188 |
+
fp: IO[bytes], ct_bytes: int
|
| 189 |
+
) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
|
| 190 |
+
# read layerinfo block
|
| 191 |
+
layers = []
|
| 192 |
+
|
| 193 |
+
def read(size: int) -> bytes:
|
| 194 |
+
return ImageFile._safe_read(fp, size)
|
| 195 |
+
|
| 196 |
+
ct = si16(read(2))
|
| 197 |
+
|
| 198 |
+
# sanity check
|
| 199 |
+
if ct_bytes < (abs(ct) * 20):
|
| 200 |
+
msg = "Layer block too short for number of layers requested"
|
| 201 |
+
raise SyntaxError(msg)
|
| 202 |
+
|
| 203 |
+
for _ in range(abs(ct)):
|
| 204 |
+
# bounding box
|
| 205 |
+
y0 = si32(read(4))
|
| 206 |
+
x0 = si32(read(4))
|
| 207 |
+
y1 = si32(read(4))
|
| 208 |
+
x1 = si32(read(4))
|
| 209 |
+
|
| 210 |
+
# image info
|
| 211 |
+
bands = []
|
| 212 |
+
ct_types = i16(read(2))
|
| 213 |
+
if ct_types > 4:
|
| 214 |
+
fp.seek(ct_types * 6 + 12, io.SEEK_CUR)
|
| 215 |
+
size = i32(read(4))
|
| 216 |
+
fp.seek(size, io.SEEK_CUR)
|
| 217 |
+
continue
|
| 218 |
+
|
| 219 |
+
for _ in range(ct_types):
|
| 220 |
+
type = i16(read(2))
|
| 221 |
+
|
| 222 |
+
if type == 65535:
|
| 223 |
+
b = "A"
|
| 224 |
+
else:
|
| 225 |
+
b = "RGBA"[type]
|
| 226 |
+
|
| 227 |
+
bands.append(b)
|
| 228 |
+
read(4) # size
|
| 229 |
+
|
| 230 |
+
# figure out the image mode
|
| 231 |
+
bands.sort()
|
| 232 |
+
if bands == ["R"]:
|
| 233 |
+
mode = "L"
|
| 234 |
+
elif bands == ["B", "G", "R"]:
|
| 235 |
+
mode = "RGB"
|
| 236 |
+
elif bands == ["A", "B", "G", "R"]:
|
| 237 |
+
mode = "RGBA"
|
| 238 |
+
else:
|
| 239 |
+
mode = "" # unknown
|
| 240 |
+
|
| 241 |
+
# skip over blend flags and extra information
|
| 242 |
+
read(12) # filler
|
| 243 |
+
name = ""
|
| 244 |
+
size = i32(read(4)) # length of the extra data field
|
| 245 |
+
if size:
|
| 246 |
+
data_end = fp.tell() + size
|
| 247 |
+
|
| 248 |
+
length = i32(read(4))
|
| 249 |
+
if length:
|
| 250 |
+
fp.seek(length - 16, io.SEEK_CUR)
|
| 251 |
+
|
| 252 |
+
length = i32(read(4))
|
| 253 |
+
if length:
|
| 254 |
+
fp.seek(length, io.SEEK_CUR)
|
| 255 |
+
|
| 256 |
+
length = i8(read(1))
|
| 257 |
+
if length:
|
| 258 |
+
# Don't know the proper encoding,
|
| 259 |
+
# Latin-1 should be a good guess
|
| 260 |
+
name = read(length).decode("latin-1", "replace")
|
| 261 |
+
|
| 262 |
+
fp.seek(data_end)
|
| 263 |
+
layers.append((name, mode, (x0, y0, x1, y1)))
|
| 264 |
+
|
| 265 |
+
# get tiles
|
| 266 |
+
layerinfo = []
|
| 267 |
+
for i, (name, mode, bbox) in enumerate(layers):
|
| 268 |
+
tile = []
|
| 269 |
+
for m in mode:
|
| 270 |
+
t = _maketile(fp, m, bbox, 1)
|
| 271 |
+
if t:
|
| 272 |
+
tile.extend(t)
|
| 273 |
+
layerinfo.append((name, mode, bbox, tile))
|
| 274 |
+
|
| 275 |
+
return layerinfo
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _maketile(
|
| 279 |
+
file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int
|
| 280 |
+
) -> list[ImageFile._Tile]:
|
| 281 |
+
tiles = []
|
| 282 |
+
read = file.read
|
| 283 |
+
|
| 284 |
+
compression = i16(read(2))
|
| 285 |
+
|
| 286 |
+
xsize = bbox[2] - bbox[0]
|
| 287 |
+
ysize = bbox[3] - bbox[1]
|
| 288 |
+
|
| 289 |
+
offset = file.tell()
|
| 290 |
+
|
| 291 |
+
if compression == 0:
|
| 292 |
+
#
|
| 293 |
+
# raw compression
|
| 294 |
+
for channel in range(channels):
|
| 295 |
+
layer = mode[channel]
|
| 296 |
+
if mode == "CMYK":
|
| 297 |
+
layer += ";I"
|
| 298 |
+
tiles.append(ImageFile._Tile("raw", bbox, offset, layer))
|
| 299 |
+
offset = offset + xsize * ysize
|
| 300 |
+
|
| 301 |
+
elif compression == 1:
|
| 302 |
+
#
|
| 303 |
+
# packbits compression
|
| 304 |
+
i = 0
|
| 305 |
+
bytecount = read(channels * ysize * 2)
|
| 306 |
+
offset = file.tell()
|
| 307 |
+
for channel in range(channels):
|
| 308 |
+
layer = mode[channel]
|
| 309 |
+
if mode == "CMYK":
|
| 310 |
+
layer += ";I"
|
| 311 |
+
tiles.append(ImageFile._Tile("packbits", bbox, offset, layer))
|
| 312 |
+
for y in range(ysize):
|
| 313 |
+
offset = offset + i16(bytecount, i)
|
| 314 |
+
i += 2
|
| 315 |
+
|
| 316 |
+
file.seek(offset)
|
| 317 |
+
|
| 318 |
+
if offset & 1:
|
| 319 |
+
read(1) # padding
|
| 320 |
+
|
| 321 |
+
return tiles
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# --------------------------------------------------------------------
|
| 325 |
+
# registry
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
Image.register_open(PsdImageFile.format, PsdImageFile, _accept)
|
| 329 |
+
|
| 330 |
+
Image.register_extension(PsdImageFile.format, ".psd")
|
| 331 |
+
|
| 332 |
+
Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")
|
lib/python3.10/site-packages/PIL/TiffImagePlugin.py
ADDED
|
@@ -0,0 +1,2297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 Iterator, MutableMapping
|
| 51 |
+
from fractions import Fraction
|
| 52 |
+
from numbers import Number, Rational
|
| 53 |
+
from typing import IO, TYPE_CHECKING, Any, Callable, NoReturn, 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 ._deprecate import deprecate
|
| 60 |
+
from ._typing import StrOrBytesPath
|
| 61 |
+
from ._util import is_path
|
| 62 |
+
from .TiffTags import TYPES
|
| 63 |
+
|
| 64 |
+
if TYPE_CHECKING:
|
| 65 |
+
from ._typing import Buffer, IntegralLike
|
| 66 |
+
|
| 67 |
+
logger = logging.getLogger(__name__)
|
| 68 |
+
|
| 69 |
+
# Set these to true to force use of libtiff for reading or writing.
|
| 70 |
+
READ_LIBTIFF = False
|
| 71 |
+
WRITE_LIBTIFF = False
|
| 72 |
+
STRIP_SIZE = 65536
|
| 73 |
+
|
| 74 |
+
II = b"II" # little-endian (Intel style)
|
| 75 |
+
MM = b"MM" # big-endian (Motorola style)
|
| 76 |
+
|
| 77 |
+
#
|
| 78 |
+
# --------------------------------------------------------------------
|
| 79 |
+
# Read TIFF files
|
| 80 |
+
|
| 81 |
+
# a few tag names, just to make the code below a bit more readable
|
| 82 |
+
OSUBFILETYPE = 255
|
| 83 |
+
IMAGEWIDTH = 256
|
| 84 |
+
IMAGELENGTH = 257
|
| 85 |
+
BITSPERSAMPLE = 258
|
| 86 |
+
COMPRESSION = 259
|
| 87 |
+
PHOTOMETRIC_INTERPRETATION = 262
|
| 88 |
+
FILLORDER = 266
|
| 89 |
+
IMAGEDESCRIPTION = 270
|
| 90 |
+
STRIPOFFSETS = 273
|
| 91 |
+
SAMPLESPERPIXEL = 277
|
| 92 |
+
ROWSPERSTRIP = 278
|
| 93 |
+
STRIPBYTECOUNTS = 279
|
| 94 |
+
X_RESOLUTION = 282
|
| 95 |
+
Y_RESOLUTION = 283
|
| 96 |
+
PLANAR_CONFIGURATION = 284
|
| 97 |
+
RESOLUTION_UNIT = 296
|
| 98 |
+
TRANSFERFUNCTION = 301
|
| 99 |
+
SOFTWARE = 305
|
| 100 |
+
DATE_TIME = 306
|
| 101 |
+
ARTIST = 315
|
| 102 |
+
PREDICTOR = 317
|
| 103 |
+
COLORMAP = 320
|
| 104 |
+
TILEWIDTH = 322
|
| 105 |
+
TILELENGTH = 323
|
| 106 |
+
TILEOFFSETS = 324
|
| 107 |
+
TILEBYTECOUNTS = 325
|
| 108 |
+
SUBIFD = 330
|
| 109 |
+
EXTRASAMPLES = 338
|
| 110 |
+
SAMPLEFORMAT = 339
|
| 111 |
+
JPEGTABLES = 347
|
| 112 |
+
YCBCRSUBSAMPLING = 530
|
| 113 |
+
REFERENCEBLACKWHITE = 532
|
| 114 |
+
COPYRIGHT = 33432
|
| 115 |
+
IPTC_NAA_CHUNK = 33723 # newsphoto properties
|
| 116 |
+
PHOTOSHOP_CHUNK = 34377 # photoshop properties
|
| 117 |
+
ICCPROFILE = 34675
|
| 118 |
+
EXIFIFD = 34665
|
| 119 |
+
XMP = 700
|
| 120 |
+
JPEGQUALITY = 65537 # pseudo-tag by libtiff
|
| 121 |
+
|
| 122 |
+
# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
|
| 123 |
+
IMAGEJ_META_DATA_BYTE_COUNTS = 50838
|
| 124 |
+
IMAGEJ_META_DATA = 50839
|
| 125 |
+
|
| 126 |
+
COMPRESSION_INFO = {
|
| 127 |
+
# Compression => pil compression name
|
| 128 |
+
1: "raw",
|
| 129 |
+
2: "tiff_ccitt",
|
| 130 |
+
3: "group3",
|
| 131 |
+
4: "group4",
|
| 132 |
+
5: "tiff_lzw",
|
| 133 |
+
6: "tiff_jpeg", # obsolete
|
| 134 |
+
7: "jpeg",
|
| 135 |
+
8: "tiff_adobe_deflate",
|
| 136 |
+
32771: "tiff_raw_16", # 16-bit padding
|
| 137 |
+
32773: "packbits",
|
| 138 |
+
32809: "tiff_thunderscan",
|
| 139 |
+
32946: "tiff_deflate",
|
| 140 |
+
34676: "tiff_sgilog",
|
| 141 |
+
34677: "tiff_sgilog24",
|
| 142 |
+
34925: "lzma",
|
| 143 |
+
50000: "zstd",
|
| 144 |
+
50001: "webp",
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}
|
| 148 |
+
|
| 149 |
+
OPEN_INFO = {
|
| 150 |
+
# (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
|
| 151 |
+
# ExtraSamples) => mode, rawmode
|
| 152 |
+
(II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 153 |
+
(MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 154 |
+
(II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 155 |
+
(MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 156 |
+
(II, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 157 |
+
(MM, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 158 |
+
(II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 159 |
+
(MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 160 |
+
(II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 161 |
+
(MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 162 |
+
(II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 163 |
+
(MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 164 |
+
(II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 165 |
+
(MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 166 |
+
(II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 167 |
+
(MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 168 |
+
(II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 169 |
+
(MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 170 |
+
(II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 171 |
+
(MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 172 |
+
(II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 173 |
+
(MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 174 |
+
(II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 175 |
+
(MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 176 |
+
(II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 177 |
+
(MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 178 |
+
(II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 179 |
+
(MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 180 |
+
(II, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 181 |
+
(MM, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 182 |
+
(II, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 183 |
+
(MM, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 184 |
+
(II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 185 |
+
(MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 186 |
+
(II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
|
| 187 |
+
(II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 188 |
+
(II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 189 |
+
(MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
|
| 190 |
+
(II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),
|
| 191 |
+
(II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),
|
| 192 |
+
(MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),
|
| 193 |
+
(II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 194 |
+
(MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 195 |
+
(II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
|
| 196 |
+
(II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
|
| 197 |
+
(MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),
|
| 198 |
+
(II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 199 |
+
(MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 200 |
+
(II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 201 |
+
(MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 202 |
+
(II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 203 |
+
(MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 204 |
+
(II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 205 |
+
(MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 206 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 207 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 208 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 209 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 210 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 211 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 212 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 213 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 214 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 215 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 216 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 217 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 218 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 219 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 220 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 221 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 222 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 223 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 224 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 225 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 226 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 227 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 228 |
+
(II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),
|
| 229 |
+
(MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),
|
| 230 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),
|
| 231 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),
|
| 232 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),
|
| 233 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),
|
| 234 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),
|
| 235 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),
|
| 236 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),
|
| 237 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),
|
| 238 |
+
(II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 239 |
+
(MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 240 |
+
(II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 241 |
+
(MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 242 |
+
(II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 243 |
+
(MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 244 |
+
(II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 245 |
+
(MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 246 |
+
(II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 247 |
+
(MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 248 |
+
(II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 249 |
+
(MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 250 |
+
(II, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 251 |
+
(MM, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 252 |
+
(II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
|
| 253 |
+
(II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 254 |
+
(MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 255 |
+
(II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 256 |
+
(MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 257 |
+
(II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 258 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 259 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 260 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 261 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 262 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 263 |
+
(II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),
|
| 264 |
+
(MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"),
|
| 265 |
+
(II, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 266 |
+
(MM, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 267 |
+
# JPEG compressed images handled by LibTiff and auto-converted to RGBX
|
| 268 |
+
# Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel
|
| 269 |
+
(II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 270 |
+
(MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 271 |
+
(II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 272 |
+
(MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)
|
| 276 |
+
|
| 277 |
+
PREFIXES = [
|
| 278 |
+
b"MM\x00\x2A", # Valid TIFF header with big-endian byte order
|
| 279 |
+
b"II\x2A\x00", # Valid TIFF header with little-endian byte order
|
| 280 |
+
b"MM\x2A\x00", # Invalid TIFF header, assume big-endian
|
| 281 |
+
b"II\x00\x2A", # Invalid TIFF header, assume little-endian
|
| 282 |
+
b"MM\x00\x2B", # BigTIFF with big-endian byte order
|
| 283 |
+
b"II\x2B\x00", # BigTIFF with little-endian byte order
|
| 284 |
+
]
|
| 285 |
+
|
| 286 |
+
if not getattr(Image.core, "libtiff_support_custom_tags", True):
|
| 287 |
+
deprecate("Support for LibTIFF earlier than version 4", 12)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _accept(prefix: bytes) -> bool:
|
| 291 |
+
return prefix[:4] in 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:
|
| 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):
|
| 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 |
+
offset += len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + 4
|
| 966 |
+
stripoffsets = None
|
| 967 |
+
|
| 968 |
+
# pass 1: convert tags to binary format
|
| 969 |
+
# always write tags in ascending order
|
| 970 |
+
fmt = "Q" if self._bigtiff else "L"
|
| 971 |
+
fmt_size = 8 if self._bigtiff else 4
|
| 972 |
+
for tag, value in sorted(self._tags_v2.items()):
|
| 973 |
+
if tag == STRIPOFFSETS:
|
| 974 |
+
stripoffsets = len(entries)
|
| 975 |
+
typ = self.tagtype[tag]
|
| 976 |
+
logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))
|
| 977 |
+
is_ifd = typ == TiffTags.LONG and isinstance(value, dict)
|
| 978 |
+
if is_ifd:
|
| 979 |
+
ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag)
|
| 980 |
+
values = self._tags_v2[tag]
|
| 981 |
+
for ifd_tag, ifd_value in values.items():
|
| 982 |
+
ifd[ifd_tag] = ifd_value
|
| 983 |
+
data = ifd.tobytes(offset)
|
| 984 |
+
else:
|
| 985 |
+
values = value if isinstance(value, tuple) else (value,)
|
| 986 |
+
data = self._write_dispatch[typ](self, *values)
|
| 987 |
+
|
| 988 |
+
tagname = TiffTags.lookup(tag, self.group).name
|
| 989 |
+
typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")
|
| 990 |
+
msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: "
|
| 991 |
+
msg += f"<table: {len(data)} bytes>" if len(data) >= 16 else str(values)
|
| 992 |
+
logger.debug(msg)
|
| 993 |
+
|
| 994 |
+
# count is sum of lengths for string and arbitrary data
|
| 995 |
+
if is_ifd:
|
| 996 |
+
count = 1
|
| 997 |
+
elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
|
| 998 |
+
count = len(data)
|
| 999 |
+
else:
|
| 1000 |
+
count = len(values)
|
| 1001 |
+
# figure out if data fits into the entry
|
| 1002 |
+
if len(data) <= fmt_size:
|
| 1003 |
+
entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b""))
|
| 1004 |
+
else:
|
| 1005 |
+
entries.append((tag, typ, count, self._pack(fmt, offset), data))
|
| 1006 |
+
offset += (len(data) + 1) // 2 * 2 # pad to word
|
| 1007 |
+
|
| 1008 |
+
# update strip offset data to point beyond auxiliary data
|
| 1009 |
+
if stripoffsets is not None:
|
| 1010 |
+
tag, typ, count, value, data = entries[stripoffsets]
|
| 1011 |
+
if data:
|
| 1012 |
+
size, handler = self._load_dispatch[typ]
|
| 1013 |
+
values = [val + offset for val in handler(self, data, self.legacy_api)]
|
| 1014 |
+
data = self._write_dispatch[typ](self, *values)
|
| 1015 |
+
else:
|
| 1016 |
+
value = self._pack(fmt, self._unpack(fmt, value)[0] + offset)
|
| 1017 |
+
entries[stripoffsets] = tag, typ, count, value, data
|
| 1018 |
+
|
| 1019 |
+
# pass 2: write entries to file
|
| 1020 |
+
for tag, typ, count, value, data in entries:
|
| 1021 |
+
logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))
|
| 1022 |
+
result += self._pack(
|
| 1023 |
+
"HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
# -- overwrite here for multi-page --
|
| 1027 |
+
result += b"\0\0\0\0" # end of entries
|
| 1028 |
+
|
| 1029 |
+
# pass 3: write auxiliary data to file
|
| 1030 |
+
for tag, typ, count, value, data in entries:
|
| 1031 |
+
result += data
|
| 1032 |
+
if len(data) & 1:
|
| 1033 |
+
result += b"\0"
|
| 1034 |
+
|
| 1035 |
+
return result
|
| 1036 |
+
|
| 1037 |
+
def save(self, fp: IO[bytes]) -> int:
|
| 1038 |
+
if fp.tell() == 0: # skip TIFF header on subsequent pages
|
| 1039 |
+
fp.write(self._get_ifh())
|
| 1040 |
+
|
| 1041 |
+
offset = fp.tell()
|
| 1042 |
+
result = self.tobytes(offset)
|
| 1043 |
+
fp.write(result)
|
| 1044 |
+
return offset + len(result)
|
| 1045 |
+
|
| 1046 |
+
|
| 1047 |
+
ImageFileDirectory_v2._load_dispatch = _load_dispatch
|
| 1048 |
+
ImageFileDirectory_v2._write_dispatch = _write_dispatch
|
| 1049 |
+
for idx, name in TYPES.items():
|
| 1050 |
+
name = name.replace(" ", "_")
|
| 1051 |
+
setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])
|
| 1052 |
+
setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])
|
| 1053 |
+
del _load_dispatch, _write_dispatch, idx, name
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
# Legacy ImageFileDirectory support.
|
| 1057 |
+
class ImageFileDirectory_v1(ImageFileDirectory_v2):
|
| 1058 |
+
"""This class represents the **legacy** interface to a TIFF tag directory.
|
| 1059 |
+
|
| 1060 |
+
Exposes a dictionary interface of the tags in the directory::
|
| 1061 |
+
|
| 1062 |
+
ifd = ImageFileDirectory_v1()
|
| 1063 |
+
ifd[key] = 'Some Data'
|
| 1064 |
+
ifd.tagtype[key] = TiffTags.ASCII
|
| 1065 |
+
print(ifd[key])
|
| 1066 |
+
('Some Data',)
|
| 1067 |
+
|
| 1068 |
+
Also contains a dictionary of tag types as read from the tiff image file,
|
| 1069 |
+
:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.
|
| 1070 |
+
|
| 1071 |
+
Values are returned as a tuple.
|
| 1072 |
+
|
| 1073 |
+
.. deprecated:: 3.0.0
|
| 1074 |
+
"""
|
| 1075 |
+
|
| 1076 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 1077 |
+
super().__init__(*args, **kwargs)
|
| 1078 |
+
self._legacy_api = True
|
| 1079 |
+
|
| 1080 |
+
tags = property(lambda self: self._tags_v1)
|
| 1081 |
+
tagdata = property(lambda self: self._tagdata)
|
| 1082 |
+
|
| 1083 |
+
# defined in ImageFileDirectory_v2
|
| 1084 |
+
tagtype: dict[int, int]
|
| 1085 |
+
"""Dictionary of tag types"""
|
| 1086 |
+
|
| 1087 |
+
@classmethod
|
| 1088 |
+
def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1:
|
| 1089 |
+
"""Returns an
|
| 1090 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1091 |
+
instance with the same data as is contained in the original
|
| 1092 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1093 |
+
instance.
|
| 1094 |
+
|
| 1095 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1096 |
+
|
| 1097 |
+
"""
|
| 1098 |
+
|
| 1099 |
+
ifd = cls(prefix=original.prefix)
|
| 1100 |
+
ifd._tagdata = original._tagdata
|
| 1101 |
+
ifd.tagtype = original.tagtype
|
| 1102 |
+
ifd.next = original.next # an indicator for multipage tiffs
|
| 1103 |
+
return ifd
|
| 1104 |
+
|
| 1105 |
+
def to_v2(self) -> ImageFileDirectory_v2:
|
| 1106 |
+
"""Returns an
|
| 1107 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1108 |
+
instance with the same data as is contained in the original
|
| 1109 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1110 |
+
instance.
|
| 1111 |
+
|
| 1112 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1113 |
+
|
| 1114 |
+
"""
|
| 1115 |
+
|
| 1116 |
+
ifd = ImageFileDirectory_v2(prefix=self.prefix)
|
| 1117 |
+
ifd._tagdata = dict(self._tagdata)
|
| 1118 |
+
ifd.tagtype = dict(self.tagtype)
|
| 1119 |
+
ifd._tags_v2 = dict(self._tags_v2)
|
| 1120 |
+
return ifd
|
| 1121 |
+
|
| 1122 |
+
def __contains__(self, tag: object) -> bool:
|
| 1123 |
+
return tag in self._tags_v1 or tag in self._tagdata
|
| 1124 |
+
|
| 1125 |
+
def __len__(self) -> int:
|
| 1126 |
+
return len(set(self._tagdata) | set(self._tags_v1))
|
| 1127 |
+
|
| 1128 |
+
def __iter__(self) -> Iterator[int]:
|
| 1129 |
+
return iter(set(self._tagdata) | set(self._tags_v1))
|
| 1130 |
+
|
| 1131 |
+
def __setitem__(self, tag: int, value: Any) -> None:
|
| 1132 |
+
for legacy_api in (False, True):
|
| 1133 |
+
self._setitem(tag, value, legacy_api)
|
| 1134 |
+
|
| 1135 |
+
def __getitem__(self, tag: int) -> Any:
|
| 1136 |
+
if tag not in self._tags_v1: # unpack on the fly
|
| 1137 |
+
data = self._tagdata[tag]
|
| 1138 |
+
typ = self.tagtype[tag]
|
| 1139 |
+
size, handler = self._load_dispatch[typ]
|
| 1140 |
+
for legacy in (False, True):
|
| 1141 |
+
self._setitem(tag, handler(self, data, legacy), legacy)
|
| 1142 |
+
val = self._tags_v1[tag]
|
| 1143 |
+
if not isinstance(val, (tuple, bytes)):
|
| 1144 |
+
val = (val,)
|
| 1145 |
+
return val
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
# undone -- switch this pointer
|
| 1149 |
+
ImageFileDirectory = ImageFileDirectory_v1
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
##
|
| 1153 |
+
# Image plugin for TIFF files.
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
class TiffImageFile(ImageFile.ImageFile):
|
| 1157 |
+
format = "TIFF"
|
| 1158 |
+
format_description = "Adobe TIFF"
|
| 1159 |
+
_close_exclusive_fp_after_loading = False
|
| 1160 |
+
|
| 1161 |
+
def __init__(
|
| 1162 |
+
self,
|
| 1163 |
+
fp: StrOrBytesPath | IO[bytes],
|
| 1164 |
+
filename: str | bytes | None = None,
|
| 1165 |
+
) -> None:
|
| 1166 |
+
self.tag_v2: ImageFileDirectory_v2
|
| 1167 |
+
""" Image file directory (tag dictionary) """
|
| 1168 |
+
|
| 1169 |
+
self.tag: ImageFileDirectory_v1
|
| 1170 |
+
""" Legacy tag entries """
|
| 1171 |
+
|
| 1172 |
+
super().__init__(fp, filename)
|
| 1173 |
+
|
| 1174 |
+
def _open(self) -> None:
|
| 1175 |
+
"""Open the first image in a TIFF file"""
|
| 1176 |
+
|
| 1177 |
+
# Header
|
| 1178 |
+
ifh = self.fp.read(8)
|
| 1179 |
+
if ifh[2] == 43:
|
| 1180 |
+
ifh += self.fp.read(8)
|
| 1181 |
+
|
| 1182 |
+
self.tag_v2 = ImageFileDirectory_v2(ifh)
|
| 1183 |
+
|
| 1184 |
+
# setup frame pointers
|
| 1185 |
+
self.__first = self.__next = self.tag_v2.next
|
| 1186 |
+
self.__frame = -1
|
| 1187 |
+
self._fp = self.fp
|
| 1188 |
+
self._frame_pos: list[int] = []
|
| 1189 |
+
self._n_frames: int | None = None
|
| 1190 |
+
|
| 1191 |
+
logger.debug("*** TiffImageFile._open ***")
|
| 1192 |
+
logger.debug("- __first: %s", self.__first)
|
| 1193 |
+
logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)
|
| 1194 |
+
|
| 1195 |
+
# and load the first frame
|
| 1196 |
+
self._seek(0)
|
| 1197 |
+
|
| 1198 |
+
@property
|
| 1199 |
+
def n_frames(self) -> int:
|
| 1200 |
+
current_n_frames = self._n_frames
|
| 1201 |
+
if current_n_frames is None:
|
| 1202 |
+
current = self.tell()
|
| 1203 |
+
self._seek(len(self._frame_pos))
|
| 1204 |
+
while self._n_frames is None:
|
| 1205 |
+
self._seek(self.tell() + 1)
|
| 1206 |
+
self.seek(current)
|
| 1207 |
+
assert self._n_frames is not None
|
| 1208 |
+
return self._n_frames
|
| 1209 |
+
|
| 1210 |
+
def seek(self, frame: int) -> None:
|
| 1211 |
+
"""Select a given frame as current image"""
|
| 1212 |
+
if not self._seek_check(frame):
|
| 1213 |
+
return
|
| 1214 |
+
self._seek(frame)
|
| 1215 |
+
if self._im is not None and (
|
| 1216 |
+
self.im.size != self._tile_size or self.im.mode != self.mode
|
| 1217 |
+
):
|
| 1218 |
+
# The core image will no longer be used
|
| 1219 |
+
self._im = None
|
| 1220 |
+
|
| 1221 |
+
def _seek(self, frame: int) -> None:
|
| 1222 |
+
self.fp = self._fp
|
| 1223 |
+
|
| 1224 |
+
while len(self._frame_pos) <= frame:
|
| 1225 |
+
if not self.__next:
|
| 1226 |
+
msg = "no more images in TIFF file"
|
| 1227 |
+
raise EOFError(msg)
|
| 1228 |
+
logger.debug(
|
| 1229 |
+
"Seeking to frame %s, on frame %s, __next %s, location: %s",
|
| 1230 |
+
frame,
|
| 1231 |
+
self.__frame,
|
| 1232 |
+
self.__next,
|
| 1233 |
+
self.fp.tell(),
|
| 1234 |
+
)
|
| 1235 |
+
if self.__next >= 2**63:
|
| 1236 |
+
msg = "Unable to seek to frame"
|
| 1237 |
+
raise ValueError(msg)
|
| 1238 |
+
self.fp.seek(self.__next)
|
| 1239 |
+
self._frame_pos.append(self.__next)
|
| 1240 |
+
logger.debug("Loading tags, location: %s", self.fp.tell())
|
| 1241 |
+
self.tag_v2.load(self.fp)
|
| 1242 |
+
if self.tag_v2.next in self._frame_pos:
|
| 1243 |
+
# This IFD has already been processed
|
| 1244 |
+
# Declare this to be the end of the image
|
| 1245 |
+
self.__next = 0
|
| 1246 |
+
else:
|
| 1247 |
+
self.__next = self.tag_v2.next
|
| 1248 |
+
if self.__next == 0:
|
| 1249 |
+
self._n_frames = frame + 1
|
| 1250 |
+
if len(self._frame_pos) == 1:
|
| 1251 |
+
self.is_animated = self.__next != 0
|
| 1252 |
+
self.__frame += 1
|
| 1253 |
+
self.fp.seek(self._frame_pos[frame])
|
| 1254 |
+
self.tag_v2.load(self.fp)
|
| 1255 |
+
if XMP in self.tag_v2:
|
| 1256 |
+
self.info["xmp"] = self.tag_v2[XMP]
|
| 1257 |
+
elif "xmp" in self.info:
|
| 1258 |
+
del self.info["xmp"]
|
| 1259 |
+
self._reload_exif()
|
| 1260 |
+
# fill the legacy tag/ifd entries
|
| 1261 |
+
self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
|
| 1262 |
+
self.__frame = frame
|
| 1263 |
+
self._setup()
|
| 1264 |
+
|
| 1265 |
+
def tell(self) -> int:
|
| 1266 |
+
"""Return the current frame number"""
|
| 1267 |
+
return self.__frame
|
| 1268 |
+
|
| 1269 |
+
def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]:
|
| 1270 |
+
"""
|
| 1271 |
+
Returns a dictionary of Photoshop "Image Resource Blocks".
|
| 1272 |
+
The keys are the image resource ID. For more information, see
|
| 1273 |
+
https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727
|
| 1274 |
+
|
| 1275 |
+
:returns: Photoshop "Image Resource Blocks" in a dictionary.
|
| 1276 |
+
"""
|
| 1277 |
+
blocks = {}
|
| 1278 |
+
val = self.tag_v2.get(ExifTags.Base.ImageResources)
|
| 1279 |
+
if val:
|
| 1280 |
+
while val[:4] == b"8BIM":
|
| 1281 |
+
id = i16(val[4:6])
|
| 1282 |
+
n = math.ceil((val[6] + 1) / 2) * 2
|
| 1283 |
+
size = i32(val[6 + n : 10 + n])
|
| 1284 |
+
data = val[10 + n : 10 + n + size]
|
| 1285 |
+
blocks[id] = {"data": data}
|
| 1286 |
+
|
| 1287 |
+
val = val[math.ceil((10 + n + size) / 2) * 2 :]
|
| 1288 |
+
return blocks
|
| 1289 |
+
|
| 1290 |
+
def load(self) -> Image.core.PixelAccess | None:
|
| 1291 |
+
if self.tile and self.use_load_libtiff:
|
| 1292 |
+
return self._load_libtiff()
|
| 1293 |
+
return super().load()
|
| 1294 |
+
|
| 1295 |
+
def load_prepare(self) -> None:
|
| 1296 |
+
if self._im is None:
|
| 1297 |
+
Image._decompression_bomb_check(self._tile_size)
|
| 1298 |
+
self.im = Image.core.new(self.mode, self._tile_size)
|
| 1299 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 1300 |
+
|
| 1301 |
+
def load_end(self) -> None:
|
| 1302 |
+
# allow closing if we're on the first frame, there's no next
|
| 1303 |
+
# This is the ImageFile.load path only, libtiff specific below.
|
| 1304 |
+
if not self.is_animated:
|
| 1305 |
+
self._close_exclusive_fp_after_loading = True
|
| 1306 |
+
|
| 1307 |
+
# load IFD data from fp before it is closed
|
| 1308 |
+
exif = self.getexif()
|
| 1309 |
+
for key in TiffTags.TAGS_V2_GROUPS:
|
| 1310 |
+
if key not in exif:
|
| 1311 |
+
continue
|
| 1312 |
+
exif.get_ifd(key)
|
| 1313 |
+
|
| 1314 |
+
ImageOps.exif_transpose(self, in_place=True)
|
| 1315 |
+
if ExifTags.Base.Orientation in self.tag_v2:
|
| 1316 |
+
del self.tag_v2[ExifTags.Base.Orientation]
|
| 1317 |
+
|
| 1318 |
+
def _load_libtiff(self) -> Image.core.PixelAccess | None:
|
| 1319 |
+
"""Overload method triggered when we detect a compressed tiff
|
| 1320 |
+
Calls out to libtiff"""
|
| 1321 |
+
|
| 1322 |
+
Image.Image.load(self)
|
| 1323 |
+
|
| 1324 |
+
self.load_prepare()
|
| 1325 |
+
|
| 1326 |
+
if not len(self.tile) == 1:
|
| 1327 |
+
msg = "Not exactly one tile"
|
| 1328 |
+
raise OSError(msg)
|
| 1329 |
+
|
| 1330 |
+
# (self._compression, (extents tuple),
|
| 1331 |
+
# 0, (rawmode, self._compression, fp))
|
| 1332 |
+
extents = self.tile[0][1]
|
| 1333 |
+
args = self.tile[0][3]
|
| 1334 |
+
|
| 1335 |
+
# To be nice on memory footprint, if there's a
|
| 1336 |
+
# file descriptor, use that instead of reading
|
| 1337 |
+
# into a string in python.
|
| 1338 |
+
try:
|
| 1339 |
+
fp = hasattr(self.fp, "fileno") and self.fp.fileno()
|
| 1340 |
+
# flush the file descriptor, prevents error on pypy 2.4+
|
| 1341 |
+
# should also eliminate the need for fp.tell
|
| 1342 |
+
# in _seek
|
| 1343 |
+
if hasattr(self.fp, "flush"):
|
| 1344 |
+
self.fp.flush()
|
| 1345 |
+
except OSError:
|
| 1346 |
+
# io.BytesIO have a fileno, but returns an OSError if
|
| 1347 |
+
# it doesn't use a file descriptor.
|
| 1348 |
+
fp = False
|
| 1349 |
+
|
| 1350 |
+
if fp:
|
| 1351 |
+
assert isinstance(args, tuple)
|
| 1352 |
+
args_list = list(args)
|
| 1353 |
+
args_list[2] = fp
|
| 1354 |
+
args = tuple(args_list)
|
| 1355 |
+
|
| 1356 |
+
decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)
|
| 1357 |
+
try:
|
| 1358 |
+
decoder.setimage(self.im, extents)
|
| 1359 |
+
except ValueError as e:
|
| 1360 |
+
msg = "Couldn't set the image"
|
| 1361 |
+
raise OSError(msg) from e
|
| 1362 |
+
|
| 1363 |
+
close_self_fp = self._exclusive_fp and not self.is_animated
|
| 1364 |
+
if hasattr(self.fp, "getvalue"):
|
| 1365 |
+
# We've got a stringio like thing passed in. Yay for all in memory.
|
| 1366 |
+
# The decoder needs the entire file in one shot, so there's not
|
| 1367 |
+
# a lot we can do here other than give it the entire file.
|
| 1368 |
+
# unless we could do something like get the address of the
|
| 1369 |
+
# underlying string for stringio.
|
| 1370 |
+
#
|
| 1371 |
+
# Rearranging for supporting byteio items, since they have a fileno
|
| 1372 |
+
# that returns an OSError if there's no underlying fp. Easier to
|
| 1373 |
+
# deal with here by reordering.
|
| 1374 |
+
logger.debug("have getvalue. just sending in a string from getvalue")
|
| 1375 |
+
n, err = decoder.decode(self.fp.getvalue())
|
| 1376 |
+
elif fp:
|
| 1377 |
+
# we've got a actual file on disk, pass in the fp.
|
| 1378 |
+
logger.debug("have fileno, calling fileno version of the decoder.")
|
| 1379 |
+
if not close_self_fp:
|
| 1380 |
+
self.fp.seek(0)
|
| 1381 |
+
# Save and restore the file position, because libtiff will move it
|
| 1382 |
+
# outside of the Python runtime, and that will confuse
|
| 1383 |
+
# io.BufferedReader and possible others.
|
| 1384 |
+
# NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(),
|
| 1385 |
+
# because the buffer read head already may not equal the actual
|
| 1386 |
+
# file position, and fp.seek() may just adjust it's internal
|
| 1387 |
+
# pointer and not actually seek the OS file handle.
|
| 1388 |
+
pos = os.lseek(fp, 0, os.SEEK_CUR)
|
| 1389 |
+
# 4 bytes, otherwise the trace might error out
|
| 1390 |
+
n, err = decoder.decode(b"fpfp")
|
| 1391 |
+
os.lseek(fp, pos, os.SEEK_SET)
|
| 1392 |
+
else:
|
| 1393 |
+
# we have something else.
|
| 1394 |
+
logger.debug("don't have fileno or getvalue. just reading")
|
| 1395 |
+
self.fp.seek(0)
|
| 1396 |
+
# UNDONE -- so much for that buffer size thing.
|
| 1397 |
+
n, err = decoder.decode(self.fp.read())
|
| 1398 |
+
|
| 1399 |
+
self.tile = []
|
| 1400 |
+
self.readonly = 0
|
| 1401 |
+
|
| 1402 |
+
self.load_end()
|
| 1403 |
+
|
| 1404 |
+
if close_self_fp:
|
| 1405 |
+
self.fp.close()
|
| 1406 |
+
self.fp = None # might be shared
|
| 1407 |
+
|
| 1408 |
+
if err < 0:
|
| 1409 |
+
raise OSError(err)
|
| 1410 |
+
|
| 1411 |
+
return Image.Image.load(self)
|
| 1412 |
+
|
| 1413 |
+
def _setup(self) -> None:
|
| 1414 |
+
"""Setup this image object based on current tags"""
|
| 1415 |
+
|
| 1416 |
+
if 0xBC01 in self.tag_v2:
|
| 1417 |
+
msg = "Windows Media Photo files not yet supported"
|
| 1418 |
+
raise OSError(msg)
|
| 1419 |
+
|
| 1420 |
+
# extract relevant tags
|
| 1421 |
+
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
|
| 1422 |
+
self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
|
| 1423 |
+
|
| 1424 |
+
# photometric is a required tag, but not everyone is reading
|
| 1425 |
+
# the specification
|
| 1426 |
+
photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
|
| 1427 |
+
|
| 1428 |
+
# old style jpeg compression images most certainly are YCbCr
|
| 1429 |
+
if self._compression == "tiff_jpeg":
|
| 1430 |
+
photo = 6
|
| 1431 |
+
|
| 1432 |
+
fillorder = self.tag_v2.get(FILLORDER, 1)
|
| 1433 |
+
|
| 1434 |
+
logger.debug("*** Summary ***")
|
| 1435 |
+
logger.debug("- compression: %s", self._compression)
|
| 1436 |
+
logger.debug("- photometric_interpretation: %s", photo)
|
| 1437 |
+
logger.debug("- planar_configuration: %s", self._planar_configuration)
|
| 1438 |
+
logger.debug("- fill_order: %s", fillorder)
|
| 1439 |
+
logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING))
|
| 1440 |
+
|
| 1441 |
+
# size
|
| 1442 |
+
try:
|
| 1443 |
+
xsize = self.tag_v2[IMAGEWIDTH]
|
| 1444 |
+
ysize = self.tag_v2[IMAGELENGTH]
|
| 1445 |
+
except KeyError as e:
|
| 1446 |
+
msg = "Missing dimensions"
|
| 1447 |
+
raise TypeError(msg) from e
|
| 1448 |
+
if not isinstance(xsize, int) or not isinstance(ysize, int):
|
| 1449 |
+
msg = "Invalid dimensions"
|
| 1450 |
+
raise ValueError(msg)
|
| 1451 |
+
self._tile_size = xsize, ysize
|
| 1452 |
+
orientation = self.tag_v2.get(ExifTags.Base.Orientation)
|
| 1453 |
+
if orientation in (5, 6, 7, 8):
|
| 1454 |
+
self._size = ysize, xsize
|
| 1455 |
+
else:
|
| 1456 |
+
self._size = xsize, ysize
|
| 1457 |
+
|
| 1458 |
+
logger.debug("- size: %s", self.size)
|
| 1459 |
+
|
| 1460 |
+
sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))
|
| 1461 |
+
if len(sample_format) > 1 and max(sample_format) == min(sample_format) == 1:
|
| 1462 |
+
# SAMPLEFORMAT is properly per band, so an RGB image will
|
| 1463 |
+
# be (1,1,1). But, we don't support per band pixel types,
|
| 1464 |
+
# and anything more than one band is a uint8. So, just
|
| 1465 |
+
# take the first element. Revisit this if adding support
|
| 1466 |
+
# for more exotic images.
|
| 1467 |
+
sample_format = (1,)
|
| 1468 |
+
|
| 1469 |
+
bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
|
| 1470 |
+
extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
|
| 1471 |
+
if photo in (2, 6, 8): # RGB, YCbCr, LAB
|
| 1472 |
+
bps_count = 3
|
| 1473 |
+
elif photo == 5: # CMYK
|
| 1474 |
+
bps_count = 4
|
| 1475 |
+
else:
|
| 1476 |
+
bps_count = 1
|
| 1477 |
+
bps_count += len(extra_tuple)
|
| 1478 |
+
bps_actual_count = len(bps_tuple)
|
| 1479 |
+
samples_per_pixel = self.tag_v2.get(
|
| 1480 |
+
SAMPLESPERPIXEL,
|
| 1481 |
+
3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
|
| 1482 |
+
)
|
| 1483 |
+
|
| 1484 |
+
if samples_per_pixel > MAX_SAMPLESPERPIXEL:
|
| 1485 |
+
# DOS check, samples_per_pixel can be a Long, and we extend the tuple below
|
| 1486 |
+
logger.error(
|
| 1487 |
+
"More samples per pixel than can be decoded: %s", samples_per_pixel
|
| 1488 |
+
)
|
| 1489 |
+
msg = "Invalid value for samples per pixel"
|
| 1490 |
+
raise SyntaxError(msg)
|
| 1491 |
+
|
| 1492 |
+
if samples_per_pixel < bps_actual_count:
|
| 1493 |
+
# If a file has more values in bps_tuple than expected,
|
| 1494 |
+
# remove the excess.
|
| 1495 |
+
bps_tuple = bps_tuple[:samples_per_pixel]
|
| 1496 |
+
elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:
|
| 1497 |
+
# If a file has only one value in bps_tuple, when it should have more,
|
| 1498 |
+
# presume it is the same number of bits for all of the samples.
|
| 1499 |
+
bps_tuple = bps_tuple * samples_per_pixel
|
| 1500 |
+
|
| 1501 |
+
if len(bps_tuple) != samples_per_pixel:
|
| 1502 |
+
msg = "unknown data organization"
|
| 1503 |
+
raise SyntaxError(msg)
|
| 1504 |
+
|
| 1505 |
+
# mode: check photometric interpretation and bits per pixel
|
| 1506 |
+
key = (
|
| 1507 |
+
self.tag_v2.prefix,
|
| 1508 |
+
photo,
|
| 1509 |
+
sample_format,
|
| 1510 |
+
fillorder,
|
| 1511 |
+
bps_tuple,
|
| 1512 |
+
extra_tuple,
|
| 1513 |
+
)
|
| 1514 |
+
logger.debug("format key: %s", key)
|
| 1515 |
+
try:
|
| 1516 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1517 |
+
except KeyError as e:
|
| 1518 |
+
logger.debug("- unsupported format")
|
| 1519 |
+
msg = "unknown pixel mode"
|
| 1520 |
+
raise SyntaxError(msg) from e
|
| 1521 |
+
|
| 1522 |
+
logger.debug("- raw mode: %s", rawmode)
|
| 1523 |
+
logger.debug("- pil mode: %s", self.mode)
|
| 1524 |
+
|
| 1525 |
+
self.info["compression"] = self._compression
|
| 1526 |
+
|
| 1527 |
+
xres = self.tag_v2.get(X_RESOLUTION, 1)
|
| 1528 |
+
yres = self.tag_v2.get(Y_RESOLUTION, 1)
|
| 1529 |
+
|
| 1530 |
+
if xres and yres:
|
| 1531 |
+
resunit = self.tag_v2.get(RESOLUTION_UNIT)
|
| 1532 |
+
if resunit == 2: # dots per inch
|
| 1533 |
+
self.info["dpi"] = (xres, yres)
|
| 1534 |
+
elif resunit == 3: # dots per centimeter. convert to dpi
|
| 1535 |
+
self.info["dpi"] = (xres * 2.54, yres * 2.54)
|
| 1536 |
+
elif resunit is None: # used to default to 1, but now 2)
|
| 1537 |
+
self.info["dpi"] = (xres, yres)
|
| 1538 |
+
# For backward compatibility,
|
| 1539 |
+
# we also preserve the old behavior
|
| 1540 |
+
self.info["resolution"] = xres, yres
|
| 1541 |
+
else: # No absolute unit of measurement
|
| 1542 |
+
self.info["resolution"] = xres, yres
|
| 1543 |
+
|
| 1544 |
+
# build tile descriptors
|
| 1545 |
+
x = y = layer = 0
|
| 1546 |
+
self.tile = []
|
| 1547 |
+
self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
|
| 1548 |
+
if self.use_load_libtiff:
|
| 1549 |
+
# Decoder expects entire file as one tile.
|
| 1550 |
+
# There's a buffer size limit in load (64k)
|
| 1551 |
+
# so large g4 images will fail if we use that
|
| 1552 |
+
# function.
|
| 1553 |
+
#
|
| 1554 |
+
# Setup the one tile for the whole image, then
|
| 1555 |
+
# use the _load_libtiff function.
|
| 1556 |
+
|
| 1557 |
+
# libtiff handles the fillmode for us, so 1;IR should
|
| 1558 |
+
# actually be 1;I. Including the R double reverses the
|
| 1559 |
+
# bits, so stripes of the image are reversed. See
|
| 1560 |
+
# https://github.com/python-pillow/Pillow/issues/279
|
| 1561 |
+
if fillorder == 2:
|
| 1562 |
+
# Replace fillorder with fillorder=1
|
| 1563 |
+
key = key[:3] + (1,) + key[4:]
|
| 1564 |
+
logger.debug("format key: %s", key)
|
| 1565 |
+
# this should always work, since all the
|
| 1566 |
+
# fillorder==2 modes have a corresponding
|
| 1567 |
+
# fillorder=1 mode
|
| 1568 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1569 |
+
# YCbCr images with new jpeg compression with pixels in one plane
|
| 1570 |
+
# unpacked straight into RGB values
|
| 1571 |
+
if (
|
| 1572 |
+
photo == 6
|
| 1573 |
+
and self._compression == "jpeg"
|
| 1574 |
+
and self._planar_configuration == 1
|
| 1575 |
+
):
|
| 1576 |
+
rawmode = "RGB"
|
| 1577 |
+
# libtiff always returns the bytes in native order.
|
| 1578 |
+
# we're expecting image byte order. So, if the rawmode
|
| 1579 |
+
# contains I;16, we need to convert from native to image
|
| 1580 |
+
# byte order.
|
| 1581 |
+
elif rawmode == "I;16":
|
| 1582 |
+
rawmode = "I;16N"
|
| 1583 |
+
elif rawmode.endswith(";16B") or rawmode.endswith(";16L"):
|
| 1584 |
+
rawmode = rawmode[:-1] + "N"
|
| 1585 |
+
|
| 1586 |
+
# Offset in the tile tuple is 0, we go from 0,0 to
|
| 1587 |
+
# w,h, and we only do this once -- eds
|
| 1588 |
+
a = (rawmode, self._compression, False, self.tag_v2.offset)
|
| 1589 |
+
self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))
|
| 1590 |
+
|
| 1591 |
+
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
|
| 1592 |
+
# striped image
|
| 1593 |
+
if STRIPOFFSETS in self.tag_v2:
|
| 1594 |
+
offsets = self.tag_v2[STRIPOFFSETS]
|
| 1595 |
+
h = self.tag_v2.get(ROWSPERSTRIP, ysize)
|
| 1596 |
+
w = xsize
|
| 1597 |
+
else:
|
| 1598 |
+
# tiled image
|
| 1599 |
+
offsets = self.tag_v2[TILEOFFSETS]
|
| 1600 |
+
tilewidth = self.tag_v2.get(TILEWIDTH)
|
| 1601 |
+
h = self.tag_v2.get(TILELENGTH)
|
| 1602 |
+
if not isinstance(tilewidth, int) or not isinstance(h, int):
|
| 1603 |
+
msg = "Invalid tile dimensions"
|
| 1604 |
+
raise ValueError(msg)
|
| 1605 |
+
w = tilewidth
|
| 1606 |
+
|
| 1607 |
+
for offset in offsets:
|
| 1608 |
+
if x + w > xsize:
|
| 1609 |
+
stride = w * sum(bps_tuple) / 8 # bytes per line
|
| 1610 |
+
else:
|
| 1611 |
+
stride = 0
|
| 1612 |
+
|
| 1613 |
+
tile_rawmode = rawmode
|
| 1614 |
+
if self._planar_configuration == 2:
|
| 1615 |
+
# each band on it's own layer
|
| 1616 |
+
tile_rawmode = rawmode[layer]
|
| 1617 |
+
# adjust stride width accordingly
|
| 1618 |
+
stride /= bps_count
|
| 1619 |
+
|
| 1620 |
+
args = (tile_rawmode, int(stride), 1)
|
| 1621 |
+
self.tile.append(
|
| 1622 |
+
ImageFile._Tile(
|
| 1623 |
+
self._compression,
|
| 1624 |
+
(x, y, min(x + w, xsize), min(y + h, ysize)),
|
| 1625 |
+
offset,
|
| 1626 |
+
args,
|
| 1627 |
+
)
|
| 1628 |
+
)
|
| 1629 |
+
x = x + w
|
| 1630 |
+
if x >= xsize:
|
| 1631 |
+
x, y = 0, y + h
|
| 1632 |
+
if y >= ysize:
|
| 1633 |
+
x = y = 0
|
| 1634 |
+
layer += 1
|
| 1635 |
+
else:
|
| 1636 |
+
logger.debug("- unsupported data organization")
|
| 1637 |
+
msg = "unknown data organization"
|
| 1638 |
+
raise SyntaxError(msg)
|
| 1639 |
+
|
| 1640 |
+
# Fix up info.
|
| 1641 |
+
if ICCPROFILE in self.tag_v2:
|
| 1642 |
+
self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
|
| 1643 |
+
|
| 1644 |
+
# fixup palette descriptor
|
| 1645 |
+
|
| 1646 |
+
if self.mode in ["P", "PA"]:
|
| 1647 |
+
palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
|
| 1648 |
+
self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
|
| 1649 |
+
|
| 1650 |
+
|
| 1651 |
+
#
|
| 1652 |
+
# --------------------------------------------------------------------
|
| 1653 |
+
# Write TIFF files
|
| 1654 |
+
|
| 1655 |
+
# little endian is default except for image modes with
|
| 1656 |
+
# explicit big endian byte-order
|
| 1657 |
+
|
| 1658 |
+
SAVE_INFO = {
|
| 1659 |
+
# mode => rawmode, byteorder, photometrics,
|
| 1660 |
+
# sampleformat, bitspersample, extra
|
| 1661 |
+
"1": ("1", II, 1, 1, (1,), None),
|
| 1662 |
+
"L": ("L", II, 1, 1, (8,), None),
|
| 1663 |
+
"LA": ("LA", II, 1, 1, (8, 8), 2),
|
| 1664 |
+
"P": ("P", II, 3, 1, (8,), None),
|
| 1665 |
+
"PA": ("PA", II, 3, 1, (8, 8), 2),
|
| 1666 |
+
"I": ("I;32S", II, 1, 2, (32,), None),
|
| 1667 |
+
"I;16": ("I;16", II, 1, 1, (16,), None),
|
| 1668 |
+
"I;16S": ("I;16S", II, 1, 2, (16,), None),
|
| 1669 |
+
"F": ("F;32F", II, 1, 3, (32,), None),
|
| 1670 |
+
"RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
|
| 1671 |
+
"RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
|
| 1672 |
+
"RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
|
| 1673 |
+
"CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
|
| 1674 |
+
"YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
|
| 1675 |
+
"LAB": ("LAB", II, 8, 1, (8, 8, 8), None),
|
| 1676 |
+
"I;32BS": ("I;32BS", MM, 1, 2, (32,), None),
|
| 1677 |
+
"I;16B": ("I;16B", MM, 1, 1, (16,), None),
|
| 1678 |
+
"I;16BS": ("I;16BS", MM, 1, 2, (16,), None),
|
| 1679 |
+
"F;32BF": ("F;32BF", MM, 1, 3, (32,), None),
|
| 1680 |
+
}
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 1684 |
+
try:
|
| 1685 |
+
rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
|
| 1686 |
+
except KeyError as e:
|
| 1687 |
+
msg = f"cannot write mode {im.mode} as TIFF"
|
| 1688 |
+
raise OSError(msg) from e
|
| 1689 |
+
|
| 1690 |
+
encoderinfo = im.encoderinfo
|
| 1691 |
+
encoderconfig = im.encoderconfig
|
| 1692 |
+
|
| 1693 |
+
ifd = ImageFileDirectory_v2(prefix=prefix)
|
| 1694 |
+
if encoderinfo.get("big_tiff"):
|
| 1695 |
+
ifd._bigtiff = True
|
| 1696 |
+
|
| 1697 |
+
try:
|
| 1698 |
+
compression = encoderinfo["compression"]
|
| 1699 |
+
except KeyError:
|
| 1700 |
+
compression = im.info.get("compression")
|
| 1701 |
+
if isinstance(compression, int):
|
| 1702 |
+
# compression value may be from BMP. Ignore it
|
| 1703 |
+
compression = None
|
| 1704 |
+
if compression is None:
|
| 1705 |
+
compression = "raw"
|
| 1706 |
+
elif compression == "tiff_jpeg":
|
| 1707 |
+
# OJPEG is obsolete, so use new-style JPEG compression instead
|
| 1708 |
+
compression = "jpeg"
|
| 1709 |
+
elif compression == "tiff_deflate":
|
| 1710 |
+
compression = "tiff_adobe_deflate"
|
| 1711 |
+
|
| 1712 |
+
libtiff = WRITE_LIBTIFF or compression != "raw"
|
| 1713 |
+
|
| 1714 |
+
# required for color libtiff images
|
| 1715 |
+
ifd[PLANAR_CONFIGURATION] = 1
|
| 1716 |
+
|
| 1717 |
+
ifd[IMAGEWIDTH] = im.size[0]
|
| 1718 |
+
ifd[IMAGELENGTH] = im.size[1]
|
| 1719 |
+
|
| 1720 |
+
# write any arbitrary tags passed in as an ImageFileDirectory
|
| 1721 |
+
if "tiffinfo" in encoderinfo:
|
| 1722 |
+
info = encoderinfo["tiffinfo"]
|
| 1723 |
+
elif "exif" in encoderinfo:
|
| 1724 |
+
info = encoderinfo["exif"]
|
| 1725 |
+
if isinstance(info, bytes):
|
| 1726 |
+
exif = Image.Exif()
|
| 1727 |
+
exif.load(info)
|
| 1728 |
+
info = exif
|
| 1729 |
+
else:
|
| 1730 |
+
info = {}
|
| 1731 |
+
logger.debug("Tiffinfo Keys: %s", list(info))
|
| 1732 |
+
if isinstance(info, ImageFileDirectory_v1):
|
| 1733 |
+
info = info.to_v2()
|
| 1734 |
+
for key in info:
|
| 1735 |
+
if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
|
| 1736 |
+
ifd[key] = info.get_ifd(key)
|
| 1737 |
+
else:
|
| 1738 |
+
ifd[key] = info.get(key)
|
| 1739 |
+
try:
|
| 1740 |
+
ifd.tagtype[key] = info.tagtype[key]
|
| 1741 |
+
except Exception:
|
| 1742 |
+
pass # might not be an IFD. Might not have populated type
|
| 1743 |
+
|
| 1744 |
+
legacy_ifd = {}
|
| 1745 |
+
if hasattr(im, "tag"):
|
| 1746 |
+
legacy_ifd = im.tag.to_v2()
|
| 1747 |
+
|
| 1748 |
+
supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
|
| 1749 |
+
for tag in (
|
| 1750 |
+
# IFD offset that may not be correct in the saved image
|
| 1751 |
+
EXIFIFD,
|
| 1752 |
+
# Determined by the image format and should not be copied from legacy_ifd.
|
| 1753 |
+
SAMPLEFORMAT,
|
| 1754 |
+
):
|
| 1755 |
+
if tag in supplied_tags:
|
| 1756 |
+
del supplied_tags[tag]
|
| 1757 |
+
|
| 1758 |
+
# additions written by Greg Couch, gregc@cgl.ucsf.edu
|
| 1759 |
+
# inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
|
| 1760 |
+
if hasattr(im, "tag_v2"):
|
| 1761 |
+
# preserve tags from original TIFF image file
|
| 1762 |
+
for key in (
|
| 1763 |
+
RESOLUTION_UNIT,
|
| 1764 |
+
X_RESOLUTION,
|
| 1765 |
+
Y_RESOLUTION,
|
| 1766 |
+
IPTC_NAA_CHUNK,
|
| 1767 |
+
PHOTOSHOP_CHUNK,
|
| 1768 |
+
XMP,
|
| 1769 |
+
):
|
| 1770 |
+
if key in im.tag_v2:
|
| 1771 |
+
if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (
|
| 1772 |
+
TiffTags.BYTE,
|
| 1773 |
+
TiffTags.UNDEFINED,
|
| 1774 |
+
):
|
| 1775 |
+
del supplied_tags[key]
|
| 1776 |
+
else:
|
| 1777 |
+
ifd[key] = im.tag_v2[key]
|
| 1778 |
+
ifd.tagtype[key] = im.tag_v2.tagtype[key]
|
| 1779 |
+
|
| 1780 |
+
# preserve ICC profile (should also work when saving other formats
|
| 1781 |
+
# which support profiles as TIFF) -- 2008-06-06 Florian Hoech
|
| 1782 |
+
icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1783 |
+
if icc:
|
| 1784 |
+
ifd[ICCPROFILE] = icc
|
| 1785 |
+
|
| 1786 |
+
for key, name in [
|
| 1787 |
+
(IMAGEDESCRIPTION, "description"),
|
| 1788 |
+
(X_RESOLUTION, "resolution"),
|
| 1789 |
+
(Y_RESOLUTION, "resolution"),
|
| 1790 |
+
(X_RESOLUTION, "x_resolution"),
|
| 1791 |
+
(Y_RESOLUTION, "y_resolution"),
|
| 1792 |
+
(RESOLUTION_UNIT, "resolution_unit"),
|
| 1793 |
+
(SOFTWARE, "software"),
|
| 1794 |
+
(DATE_TIME, "date_time"),
|
| 1795 |
+
(ARTIST, "artist"),
|
| 1796 |
+
(COPYRIGHT, "copyright"),
|
| 1797 |
+
]:
|
| 1798 |
+
if name in encoderinfo:
|
| 1799 |
+
ifd[key] = encoderinfo[name]
|
| 1800 |
+
|
| 1801 |
+
dpi = encoderinfo.get("dpi")
|
| 1802 |
+
if dpi:
|
| 1803 |
+
ifd[RESOLUTION_UNIT] = 2
|
| 1804 |
+
ifd[X_RESOLUTION] = dpi[0]
|
| 1805 |
+
ifd[Y_RESOLUTION] = dpi[1]
|
| 1806 |
+
|
| 1807 |
+
if bits != (1,):
|
| 1808 |
+
ifd[BITSPERSAMPLE] = bits
|
| 1809 |
+
if len(bits) != 1:
|
| 1810 |
+
ifd[SAMPLESPERPIXEL] = len(bits)
|
| 1811 |
+
if extra is not None:
|
| 1812 |
+
ifd[EXTRASAMPLES] = extra
|
| 1813 |
+
if format != 1:
|
| 1814 |
+
ifd[SAMPLEFORMAT] = format
|
| 1815 |
+
|
| 1816 |
+
if PHOTOMETRIC_INTERPRETATION not in ifd:
|
| 1817 |
+
ifd[PHOTOMETRIC_INTERPRETATION] = photo
|
| 1818 |
+
elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:
|
| 1819 |
+
if im.mode == "1":
|
| 1820 |
+
inverted_im = im.copy()
|
| 1821 |
+
px = inverted_im.load()
|
| 1822 |
+
if px is not None:
|
| 1823 |
+
for y in range(inverted_im.height):
|
| 1824 |
+
for x in range(inverted_im.width):
|
| 1825 |
+
px[x, y] = 0 if px[x, y] == 255 else 255
|
| 1826 |
+
im = inverted_im
|
| 1827 |
+
else:
|
| 1828 |
+
im = ImageOps.invert(im)
|
| 1829 |
+
|
| 1830 |
+
if im.mode in ["P", "PA"]:
|
| 1831 |
+
lut = im.im.getpalette("RGB", "RGB;L")
|
| 1832 |
+
colormap = []
|
| 1833 |
+
colors = len(lut) // 3
|
| 1834 |
+
for i in range(3):
|
| 1835 |
+
colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]
|
| 1836 |
+
colormap += [0] * (256 - colors)
|
| 1837 |
+
ifd[COLORMAP] = colormap
|
| 1838 |
+
# data orientation
|
| 1839 |
+
w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]
|
| 1840 |
+
stride = len(bits) * ((w * bits[0] + 7) // 8)
|
| 1841 |
+
if ROWSPERSTRIP not in ifd:
|
| 1842 |
+
# aim for given strip size (64 KB by default) when using libtiff writer
|
| 1843 |
+
if libtiff:
|
| 1844 |
+
im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)
|
| 1845 |
+
rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)
|
| 1846 |
+
# JPEG encoder expects multiple of 8 rows
|
| 1847 |
+
if compression == "jpeg":
|
| 1848 |
+
rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)
|
| 1849 |
+
else:
|
| 1850 |
+
rows_per_strip = h
|
| 1851 |
+
if rows_per_strip == 0:
|
| 1852 |
+
rows_per_strip = 1
|
| 1853 |
+
ifd[ROWSPERSTRIP] = rows_per_strip
|
| 1854 |
+
strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]
|
| 1855 |
+
strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]
|
| 1856 |
+
if strip_byte_counts >= 2**16:
|
| 1857 |
+
ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
|
| 1858 |
+
ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (
|
| 1859 |
+
stride * h - strip_byte_counts * (strips_per_image - 1),
|
| 1860 |
+
)
|
| 1861 |
+
ifd[STRIPOFFSETS] = tuple(
|
| 1862 |
+
range(0, strip_byte_counts * strips_per_image, strip_byte_counts)
|
| 1863 |
+
) # this is adjusted by IFD writer
|
| 1864 |
+
# no compression by default:
|
| 1865 |
+
ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
|
| 1866 |
+
|
| 1867 |
+
if im.mode == "YCbCr":
|
| 1868 |
+
for tag, default_value in {
|
| 1869 |
+
YCBCRSUBSAMPLING: (1, 1),
|
| 1870 |
+
REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),
|
| 1871 |
+
}.items():
|
| 1872 |
+
ifd.setdefault(tag, default_value)
|
| 1873 |
+
|
| 1874 |
+
blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]
|
| 1875 |
+
if libtiff:
|
| 1876 |
+
if "quality" in encoderinfo:
|
| 1877 |
+
quality = encoderinfo["quality"]
|
| 1878 |
+
if not isinstance(quality, int) or quality < 0 or quality > 100:
|
| 1879 |
+
msg = "Invalid quality setting"
|
| 1880 |
+
raise ValueError(msg)
|
| 1881 |
+
if compression != "jpeg":
|
| 1882 |
+
msg = "quality setting only supported for 'jpeg' compression"
|
| 1883 |
+
raise ValueError(msg)
|
| 1884 |
+
ifd[JPEGQUALITY] = quality
|
| 1885 |
+
|
| 1886 |
+
logger.debug("Saving using libtiff encoder")
|
| 1887 |
+
logger.debug("Items: %s", sorted(ifd.items()))
|
| 1888 |
+
_fp = 0
|
| 1889 |
+
if hasattr(fp, "fileno"):
|
| 1890 |
+
try:
|
| 1891 |
+
fp.seek(0)
|
| 1892 |
+
_fp = fp.fileno()
|
| 1893 |
+
except io.UnsupportedOperation:
|
| 1894 |
+
pass
|
| 1895 |
+
|
| 1896 |
+
# optional types for non core tags
|
| 1897 |
+
types = {}
|
| 1898 |
+
# STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
|
| 1899 |
+
# based on the data in the strip.
|
| 1900 |
+
# OSUBFILETYPE is deprecated.
|
| 1901 |
+
# The other tags expect arrays with a certain length (fixed or depending on
|
| 1902 |
+
# BITSPERSAMPLE, etc), passing arrays with a different length will result in
|
| 1903 |
+
# segfaults. Block these tags until we add extra validation.
|
| 1904 |
+
# SUBIFD may also cause a segfault.
|
| 1905 |
+
blocklist += [
|
| 1906 |
+
OSUBFILETYPE,
|
| 1907 |
+
REFERENCEBLACKWHITE,
|
| 1908 |
+
STRIPBYTECOUNTS,
|
| 1909 |
+
STRIPOFFSETS,
|
| 1910 |
+
TRANSFERFUNCTION,
|
| 1911 |
+
SUBIFD,
|
| 1912 |
+
]
|
| 1913 |
+
|
| 1914 |
+
# bits per sample is a single short in the tiff directory, not a list.
|
| 1915 |
+
atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
|
| 1916 |
+
# Merge the ones that we have with (optional) more bits from
|
| 1917 |
+
# the original file, e.g x,y resolution so that we can
|
| 1918 |
+
# save(load('')) == original file.
|
| 1919 |
+
for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
|
| 1920 |
+
# Libtiff can only process certain core items without adding
|
| 1921 |
+
# them to the custom dictionary.
|
| 1922 |
+
# Custom items are supported for int, float, unicode, string and byte
|
| 1923 |
+
# values. Other types and tuples require a tagtype.
|
| 1924 |
+
if tag not in TiffTags.LIBTIFF_CORE:
|
| 1925 |
+
if not getattr(Image.core, "libtiff_support_custom_tags", False):
|
| 1926 |
+
continue
|
| 1927 |
+
|
| 1928 |
+
if tag in TiffTags.TAGS_V2_GROUPS:
|
| 1929 |
+
types[tag] = TiffTags.LONG8
|
| 1930 |
+
elif tag in ifd.tagtype:
|
| 1931 |
+
types[tag] = ifd.tagtype[tag]
|
| 1932 |
+
elif not (isinstance(value, (int, float, str, bytes))):
|
| 1933 |
+
continue
|
| 1934 |
+
else:
|
| 1935 |
+
type = TiffTags.lookup(tag).type
|
| 1936 |
+
if type:
|
| 1937 |
+
types[tag] = type
|
| 1938 |
+
if tag not in atts and tag not in blocklist:
|
| 1939 |
+
if isinstance(value, str):
|
| 1940 |
+
atts[tag] = value.encode("ascii", "replace") + b"\0"
|
| 1941 |
+
elif isinstance(value, IFDRational):
|
| 1942 |
+
atts[tag] = float(value)
|
| 1943 |
+
else:
|
| 1944 |
+
atts[tag] = value
|
| 1945 |
+
|
| 1946 |
+
if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:
|
| 1947 |
+
atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]
|
| 1948 |
+
|
| 1949 |
+
logger.debug("Converted items: %s", sorted(atts.items()))
|
| 1950 |
+
|
| 1951 |
+
# libtiff always expects the bytes in native order.
|
| 1952 |
+
# we're storing image byte order. So, if the rawmode
|
| 1953 |
+
# contains I;16, we need to convert from native to image
|
| 1954 |
+
# byte order.
|
| 1955 |
+
if im.mode in ("I;16B", "I;16"):
|
| 1956 |
+
rawmode = "I;16N"
|
| 1957 |
+
|
| 1958 |
+
# Pass tags as sorted list so that the tags are set in a fixed order.
|
| 1959 |
+
# This is required by libtiff for some tags. For example, the JPEGQUALITY
|
| 1960 |
+
# pseudo tag requires that the COMPRESS tag was already set.
|
| 1961 |
+
tags = list(atts.items())
|
| 1962 |
+
tags.sort()
|
| 1963 |
+
a = (rawmode, compression, _fp, filename, tags, types)
|
| 1964 |
+
encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
|
| 1965 |
+
encoder.setimage(im.im, (0, 0) + im.size)
|
| 1966 |
+
while True:
|
| 1967 |
+
errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:]
|
| 1968 |
+
if not _fp:
|
| 1969 |
+
fp.write(data)
|
| 1970 |
+
if errcode:
|
| 1971 |
+
break
|
| 1972 |
+
if errcode < 0:
|
| 1973 |
+
msg = f"encoder error {errcode} when writing image file"
|
| 1974 |
+
raise OSError(msg)
|
| 1975 |
+
|
| 1976 |
+
else:
|
| 1977 |
+
for tag in blocklist:
|
| 1978 |
+
del ifd[tag]
|
| 1979 |
+
offset = ifd.save(fp)
|
| 1980 |
+
|
| 1981 |
+
ImageFile._save(
|
| 1982 |
+
im,
|
| 1983 |
+
fp,
|
| 1984 |
+
[ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))],
|
| 1985 |
+
)
|
| 1986 |
+
|
| 1987 |
+
# -- helper for multi-page save --
|
| 1988 |
+
if "_debug_multipage" in encoderinfo:
|
| 1989 |
+
# just to access o32 and o16 (using correct byte order)
|
| 1990 |
+
setattr(im, "_debug_multipage", ifd)
|
| 1991 |
+
|
| 1992 |
+
|
| 1993 |
+
class AppendingTiffWriter(io.BytesIO):
|
| 1994 |
+
fieldSizes = [
|
| 1995 |
+
0, # None
|
| 1996 |
+
1, # byte
|
| 1997 |
+
1, # ascii
|
| 1998 |
+
2, # short
|
| 1999 |
+
4, # long
|
| 2000 |
+
8, # rational
|
| 2001 |
+
1, # sbyte
|
| 2002 |
+
1, # undefined
|
| 2003 |
+
2, # sshort
|
| 2004 |
+
4, # slong
|
| 2005 |
+
8, # srational
|
| 2006 |
+
4, # float
|
| 2007 |
+
8, # double
|
| 2008 |
+
4, # ifd
|
| 2009 |
+
2, # unicode
|
| 2010 |
+
4, # complex
|
| 2011 |
+
8, # long8
|
| 2012 |
+
]
|
| 2013 |
+
|
| 2014 |
+
Tags = {
|
| 2015 |
+
273, # StripOffsets
|
| 2016 |
+
288, # FreeOffsets
|
| 2017 |
+
324, # TileOffsets
|
| 2018 |
+
519, # JPEGQTables
|
| 2019 |
+
520, # JPEGDCTables
|
| 2020 |
+
521, # JPEGACTables
|
| 2021 |
+
}
|
| 2022 |
+
|
| 2023 |
+
def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None:
|
| 2024 |
+
self.f: IO[bytes]
|
| 2025 |
+
if is_path(fn):
|
| 2026 |
+
self.name = fn
|
| 2027 |
+
self.close_fp = True
|
| 2028 |
+
try:
|
| 2029 |
+
self.f = open(fn, "w+b" if new else "r+b")
|
| 2030 |
+
except OSError:
|
| 2031 |
+
self.f = open(fn, "w+b")
|
| 2032 |
+
else:
|
| 2033 |
+
self.f = cast(IO[bytes], fn)
|
| 2034 |
+
self.close_fp = False
|
| 2035 |
+
self.beginning = self.f.tell()
|
| 2036 |
+
self.setup()
|
| 2037 |
+
|
| 2038 |
+
def setup(self) -> None:
|
| 2039 |
+
# Reset everything.
|
| 2040 |
+
self.f.seek(self.beginning, os.SEEK_SET)
|
| 2041 |
+
|
| 2042 |
+
self.whereToWriteNewIFDOffset: int | None = None
|
| 2043 |
+
self.offsetOfNewPage = 0
|
| 2044 |
+
|
| 2045 |
+
self.IIMM = iimm = self.f.read(4)
|
| 2046 |
+
if not iimm:
|
| 2047 |
+
# empty file - first page
|
| 2048 |
+
self.isFirst = True
|
| 2049 |
+
return
|
| 2050 |
+
|
| 2051 |
+
self.isFirst = False
|
| 2052 |
+
if iimm == b"II\x2a\x00":
|
| 2053 |
+
self.setEndian("<")
|
| 2054 |
+
elif iimm == b"MM\x00\x2a":
|
| 2055 |
+
self.setEndian(">")
|
| 2056 |
+
else:
|
| 2057 |
+
msg = "Invalid TIFF file header"
|
| 2058 |
+
raise RuntimeError(msg)
|
| 2059 |
+
|
| 2060 |
+
self.skipIFDs()
|
| 2061 |
+
self.goToEnd()
|
| 2062 |
+
|
| 2063 |
+
def finalize(self) -> None:
|
| 2064 |
+
if self.isFirst:
|
| 2065 |
+
return
|
| 2066 |
+
|
| 2067 |
+
# fix offsets
|
| 2068 |
+
self.f.seek(self.offsetOfNewPage)
|
| 2069 |
+
|
| 2070 |
+
iimm = self.f.read(4)
|
| 2071 |
+
if not iimm:
|
| 2072 |
+
# Make it easy to finish a frame without committing to a new one.
|
| 2073 |
+
return
|
| 2074 |
+
|
| 2075 |
+
if iimm != self.IIMM:
|
| 2076 |
+
msg = "IIMM of new page doesn't match IIMM of first page"
|
| 2077 |
+
raise RuntimeError(msg)
|
| 2078 |
+
|
| 2079 |
+
ifd_offset = self.readLong()
|
| 2080 |
+
ifd_offset += self.offsetOfNewPage
|
| 2081 |
+
assert self.whereToWriteNewIFDOffset is not None
|
| 2082 |
+
self.f.seek(self.whereToWriteNewIFDOffset)
|
| 2083 |
+
self.writeLong(ifd_offset)
|
| 2084 |
+
self.f.seek(ifd_offset)
|
| 2085 |
+
self.fixIFD()
|
| 2086 |
+
|
| 2087 |
+
def newFrame(self) -> None:
|
| 2088 |
+
# Call this to finish a frame.
|
| 2089 |
+
self.finalize()
|
| 2090 |
+
self.setup()
|
| 2091 |
+
|
| 2092 |
+
def __enter__(self) -> AppendingTiffWriter:
|
| 2093 |
+
return self
|
| 2094 |
+
|
| 2095 |
+
def __exit__(self, *args: object) -> None:
|
| 2096 |
+
if self.close_fp:
|
| 2097 |
+
self.close()
|
| 2098 |
+
|
| 2099 |
+
def tell(self) -> int:
|
| 2100 |
+
return self.f.tell() - self.offsetOfNewPage
|
| 2101 |
+
|
| 2102 |
+
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
|
| 2103 |
+
"""
|
| 2104 |
+
:param offset: Distance to seek.
|
| 2105 |
+
:param whence: Whether the distance is relative to the start,
|
| 2106 |
+
end or current position.
|
| 2107 |
+
:returns: The resulting position, relative to the start.
|
| 2108 |
+
"""
|
| 2109 |
+
if whence == os.SEEK_SET:
|
| 2110 |
+
offset += self.offsetOfNewPage
|
| 2111 |
+
|
| 2112 |
+
self.f.seek(offset, whence)
|
| 2113 |
+
return self.tell()
|
| 2114 |
+
|
| 2115 |
+
def goToEnd(self) -> None:
|
| 2116 |
+
self.f.seek(0, os.SEEK_END)
|
| 2117 |
+
pos = self.f.tell()
|
| 2118 |
+
|
| 2119 |
+
# pad to 16 byte boundary
|
| 2120 |
+
pad_bytes = 16 - pos % 16
|
| 2121 |
+
if 0 < pad_bytes < 16:
|
| 2122 |
+
self.f.write(bytes(pad_bytes))
|
| 2123 |
+
self.offsetOfNewPage = self.f.tell()
|
| 2124 |
+
|
| 2125 |
+
def setEndian(self, endian: str) -> None:
|
| 2126 |
+
self.endian = endian
|
| 2127 |
+
self.longFmt = f"{self.endian}L"
|
| 2128 |
+
self.shortFmt = f"{self.endian}H"
|
| 2129 |
+
self.tagFormat = f"{self.endian}HHL"
|
| 2130 |
+
|
| 2131 |
+
def skipIFDs(self) -> None:
|
| 2132 |
+
while True:
|
| 2133 |
+
ifd_offset = self.readLong()
|
| 2134 |
+
if ifd_offset == 0:
|
| 2135 |
+
self.whereToWriteNewIFDOffset = self.f.tell() - 4
|
| 2136 |
+
break
|
| 2137 |
+
|
| 2138 |
+
self.f.seek(ifd_offset)
|
| 2139 |
+
num_tags = self.readShort()
|
| 2140 |
+
self.f.seek(num_tags * 12, os.SEEK_CUR)
|
| 2141 |
+
|
| 2142 |
+
def write(self, data: Buffer, /) -> int:
|
| 2143 |
+
return self.f.write(data)
|
| 2144 |
+
|
| 2145 |
+
def _fmt(self, field_size: int) -> str:
|
| 2146 |
+
try:
|
| 2147 |
+
return {2: "H", 4: "L", 8: "Q"}[field_size]
|
| 2148 |
+
except KeyError:
|
| 2149 |
+
msg = "offset is not supported"
|
| 2150 |
+
raise RuntimeError(msg)
|
| 2151 |
+
|
| 2152 |
+
def _read(self, field_size: int) -> int:
|
| 2153 |
+
(value,) = struct.unpack(
|
| 2154 |
+
self.endian + self._fmt(field_size), self.f.read(field_size)
|
| 2155 |
+
)
|
| 2156 |
+
return value
|
| 2157 |
+
|
| 2158 |
+
def readShort(self) -> int:
|
| 2159 |
+
return self._read(2)
|
| 2160 |
+
|
| 2161 |
+
def readLong(self) -> int:
|
| 2162 |
+
return self._read(4)
|
| 2163 |
+
|
| 2164 |
+
@staticmethod
|
| 2165 |
+
def _verify_bytes_written(bytes_written: int | None, expected: int) -> None:
|
| 2166 |
+
if bytes_written is not None and bytes_written != expected:
|
| 2167 |
+
msg = f"wrote only {bytes_written} bytes but wanted {expected}"
|
| 2168 |
+
raise RuntimeError(msg)
|
| 2169 |
+
|
| 2170 |
+
def rewriteLastShortToLong(self, value: int) -> None:
|
| 2171 |
+
self.f.seek(-2, os.SEEK_CUR)
|
| 2172 |
+
bytes_written = self.f.write(struct.pack(self.longFmt, value))
|
| 2173 |
+
self._verify_bytes_written(bytes_written, 4)
|
| 2174 |
+
|
| 2175 |
+
def _rewriteLast(self, value: int, field_size: int) -> None:
|
| 2176 |
+
self.f.seek(-field_size, os.SEEK_CUR)
|
| 2177 |
+
bytes_written = self.f.write(
|
| 2178 |
+
struct.pack(self.endian + self._fmt(field_size), value)
|
| 2179 |
+
)
|
| 2180 |
+
self._verify_bytes_written(bytes_written, field_size)
|
| 2181 |
+
|
| 2182 |
+
def rewriteLastShort(self, value: int) -> None:
|
| 2183 |
+
return self._rewriteLast(value, 2)
|
| 2184 |
+
|
| 2185 |
+
def rewriteLastLong(self, value: int) -> None:
|
| 2186 |
+
return self._rewriteLast(value, 4)
|
| 2187 |
+
|
| 2188 |
+
def writeShort(self, value: int) -> None:
|
| 2189 |
+
bytes_written = self.f.write(struct.pack(self.shortFmt, value))
|
| 2190 |
+
self._verify_bytes_written(bytes_written, 2)
|
| 2191 |
+
|
| 2192 |
+
def writeLong(self, value: int) -> None:
|
| 2193 |
+
bytes_written = self.f.write(struct.pack(self.longFmt, value))
|
| 2194 |
+
self._verify_bytes_written(bytes_written, 4)
|
| 2195 |
+
|
| 2196 |
+
def close(self) -> None:
|
| 2197 |
+
self.finalize()
|
| 2198 |
+
if self.close_fp:
|
| 2199 |
+
self.f.close()
|
| 2200 |
+
|
| 2201 |
+
def fixIFD(self) -> None:
|
| 2202 |
+
num_tags = self.readShort()
|
| 2203 |
+
|
| 2204 |
+
for i in range(num_tags):
|
| 2205 |
+
tag, field_type, count = struct.unpack(self.tagFormat, self.f.read(8))
|
| 2206 |
+
|
| 2207 |
+
field_size = self.fieldSizes[field_type]
|
| 2208 |
+
total_size = field_size * count
|
| 2209 |
+
is_local = total_size <= 4
|
| 2210 |
+
if not is_local:
|
| 2211 |
+
offset = self.readLong() + self.offsetOfNewPage
|
| 2212 |
+
self.rewriteLastLong(offset)
|
| 2213 |
+
|
| 2214 |
+
if tag in self.Tags:
|
| 2215 |
+
cur_pos = self.f.tell()
|
| 2216 |
+
|
| 2217 |
+
if is_local:
|
| 2218 |
+
self._fixOffsets(count, field_size)
|
| 2219 |
+
self.f.seek(cur_pos + 4)
|
| 2220 |
+
else:
|
| 2221 |
+
self.f.seek(offset)
|
| 2222 |
+
self._fixOffsets(count, field_size)
|
| 2223 |
+
self.f.seek(cur_pos)
|
| 2224 |
+
|
| 2225 |
+
elif is_local:
|
| 2226 |
+
# skip the locally stored value that is not an offset
|
| 2227 |
+
self.f.seek(4, os.SEEK_CUR)
|
| 2228 |
+
|
| 2229 |
+
def _fixOffsets(self, count: int, field_size: int) -> None:
|
| 2230 |
+
for i in range(count):
|
| 2231 |
+
offset = self._read(field_size)
|
| 2232 |
+
offset += self.offsetOfNewPage
|
| 2233 |
+
if field_size == 2 and offset >= 65536:
|
| 2234 |
+
# offset is now too large - we must convert shorts to longs
|
| 2235 |
+
if count != 1:
|
| 2236 |
+
msg = "not implemented"
|
| 2237 |
+
raise RuntimeError(msg) # XXX TODO
|
| 2238 |
+
|
| 2239 |
+
# simple case - the offset is just one and therefore it is
|
| 2240 |
+
# local (not referenced with another offset)
|
| 2241 |
+
self.rewriteLastShortToLong(offset)
|
| 2242 |
+
self.f.seek(-10, os.SEEK_CUR)
|
| 2243 |
+
self.writeShort(TiffTags.LONG) # rewrite the type to LONG
|
| 2244 |
+
self.f.seek(8, os.SEEK_CUR)
|
| 2245 |
+
else:
|
| 2246 |
+
self._rewriteLast(offset, field_size)
|
| 2247 |
+
|
| 2248 |
+
def fixOffsets(
|
| 2249 |
+
self, count: int, isShort: bool = False, isLong: bool = False
|
| 2250 |
+
) -> None:
|
| 2251 |
+
if isShort:
|
| 2252 |
+
field_size = 2
|
| 2253 |
+
elif isLong:
|
| 2254 |
+
field_size = 4
|
| 2255 |
+
else:
|
| 2256 |
+
field_size = 0
|
| 2257 |
+
return self._fixOffsets(count, field_size)
|
| 2258 |
+
|
| 2259 |
+
|
| 2260 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 2261 |
+
encoderinfo = im.encoderinfo.copy()
|
| 2262 |
+
encoderconfig = im.encoderconfig
|
| 2263 |
+
append_images = list(encoderinfo.get("append_images", []))
|
| 2264 |
+
if not hasattr(im, "n_frames") and not append_images:
|
| 2265 |
+
return _save(im, fp, filename)
|
| 2266 |
+
|
| 2267 |
+
cur_idx = im.tell()
|
| 2268 |
+
try:
|
| 2269 |
+
with AppendingTiffWriter(fp) as tf:
|
| 2270 |
+
for ims in [im] + append_images:
|
| 2271 |
+
ims.encoderinfo = encoderinfo
|
| 2272 |
+
ims.encoderconfig = encoderconfig
|
| 2273 |
+
if not hasattr(ims, "n_frames"):
|
| 2274 |
+
nfr = 1
|
| 2275 |
+
else:
|
| 2276 |
+
nfr = ims.n_frames
|
| 2277 |
+
|
| 2278 |
+
for idx in range(nfr):
|
| 2279 |
+
ims.seek(idx)
|
| 2280 |
+
ims.load()
|
| 2281 |
+
_save(ims, tf, filename)
|
| 2282 |
+
tf.newFrame()
|
| 2283 |
+
finally:
|
| 2284 |
+
im.seek(cur_idx)
|
| 2285 |
+
|
| 2286 |
+
|
| 2287 |
+
#
|
| 2288 |
+
# --------------------------------------------------------------------
|
| 2289 |
+
# Register
|
| 2290 |
+
|
| 2291 |
+
Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
|
| 2292 |
+
Image.register_save(TiffImageFile.format, _save)
|
| 2293 |
+
Image.register_save_all(TiffImageFile.format, _save_all)
|
| 2294 |
+
|
| 2295 |
+
Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"])
|
| 2296 |
+
|
| 2297 |
+
Image.register_mime(TiffImageFile.format, "image/tiff")
|
lib/python3.10/site-packages/PIL/TiffTags.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
33432: ("Copyright", ASCII, 1),
|
| 207 |
+
33723: ("IptcNaaInfo", UNDEFINED, 1),
|
| 208 |
+
34377: ("PhotoshopInfo", BYTE, 0),
|
| 209 |
+
# FIXME add more tags here
|
| 210 |
+
34665: ("ExifIFD", LONG, 1),
|
| 211 |
+
34675: ("ICCProfile", UNDEFINED, 1),
|
| 212 |
+
34853: ("GPSInfoIFD", LONG, 1),
|
| 213 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 214 |
+
37724: ("ImageSourceData", UNDEFINED, 1),
|
| 215 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 216 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 217 |
+
# MPInfo
|
| 218 |
+
45056: ("MPFVersion", UNDEFINED, 1),
|
| 219 |
+
45057: ("NumberOfImages", LONG, 1),
|
| 220 |
+
45058: ("MPEntry", UNDEFINED, 1),
|
| 221 |
+
45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
|
| 222 |
+
45060: ("TotalFrames", LONG, 1),
|
| 223 |
+
45313: ("MPIndividualNum", LONG, 1),
|
| 224 |
+
45569: ("PanOrientation", LONG, 1),
|
| 225 |
+
45570: ("PanOverlap_H", RATIONAL, 1),
|
| 226 |
+
45571: ("PanOverlap_V", RATIONAL, 1),
|
| 227 |
+
45572: ("BaseViewpointNum", LONG, 1),
|
| 228 |
+
45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
|
| 229 |
+
45574: ("BaselineLength", RATIONAL, 1),
|
| 230 |
+
45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
|
| 231 |
+
45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
|
| 232 |
+
45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
|
| 233 |
+
45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
|
| 234 |
+
45579: ("YawAngle", SIGNED_RATIONAL, 1),
|
| 235 |
+
45580: ("PitchAngle", SIGNED_RATIONAL, 1),
|
| 236 |
+
45581: ("RollAngle", SIGNED_RATIONAL, 1),
|
| 237 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 238 |
+
50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
|
| 239 |
+
50780: ("BestQualityScale", RATIONAL, 1),
|
| 240 |
+
50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
|
| 241 |
+
50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
|
| 242 |
+
}
|
| 243 |
+
_tags_v2_groups = {
|
| 244 |
+
# ExifIFD
|
| 245 |
+
34665: {
|
| 246 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 247 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 248 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 249 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 250 |
+
},
|
| 251 |
+
# GPSInfoIFD
|
| 252 |
+
34853: {
|
| 253 |
+
0: ("GPSVersionID", BYTE, 4),
|
| 254 |
+
1: ("GPSLatitudeRef", ASCII, 2),
|
| 255 |
+
2: ("GPSLatitude", RATIONAL, 3),
|
| 256 |
+
3: ("GPSLongitudeRef", ASCII, 2),
|
| 257 |
+
4: ("GPSLongitude", RATIONAL, 3),
|
| 258 |
+
5: ("GPSAltitudeRef", BYTE, 1),
|
| 259 |
+
6: ("GPSAltitude", RATIONAL, 1),
|
| 260 |
+
7: ("GPSTimeStamp", RATIONAL, 3),
|
| 261 |
+
8: ("GPSSatellites", ASCII, 0),
|
| 262 |
+
9: ("GPSStatus", ASCII, 2),
|
| 263 |
+
10: ("GPSMeasureMode", ASCII, 2),
|
| 264 |
+
11: ("GPSDOP", RATIONAL, 1),
|
| 265 |
+
12: ("GPSSpeedRef", ASCII, 2),
|
| 266 |
+
13: ("GPSSpeed", RATIONAL, 1),
|
| 267 |
+
14: ("GPSTrackRef", ASCII, 2),
|
| 268 |
+
15: ("GPSTrack", RATIONAL, 1),
|
| 269 |
+
16: ("GPSImgDirectionRef", ASCII, 2),
|
| 270 |
+
17: ("GPSImgDirection", RATIONAL, 1),
|
| 271 |
+
18: ("GPSMapDatum", ASCII, 0),
|
| 272 |
+
19: ("GPSDestLatitudeRef", ASCII, 2),
|
| 273 |
+
20: ("GPSDestLatitude", RATIONAL, 3),
|
| 274 |
+
21: ("GPSDestLongitudeRef", ASCII, 2),
|
| 275 |
+
22: ("GPSDestLongitude", RATIONAL, 3),
|
| 276 |
+
23: ("GPSDestBearingRef", ASCII, 2),
|
| 277 |
+
24: ("GPSDestBearing", RATIONAL, 1),
|
| 278 |
+
25: ("GPSDestDistanceRef", ASCII, 2),
|
| 279 |
+
26: ("GPSDestDistance", RATIONAL, 1),
|
| 280 |
+
27: ("GPSProcessingMethod", UNDEFINED, 0),
|
| 281 |
+
28: ("GPSAreaInformation", UNDEFINED, 0),
|
| 282 |
+
29: ("GPSDateStamp", ASCII, 11),
|
| 283 |
+
30: ("GPSDifferential", SHORT, 1),
|
| 284 |
+
},
|
| 285 |
+
# InteroperabilityIFD
|
| 286 |
+
40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
# Legacy Tags structure
|
| 290 |
+
# these tags aren't included above, but were in the previous versions
|
| 291 |
+
TAGS: dict[int | tuple[int, int], str] = {
|
| 292 |
+
347: "JPEGTables",
|
| 293 |
+
700: "XMP",
|
| 294 |
+
# Additional Exif Info
|
| 295 |
+
32932: "Wang Annotation",
|
| 296 |
+
33434: "ExposureTime",
|
| 297 |
+
33437: "FNumber",
|
| 298 |
+
33445: "MD FileTag",
|
| 299 |
+
33446: "MD ScalePixel",
|
| 300 |
+
33447: "MD ColorTable",
|
| 301 |
+
33448: "MD LabName",
|
| 302 |
+
33449: "MD SampleInfo",
|
| 303 |
+
33450: "MD PrepDate",
|
| 304 |
+
33451: "MD PrepTime",
|
| 305 |
+
33452: "MD FileUnits",
|
| 306 |
+
33550: "ModelPixelScaleTag",
|
| 307 |
+
33723: "IptcNaaInfo",
|
| 308 |
+
33918: "INGR Packet Data Tag",
|
| 309 |
+
33919: "INGR Flag Registers",
|
| 310 |
+
33920: "IrasB Transformation Matrix",
|
| 311 |
+
33922: "ModelTiepointTag",
|
| 312 |
+
34264: "ModelTransformationTag",
|
| 313 |
+
34377: "PhotoshopInfo",
|
| 314 |
+
34735: "GeoKeyDirectoryTag",
|
| 315 |
+
34736: "GeoDoubleParamsTag",
|
| 316 |
+
34737: "GeoAsciiParamsTag",
|
| 317 |
+
34850: "ExposureProgram",
|
| 318 |
+
34852: "SpectralSensitivity",
|
| 319 |
+
34855: "ISOSpeedRatings",
|
| 320 |
+
34856: "OECF",
|
| 321 |
+
34864: "SensitivityType",
|
| 322 |
+
34865: "StandardOutputSensitivity",
|
| 323 |
+
34866: "RecommendedExposureIndex",
|
| 324 |
+
34867: "ISOSpeed",
|
| 325 |
+
34868: "ISOSpeedLatitudeyyy",
|
| 326 |
+
34869: "ISOSpeedLatitudezzz",
|
| 327 |
+
34908: "HylaFAX FaxRecvParams",
|
| 328 |
+
34909: "HylaFAX FaxSubAddress",
|
| 329 |
+
34910: "HylaFAX FaxRecvTime",
|
| 330 |
+
36864: "ExifVersion",
|
| 331 |
+
36867: "DateTimeOriginal",
|
| 332 |
+
36868: "DateTimeDigitized",
|
| 333 |
+
37121: "ComponentsConfiguration",
|
| 334 |
+
37122: "CompressedBitsPerPixel",
|
| 335 |
+
37724: "ImageSourceData",
|
| 336 |
+
37377: "ShutterSpeedValue",
|
| 337 |
+
37378: "ApertureValue",
|
| 338 |
+
37379: "BrightnessValue",
|
| 339 |
+
37380: "ExposureBiasValue",
|
| 340 |
+
37381: "MaxApertureValue",
|
| 341 |
+
37382: "SubjectDistance",
|
| 342 |
+
37383: "MeteringMode",
|
| 343 |
+
37384: "LightSource",
|
| 344 |
+
37385: "Flash",
|
| 345 |
+
37386: "FocalLength",
|
| 346 |
+
37396: "SubjectArea",
|
| 347 |
+
37500: "MakerNote",
|
| 348 |
+
37510: "UserComment",
|
| 349 |
+
37520: "SubSec",
|
| 350 |
+
37521: "SubSecTimeOriginal",
|
| 351 |
+
37522: "SubsecTimeDigitized",
|
| 352 |
+
40960: "FlashPixVersion",
|
| 353 |
+
40961: "ColorSpace",
|
| 354 |
+
40962: "PixelXDimension",
|
| 355 |
+
40963: "PixelYDimension",
|
| 356 |
+
40964: "RelatedSoundFile",
|
| 357 |
+
40965: "InteroperabilityIFD",
|
| 358 |
+
41483: "FlashEnergy",
|
| 359 |
+
41484: "SpatialFrequencyResponse",
|
| 360 |
+
41486: "FocalPlaneXResolution",
|
| 361 |
+
41487: "FocalPlaneYResolution",
|
| 362 |
+
41488: "FocalPlaneResolutionUnit",
|
| 363 |
+
41492: "SubjectLocation",
|
| 364 |
+
41493: "ExposureIndex",
|
| 365 |
+
41495: "SensingMethod",
|
| 366 |
+
41728: "FileSource",
|
| 367 |
+
41729: "SceneType",
|
| 368 |
+
41730: "CFAPattern",
|
| 369 |
+
41985: "CustomRendered",
|
| 370 |
+
41986: "ExposureMode",
|
| 371 |
+
41987: "WhiteBalance",
|
| 372 |
+
41988: "DigitalZoomRatio",
|
| 373 |
+
41989: "FocalLengthIn35mmFilm",
|
| 374 |
+
41990: "SceneCaptureType",
|
| 375 |
+
41991: "GainControl",
|
| 376 |
+
41992: "Contrast",
|
| 377 |
+
41993: "Saturation",
|
| 378 |
+
41994: "Sharpness",
|
| 379 |
+
41995: "DeviceSettingDescription",
|
| 380 |
+
41996: "SubjectDistanceRange",
|
| 381 |
+
42016: "ImageUniqueID",
|
| 382 |
+
42032: "CameraOwnerName",
|
| 383 |
+
42033: "BodySerialNumber",
|
| 384 |
+
42034: "LensSpecification",
|
| 385 |
+
42035: "LensMake",
|
| 386 |
+
42036: "LensModel",
|
| 387 |
+
42037: "LensSerialNumber",
|
| 388 |
+
42112: "GDAL_METADATA",
|
| 389 |
+
42113: "GDAL_NODATA",
|
| 390 |
+
42240: "Gamma",
|
| 391 |
+
50215: "Oce Scanjob Description",
|
| 392 |
+
50216: "Oce Application Selector",
|
| 393 |
+
50217: "Oce Identification Number",
|
| 394 |
+
50218: "Oce ImageLogic Characteristics",
|
| 395 |
+
# Adobe DNG
|
| 396 |
+
50706: "DNGVersion",
|
| 397 |
+
50707: "DNGBackwardVersion",
|
| 398 |
+
50708: "UniqueCameraModel",
|
| 399 |
+
50709: "LocalizedCameraModel",
|
| 400 |
+
50710: "CFAPlaneColor",
|
| 401 |
+
50711: "CFALayout",
|
| 402 |
+
50712: "LinearizationTable",
|
| 403 |
+
50713: "BlackLevelRepeatDim",
|
| 404 |
+
50714: "BlackLevel",
|
| 405 |
+
50715: "BlackLevelDeltaH",
|
| 406 |
+
50716: "BlackLevelDeltaV",
|
| 407 |
+
50717: "WhiteLevel",
|
| 408 |
+
50718: "DefaultScale",
|
| 409 |
+
50719: "DefaultCropOrigin",
|
| 410 |
+
50720: "DefaultCropSize",
|
| 411 |
+
50721: "ColorMatrix1",
|
| 412 |
+
50722: "ColorMatrix2",
|
| 413 |
+
50723: "CameraCalibration1",
|
| 414 |
+
50724: "CameraCalibration2",
|
| 415 |
+
50725: "ReductionMatrix1",
|
| 416 |
+
50726: "ReductionMatrix2",
|
| 417 |
+
50727: "AnalogBalance",
|
| 418 |
+
50728: "AsShotNeutral",
|
| 419 |
+
50729: "AsShotWhiteXY",
|
| 420 |
+
50730: "BaselineExposure",
|
| 421 |
+
50731: "BaselineNoise",
|
| 422 |
+
50732: "BaselineSharpness",
|
| 423 |
+
50733: "BayerGreenSplit",
|
| 424 |
+
50734: "LinearResponseLimit",
|
| 425 |
+
50735: "CameraSerialNumber",
|
| 426 |
+
50736: "LensInfo",
|
| 427 |
+
50737: "ChromaBlurRadius",
|
| 428 |
+
50738: "AntiAliasStrength",
|
| 429 |
+
50740: "DNGPrivateData",
|
| 430 |
+
50778: "CalibrationIlluminant1",
|
| 431 |
+
50779: "CalibrationIlluminant2",
|
| 432 |
+
50784: "Alias Layer Metadata",
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
TAGS_V2: dict[int, TagInfo] = {}
|
| 436 |
+
TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {}
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def _populate() -> None:
|
| 440 |
+
for k, v in _tags_v2.items():
|
| 441 |
+
# Populate legacy structure.
|
| 442 |
+
TAGS[k] = v[0]
|
| 443 |
+
if len(v) == 4:
|
| 444 |
+
for sk, sv in v[3].items():
|
| 445 |
+
TAGS[(k, sv)] = sk
|
| 446 |
+
|
| 447 |
+
TAGS_V2[k] = TagInfo(k, *v)
|
| 448 |
+
|
| 449 |
+
for group, tags in _tags_v2_groups.items():
|
| 450 |
+
TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()}
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
_populate()
|
| 454 |
+
##
|
| 455 |
+
# Map type numbers to type names -- defined in ImageFileDirectory.
|
| 456 |
+
|
| 457 |
+
TYPES: dict[int, str] = {}
|
| 458 |
+
|
| 459 |
+
#
|
| 460 |
+
# These tags are handled by default in libtiff, without
|
| 461 |
+
# adding to the custom dictionary. From tif_dir.c, searching for
|
| 462 |
+
# case TIFFTAG in the _TIFFVSetField function:
|
| 463 |
+
# Line: item.
|
| 464 |
+
# 148: case TIFFTAG_SUBFILETYPE:
|
| 465 |
+
# 151: case TIFFTAG_IMAGEWIDTH:
|
| 466 |
+
# 154: case TIFFTAG_IMAGELENGTH:
|
| 467 |
+
# 157: case TIFFTAG_BITSPERSAMPLE:
|
| 468 |
+
# 181: case TIFFTAG_COMPRESSION:
|
| 469 |
+
# 202: case TIFFTAG_PHOTOMETRIC:
|
| 470 |
+
# 205: case TIFFTAG_THRESHHOLDING:
|
| 471 |
+
# 208: case TIFFTAG_FILLORDER:
|
| 472 |
+
# 214: case TIFFTAG_ORIENTATION:
|
| 473 |
+
# 221: case TIFFTAG_SAMPLESPERPIXEL:
|
| 474 |
+
# 228: case TIFFTAG_ROWSPERSTRIP:
|
| 475 |
+
# 238: case TIFFTAG_MINSAMPLEVALUE:
|
| 476 |
+
# 241: case TIFFTAG_MAXSAMPLEVALUE:
|
| 477 |
+
# 244: case TIFFTAG_SMINSAMPLEVALUE:
|
| 478 |
+
# 247: case TIFFTAG_SMAXSAMPLEVALUE:
|
| 479 |
+
# 250: case TIFFTAG_XRESOLUTION:
|
| 480 |
+
# 256: case TIFFTAG_YRESOLUTION:
|
| 481 |
+
# 262: case TIFFTAG_PLANARCONFIG:
|
| 482 |
+
# 268: case TIFFTAG_XPOSITION:
|
| 483 |
+
# 271: case TIFFTAG_YPOSITION:
|
| 484 |
+
# 274: case TIFFTAG_RESOLUTIONUNIT:
|
| 485 |
+
# 280: case TIFFTAG_PAGENUMBER:
|
| 486 |
+
# 284: case TIFFTAG_HALFTONEHINTS:
|
| 487 |
+
# 288: case TIFFTAG_COLORMAP:
|
| 488 |
+
# 294: case TIFFTAG_EXTRASAMPLES:
|
| 489 |
+
# 298: case TIFFTAG_MATTEING:
|
| 490 |
+
# 305: case TIFFTAG_TILEWIDTH:
|
| 491 |
+
# 316: case TIFFTAG_TILELENGTH:
|
| 492 |
+
# 327: case TIFFTAG_TILEDEPTH:
|
| 493 |
+
# 333: case TIFFTAG_DATATYPE:
|
| 494 |
+
# 344: case TIFFTAG_SAMPLEFORMAT:
|
| 495 |
+
# 361: case TIFFTAG_IMAGEDEPTH:
|
| 496 |
+
# 364: case TIFFTAG_SUBIFD:
|
| 497 |
+
# 376: case TIFFTAG_YCBCRPOSITIONING:
|
| 498 |
+
# 379: case TIFFTAG_YCBCRSUBSAMPLING:
|
| 499 |
+
# 383: case TIFFTAG_TRANSFERFUNCTION:
|
| 500 |
+
# 389: case TIFFTAG_REFERENCEBLACKWHITE:
|
| 501 |
+
# 393: case TIFFTAG_INKNAMES:
|
| 502 |
+
|
| 503 |
+
# Following pseudo-tags are also handled by default in libtiff:
|
| 504 |
+
# TIFFTAG_JPEGQUALITY 65537
|
| 505 |
+
|
| 506 |
+
# some of these are not in our TAGS_V2 dict and were included from tiff.h
|
| 507 |
+
|
| 508 |
+
# This list also exists in encode.c
|
| 509 |
+
LIBTIFF_CORE = {
|
| 510 |
+
255,
|
| 511 |
+
256,
|
| 512 |
+
257,
|
| 513 |
+
258,
|
| 514 |
+
259,
|
| 515 |
+
262,
|
| 516 |
+
263,
|
| 517 |
+
266,
|
| 518 |
+
274,
|
| 519 |
+
277,
|
| 520 |
+
278,
|
| 521 |
+
280,
|
| 522 |
+
281,
|
| 523 |
+
340,
|
| 524 |
+
341,
|
| 525 |
+
282,
|
| 526 |
+
283,
|
| 527 |
+
284,
|
| 528 |
+
286,
|
| 529 |
+
287,
|
| 530 |
+
296,
|
| 531 |
+
297,
|
| 532 |
+
321,
|
| 533 |
+
320,
|
| 534 |
+
338,
|
| 535 |
+
32995,
|
| 536 |
+
322,
|
| 537 |
+
323,
|
| 538 |
+
32998,
|
| 539 |
+
32996,
|
| 540 |
+
339,
|
| 541 |
+
32997,
|
| 542 |
+
330,
|
| 543 |
+
531,
|
| 544 |
+
530,
|
| 545 |
+
301,
|
| 546 |
+
532,
|
| 547 |
+
333,
|
| 548 |
+
# as above
|
| 549 |
+
269, # this has been in our tests forever, and works
|
| 550 |
+
65537,
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
|
| 554 |
+
LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
|
| 555 |
+
LIBTIFF_CORE.remove(323) # Tiled images
|
| 556 |
+
LIBTIFF_CORE.remove(333) # Ink Names either
|
| 557 |
+
|
| 558 |
+
# Note to advanced users: There may be combinations of these
|
| 559 |
+
# parameters and values that when added properly, will work and
|
| 560 |
+
# produce valid tiff images that may work in your application.
|
| 561 |
+
# It is safe to add and remove tags from this set from Pillow's point
|
| 562 |
+
# of view so long as you test against libtiff.
|
lib/python3.10/site-packages/PIL/WmfImagePlugin.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
im.fp.seek(0) # rewind
|
| 53 |
+
return Image.frombytes(
|
| 54 |
+
"RGB",
|
| 55 |
+
im.size,
|
| 56 |
+
Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
|
| 57 |
+
"raw",
|
| 58 |
+
"BGR",
|
| 59 |
+
(im.size[0] * 3 + 3) & -4,
|
| 60 |
+
-1,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
register_handler(WmfHandler())
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
# --------------------------------------------------------------------
|
| 67 |
+
# Read WMF file
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _accept(prefix: bytes) -> bool:
|
| 71 |
+
return (
|
| 72 |
+
prefix[:6] == b"\xd7\xcd\xc6\x9a\x00\x00" or prefix[:4] == b"\x01\x00\x00\x00"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
##
|
| 77 |
+
# Image plugin for Windows metafiles.
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class WmfStubImageFile(ImageFile.StubImageFile):
|
| 81 |
+
format = "WMF"
|
| 82 |
+
format_description = "Windows Metafile"
|
| 83 |
+
|
| 84 |
+
def _open(self) -> None:
|
| 85 |
+
self._inch = None
|
| 86 |
+
|
| 87 |
+
# check placable header
|
| 88 |
+
s = self.fp.read(80)
|
| 89 |
+
|
| 90 |
+
if s[:6] == b"\xd7\xcd\xc6\x9a\x00\x00":
|
| 91 |
+
# placeable windows metafile
|
| 92 |
+
|
| 93 |
+
# get units per inch
|
| 94 |
+
self._inch = word(s, 14)
|
| 95 |
+
if self._inch == 0:
|
| 96 |
+
msg = "Invalid inch"
|
| 97 |
+
raise ValueError(msg)
|
| 98 |
+
|
| 99 |
+
# get bounding box
|
| 100 |
+
x0 = short(s, 6)
|
| 101 |
+
y0 = short(s, 8)
|
| 102 |
+
x1 = short(s, 10)
|
| 103 |
+
y1 = short(s, 12)
|
| 104 |
+
|
| 105 |
+
# normalize size to 72 dots per inch
|
| 106 |
+
self.info["dpi"] = 72
|
| 107 |
+
size = (
|
| 108 |
+
(x1 - x0) * self.info["dpi"] // self._inch,
|
| 109 |
+
(y1 - y0) * self.info["dpi"] // self._inch,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 113 |
+
|
| 114 |
+
# sanity check (standard metafile header)
|
| 115 |
+
if s[22:26] != b"\x01\x00\t\x00":
|
| 116 |
+
msg = "Unsupported WMF file format"
|
| 117 |
+
raise SyntaxError(msg)
|
| 118 |
+
|
| 119 |
+
elif s[:4] == b"\x01\x00\x00\x00" and s[40:44] == b" EMF":
|
| 120 |
+
# enhanced metafile
|
| 121 |
+
|
| 122 |
+
# get bounding box
|
| 123 |
+
x0 = _long(s, 8)
|
| 124 |
+
y0 = _long(s, 12)
|
| 125 |
+
x1 = _long(s, 16)
|
| 126 |
+
y1 = _long(s, 20)
|
| 127 |
+
|
| 128 |
+
# get frame (in 0.01 millimeter units)
|
| 129 |
+
frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
|
| 130 |
+
|
| 131 |
+
size = x1 - x0, y1 - y0
|
| 132 |
+
|
| 133 |
+
# calculate dots per inch from bbox and frame
|
| 134 |
+
xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
|
| 135 |
+
ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
|
| 136 |
+
|
| 137 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 138 |
+
|
| 139 |
+
if xdpi == ydpi:
|
| 140 |
+
self.info["dpi"] = xdpi
|
| 141 |
+
else:
|
| 142 |
+
self.info["dpi"] = 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(self, dpi: int | None = None) -> Image.core.PixelAccess | None:
|
| 159 |
+
if dpi is not None and self._inch is not None:
|
| 160 |
+
self.info["dpi"] = dpi
|
| 161 |
+
x0, y0, x1, y1 = self.info["wmf_bbox"]
|
| 162 |
+
self._size = (
|
| 163 |
+
(x1 - x0) * self.info["dpi"] // self._inch,
|
| 164 |
+
(y1 - y0) * self.info["dpi"] // self._inch,
|
| 165 |
+
)
|
| 166 |
+
return super().load()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 170 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 171 |
+
msg = "WMF save handler not installed"
|
| 172 |
+
raise OSError(msg)
|
| 173 |
+
_handler.save(im, fp, filename)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
#
|
| 177 |
+
# --------------------------------------------------------------------
|
| 178 |
+
# Registry stuff
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
|
| 182 |
+
Image.register_save(WmfStubImageFile.format, _save)
|
| 183 |
+
|
| 184 |
+
Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])
|
lib/python3.10/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()[:7] == 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")
|
lib/python3.10/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)
|
lib/python3.10/site-packages/PIL/_deprecate.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
from . import __version__
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def deprecate(
|
| 9 |
+
deprecated: str,
|
| 10 |
+
when: int | None,
|
| 11 |
+
replacement: str | None = None,
|
| 12 |
+
*,
|
| 13 |
+
action: str | None = None,
|
| 14 |
+
plural: bool = False,
|
| 15 |
+
) -> None:
|
| 16 |
+
"""
|
| 17 |
+
Deprecations helper.
|
| 18 |
+
|
| 19 |
+
:param deprecated: Name of thing to be deprecated.
|
| 20 |
+
:param when: Pillow major version to be removed in.
|
| 21 |
+
:param replacement: Name of replacement.
|
| 22 |
+
:param action: Instead of "replacement", give a custom call to action
|
| 23 |
+
e.g. "Upgrade to new thing".
|
| 24 |
+
:param plural: if the deprecated thing is plural, needing "are" instead of "is".
|
| 25 |
+
|
| 26 |
+
Usually of the form:
|
| 27 |
+
|
| 28 |
+
"[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).
|
| 29 |
+
Use [replacement] instead."
|
| 30 |
+
|
| 31 |
+
You can leave out the replacement sentence:
|
| 32 |
+
|
| 33 |
+
"[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)"
|
| 34 |
+
|
| 35 |
+
Or with another call to action:
|
| 36 |
+
|
| 37 |
+
"[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).
|
| 38 |
+
[action]."
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
is_ = "are" if plural else "is"
|
| 42 |
+
|
| 43 |
+
if when is None:
|
| 44 |
+
removed = "a future version"
|
| 45 |
+
elif when <= int(__version__.split(".")[0]):
|
| 46 |
+
msg = f"{deprecated} {is_} deprecated and should be removed."
|
| 47 |
+
raise RuntimeError(msg)
|
| 48 |
+
elif when == 12:
|
| 49 |
+
removed = "Pillow 12 (2025-10-15)"
|
| 50 |
+
else:
|
| 51 |
+
msg = f"Unknown removal version: {when}. Update {__name__}?"
|
| 52 |
+
raise ValueError(msg)
|
| 53 |
+
|
| 54 |
+
if replacement and action:
|
| 55 |
+
msg = "Use only one of 'replacement' and 'action'"
|
| 56 |
+
raise ValueError(msg)
|
| 57 |
+
|
| 58 |
+
if replacement:
|
| 59 |
+
action = f". Use {replacement} instead."
|
| 60 |
+
elif action:
|
| 61 |
+
action = f". {action.rstrip('.')}."
|
| 62 |
+
else:
|
| 63 |
+
action = ""
|
| 64 |
+
|
| 65 |
+
warnings.warn(
|
| 66 |
+
f"{deprecated} {is_} deprecated and will be removed in {removed}{action}",
|
| 67 |
+
DeprecationWarning,
|
| 68 |
+
stacklevel=3,
|
| 69 |
+
)
|
lib/python3.10/site-packages/PIL/_imagingmath.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
def __getattr__(name: str) -> Any: ...
|
lib/python3.10/site-packages/PIL/_imagingmorph.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (35.4 kB). View file
|
|
|
lib/python3.10/site-packages/PIL/_imagingmorph.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
def __getattr__(name: str) -> Any: ...
|
lib/python3.10/site-packages/PIL/_imagingtk.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (44.8 kB). View file
|
|
|
lib/python3.10/site-packages/PIL/_imagingtk.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
def __getattr__(name: str) -> Any: ...
|
lib/python3.10/site-packages/PIL/_webp.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (84.2 kB). View file
|
|
|
lib/python3.10/site-packages/PIL/_webp.pyi
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
def __getattr__(name: str) -> Any: ...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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import IO
|
| 8 |
+
|
| 9 |
+
import PIL
|
| 10 |
+
|
| 11 |
+
from . import Image
|
| 12 |
+
from ._deprecate import deprecate
|
| 13 |
+
|
| 14 |
+
modules = {
|
| 15 |
+
"pil": ("PIL._imaging", "PILLOW_VERSION"),
|
| 16 |
+
"tkinter": ("PIL._tkinter_finder", "tk_version"),
|
| 17 |
+
"freetype2": ("PIL._imagingft", "freetype2_version"),
|
| 18 |
+
"littlecms2": ("PIL._imagingcms", "littlecms_version"),
|
| 19 |
+
"webp": ("PIL._webp", "webpdecoder_version"),
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def check_module(feature: str) -> bool:
|
| 24 |
+
"""
|
| 25 |
+
Checks if a module is available.
|
| 26 |
+
|
| 27 |
+
:param feature: The module to check for.
|
| 28 |
+
:returns: ``True`` if available, ``False`` otherwise.
|
| 29 |
+
:raises ValueError: If the module is not defined in this version of Pillow.
|
| 30 |
+
"""
|
| 31 |
+
if feature not in modules:
|
| 32 |
+
msg = f"Unknown module {feature}"
|
| 33 |
+
raise ValueError(msg)
|
| 34 |
+
|
| 35 |
+
module, ver = modules[feature]
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
__import__(module)
|
| 39 |
+
return True
|
| 40 |
+
except ModuleNotFoundError:
|
| 41 |
+
return False
|
| 42 |
+
except ImportError as ex:
|
| 43 |
+
warnings.warn(str(ex))
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def version_module(feature: str) -> str | None:
|
| 48 |
+
"""
|
| 49 |
+
:param feature: The module to check for.
|
| 50 |
+
:returns:
|
| 51 |
+
The loaded version number as a string, or ``None`` if unknown or not available.
|
| 52 |
+
:raises ValueError: If the module is not defined in this version of Pillow.
|
| 53 |
+
"""
|
| 54 |
+
if not check_module(feature):
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
module, ver = modules[feature]
|
| 58 |
+
|
| 59 |
+
return getattr(__import__(module, fromlist=[ver]), ver)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_supported_modules() -> list[str]:
|
| 63 |
+
"""
|
| 64 |
+
:returns: A list of all supported modules.
|
| 65 |
+
"""
|
| 66 |
+
return [f for f in modules if check_module(f)]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
codecs = {
|
| 70 |
+
"jpg": ("jpeg", "jpeglib"),
|
| 71 |
+
"jpg_2000": ("jpeg2k", "jp2klib"),
|
| 72 |
+
"zlib": ("zip", "zlib"),
|
| 73 |
+
"libtiff": ("libtiff", "libtiff"),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_codec(feature: str) -> bool:
|
| 78 |
+
"""
|
| 79 |
+
Checks if a codec is available.
|
| 80 |
+
|
| 81 |
+
:param feature: The codec to check for.
|
| 82 |
+
:returns: ``True`` if available, ``False`` otherwise.
|
| 83 |
+
:raises ValueError: If the codec is not defined in this version of Pillow.
|
| 84 |
+
"""
|
| 85 |
+
if feature not in codecs:
|
| 86 |
+
msg = f"Unknown codec {feature}"
|
| 87 |
+
raise ValueError(msg)
|
| 88 |
+
|
| 89 |
+
codec, lib = codecs[feature]
|
| 90 |
+
|
| 91 |
+
return f"{codec}_encoder" in dir(Image.core)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def version_codec(feature: str) -> str | None:
|
| 95 |
+
"""
|
| 96 |
+
:param feature: The codec to check for.
|
| 97 |
+
:returns:
|
| 98 |
+
The version number as a string, or ``None`` if not available.
|
| 99 |
+
Checked at compile time for ``jpg``, run-time otherwise.
|
| 100 |
+
:raises ValueError: If the codec is not defined in this version of Pillow.
|
| 101 |
+
"""
|
| 102 |
+
if not check_codec(feature):
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
codec, lib = codecs[feature]
|
| 106 |
+
|
| 107 |
+
version = getattr(Image.core, f"{lib}_version")
|
| 108 |
+
|
| 109 |
+
if feature == "libtiff":
|
| 110 |
+
return version.split("\n")[0].split("Version ")[1]
|
| 111 |
+
|
| 112 |
+
return version
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_supported_codecs() -> list[str]:
|
| 116 |
+
"""
|
| 117 |
+
:returns: A list of all supported codecs.
|
| 118 |
+
"""
|
| 119 |
+
return [f for f in codecs if check_codec(f)]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
features: dict[str, tuple[str, str | bool, str | None]] = {
|
| 123 |
+
"webp_anim": ("PIL._webp", True, None),
|
| 124 |
+
"webp_mux": ("PIL._webp", True, None),
|
| 125 |
+
"transp_webp": ("PIL._webp", True, None),
|
| 126 |
+
"raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"),
|
| 127 |
+
"fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"),
|
| 128 |
+
"harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"),
|
| 129 |
+
"libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"),
|
| 130 |
+
"zlib_ng": ("PIL._imaging", "HAVE_ZLIBNG", "zlib_ng_version"),
|
| 131 |
+
"libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"),
|
| 132 |
+
"xcb": ("PIL._imaging", "HAVE_XCB", None),
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def check_feature(feature: str) -> bool | None:
|
| 137 |
+
"""
|
| 138 |
+
Checks if a feature is available.
|
| 139 |
+
|
| 140 |
+
:param feature: The feature to check for.
|
| 141 |
+
:returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
|
| 142 |
+
:raises ValueError: If the feature is not defined in this version of Pillow.
|
| 143 |
+
"""
|
| 144 |
+
if feature not in features:
|
| 145 |
+
msg = f"Unknown feature {feature}"
|
| 146 |
+
raise ValueError(msg)
|
| 147 |
+
|
| 148 |
+
module, flag, ver = features[feature]
|
| 149 |
+
|
| 150 |
+
if isinstance(flag, bool):
|
| 151 |
+
deprecate(f'check_feature("{feature}")', 12)
|
| 152 |
+
try:
|
| 153 |
+
imported_module = __import__(module, fromlist=["PIL"])
|
| 154 |
+
if isinstance(flag, bool):
|
| 155 |
+
return flag
|
| 156 |
+
return getattr(imported_module, flag)
|
| 157 |
+
except ModuleNotFoundError:
|
| 158 |
+
return None
|
| 159 |
+
except ImportError as ex:
|
| 160 |
+
warnings.warn(str(ex))
|
| 161 |
+
return None
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def version_feature(feature: str) -> str | None:
|
| 165 |
+
"""
|
| 166 |
+
:param feature: The feature to check for.
|
| 167 |
+
:returns: The version number as a string, or ``None`` if not available.
|
| 168 |
+
:raises ValueError: If the feature is not defined in this version of Pillow.
|
| 169 |
+
"""
|
| 170 |
+
if not check_feature(feature):
|
| 171 |
+
return None
|
| 172 |
+
|
| 173 |
+
module, flag, ver = features[feature]
|
| 174 |
+
|
| 175 |
+
if ver is None:
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
return getattr(__import__(module, fromlist=[ver]), ver)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_supported_features() -> list[str]:
|
| 182 |
+
"""
|
| 183 |
+
:returns: A list of all supported features.
|
| 184 |
+
"""
|
| 185 |
+
supported_features = []
|
| 186 |
+
for f, (module, flag, _) in features.items():
|
| 187 |
+
if flag is True:
|
| 188 |
+
for feature, (feature_module, _) in modules.items():
|
| 189 |
+
if feature_module == module:
|
| 190 |
+
if check_module(feature):
|
| 191 |
+
supported_features.append(f)
|
| 192 |
+
break
|
| 193 |
+
elif check_feature(f):
|
| 194 |
+
supported_features.append(f)
|
| 195 |
+
return supported_features
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def check(feature: str) -> bool | None:
|
| 199 |
+
"""
|
| 200 |
+
:param feature: A module, codec, or feature name.
|
| 201 |
+
:returns:
|
| 202 |
+
``True`` if the module, codec, or feature is available,
|
| 203 |
+
``False`` or ``None`` otherwise.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
if feature in modules:
|
| 207 |
+
return check_module(feature)
|
| 208 |
+
if feature in codecs:
|
| 209 |
+
return check_codec(feature)
|
| 210 |
+
if feature in features:
|
| 211 |
+
return check_feature(feature)
|
| 212 |
+
warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2)
|
| 213 |
+
return False
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def version(feature: str) -> str | None:
|
| 217 |
+
"""
|
| 218 |
+
:param feature:
|
| 219 |
+
The module, codec, or feature to check for.
|
| 220 |
+
:returns:
|
| 221 |
+
The version number as a string, or ``None`` if unknown or not available.
|
| 222 |
+
"""
|
| 223 |
+
if feature in modules:
|
| 224 |
+
return version_module(feature)
|
| 225 |
+
if feature in codecs:
|
| 226 |
+
return version_codec(feature)
|
| 227 |
+
if feature in features:
|
| 228 |
+
return version_feature(feature)
|
| 229 |
+
return None
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def get_supported() -> list[str]:
|
| 233 |
+
"""
|
| 234 |
+
:returns: A list of all supported modules, features, and codecs.
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
ret = get_supported_modules()
|
| 238 |
+
ret.extend(get_supported_features())
|
| 239 |
+
ret.extend(get_supported_codecs())
|
| 240 |
+
return ret
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None:
|
| 244 |
+
"""
|
| 245 |
+
Prints information about this installation of Pillow.
|
| 246 |
+
This function can be called with ``python3 -m PIL``.
|
| 247 |
+
It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report``
|
| 248 |
+
to have "supported_formats" set to ``False``, omitting the list of all supported
|
| 249 |
+
image file formats.
|
| 250 |
+
|
| 251 |
+
:param out:
|
| 252 |
+
The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
|
| 253 |
+
:param supported_formats:
|
| 254 |
+
If ``True``, a list of all supported image file formats will be printed.
|
| 255 |
+
"""
|
| 256 |
+
|
| 257 |
+
if out is None:
|
| 258 |
+
out = sys.stdout
|
| 259 |
+
|
| 260 |
+
Image.init()
|
| 261 |
+
|
| 262 |
+
print("-" * 68, file=out)
|
| 263 |
+
print(f"Pillow {PIL.__version__}", file=out)
|
| 264 |
+
py_version_lines = sys.version.splitlines()
|
| 265 |
+
print(f"Python {py_version_lines[0].strip()}", file=out)
|
| 266 |
+
for py_version in py_version_lines[1:]:
|
| 267 |
+
print(f" {py_version.strip()}", file=out)
|
| 268 |
+
print("-" * 68, file=out)
|
| 269 |
+
print(f"Python executable is {sys.executable or 'unknown'}", file=out)
|
| 270 |
+
if sys.prefix != sys.base_prefix:
|
| 271 |
+
print(f"Environment Python files loaded from {sys.prefix}", file=out)
|
| 272 |
+
print(f"System Python files loaded from {sys.base_prefix}", file=out)
|
| 273 |
+
print("-" * 68, file=out)
|
| 274 |
+
print(
|
| 275 |
+
f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}",
|
| 276 |
+
file=out,
|
| 277 |
+
)
|
| 278 |
+
print(
|
| 279 |
+
f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}",
|
| 280 |
+
file=out,
|
| 281 |
+
)
|
| 282 |
+
print("-" * 68, file=out)
|
| 283 |
+
|
| 284 |
+
for name, feature in [
|
| 285 |
+
("pil", "PIL CORE"),
|
| 286 |
+
("tkinter", "TKINTER"),
|
| 287 |
+
("freetype2", "FREETYPE2"),
|
| 288 |
+
("littlecms2", "LITTLECMS2"),
|
| 289 |
+
("webp", "WEBP"),
|
| 290 |
+
("jpg", "JPEG"),
|
| 291 |
+
("jpg_2000", "OPENJPEG (JPEG2000)"),
|
| 292 |
+
("zlib", "ZLIB (PNG/ZIP)"),
|
| 293 |
+
("libtiff", "LIBTIFF"),
|
| 294 |
+
("raqm", "RAQM (Bidirectional Text)"),
|
| 295 |
+
("libimagequant", "LIBIMAGEQUANT (Quantization method)"),
|
| 296 |
+
("xcb", "XCB (X protocol)"),
|
| 297 |
+
]:
|
| 298 |
+
if check(name):
|
| 299 |
+
v: str | None = None
|
| 300 |
+
if name == "jpg":
|
| 301 |
+
libjpeg_turbo_version = version_feature("libjpeg_turbo")
|
| 302 |
+
if libjpeg_turbo_version is not None:
|
| 303 |
+
v = "libjpeg-turbo " + libjpeg_turbo_version
|
| 304 |
+
if v is None:
|
| 305 |
+
v = version(name)
|
| 306 |
+
if v is not None:
|
| 307 |
+
version_static = name in ("pil", "jpg")
|
| 308 |
+
if name == "littlecms2":
|
| 309 |
+
# this check is also in src/_imagingcms.c:setup_module()
|
| 310 |
+
version_static = tuple(int(x) for x in v.split(".")) < (2, 7)
|
| 311 |
+
t = "compiled for" if version_static else "loaded"
|
| 312 |
+
if name == "zlib":
|
| 313 |
+
zlib_ng_version = version_feature("zlib_ng")
|
| 314 |
+
if zlib_ng_version is not None:
|
| 315 |
+
v += ", compiled for zlib-ng " + zlib_ng_version
|
| 316 |
+
elif name == "raqm":
|
| 317 |
+
for f in ("fribidi", "harfbuzz"):
|
| 318 |
+
v2 = version_feature(f)
|
| 319 |
+
if v2 is not None:
|
| 320 |
+
v += f", {f} {v2}"
|
| 321 |
+
print("---", feature, "support ok,", t, v, file=out)
|
| 322 |
+
else:
|
| 323 |
+
print("---", feature, "support ok", file=out)
|
| 324 |
+
else:
|
| 325 |
+
print("***", feature, "support not installed", file=out)
|
| 326 |
+
print("-" * 68, file=out)
|
| 327 |
+
|
| 328 |
+
if supported_formats:
|
| 329 |
+
extensions = collections.defaultdict(list)
|
| 330 |
+
for ext, i in Image.EXTENSION.items():
|
| 331 |
+
extensions[i].append(ext)
|
| 332 |
+
|
| 333 |
+
for i in sorted(Image.ID):
|
| 334 |
+
line = f"{i}"
|
| 335 |
+
if i in Image.MIME:
|
| 336 |
+
line = f"{line} {Image.MIME[i]}"
|
| 337 |
+
print(line, file=out)
|
| 338 |
+
|
| 339 |
+
if i in extensions:
|
| 340 |
+
print(
|
| 341 |
+
"Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
features = []
|
| 345 |
+
if i in Image.OPEN:
|
| 346 |
+
features.append("open")
|
| 347 |
+
if i in Image.SAVE:
|
| 348 |
+
features.append("save")
|
| 349 |
+
if i in Image.SAVE_ALL:
|
| 350 |
+
features.append("save_all")
|
| 351 |
+
if i in Image.DECODERS:
|
| 352 |
+
features.append("decode")
|
| 353 |
+
if i in Image.ENCODERS:
|
| 354 |
+
features.append("encode")
|
| 355 |
+
|
| 356 |
+
print("Features: {}".format(", ".join(features)), file=out)
|
| 357 |
+
print("-" * 68, file=out)
|
lib/python3.10/site-packages/PIL/report.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .features import pilinfo
|
| 4 |
+
|
| 5 |
+
pilinfo(supported_formats=False)
|
lib/python3.10/site-packages/av/codec/hwaccel.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4e4012a6f31f3230284296befd4fe9abeae06cc81e45af4265a9db9daa64e89
|
| 3 |
+
size 737081
|
lib/python3.10/site-packages/av/filter/context.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3e5cb5cc0f800fcc774c1462f4758f99d332dc91eaf0cb571208ea5a011eebd6
|
| 3 |
+
size 720641
|
lib/python3.10/site-packages/av/filter/link.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc7068cbb9f5b4e2f5b4e8f2ad13ca36451077a65527a2976ffddfc947322827
|
| 3 |
+
size 375889
|
lib/python3.10/site-packages/av/filter/loudnorm.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6b3ad9dd72300bf2b0202b68208d43f573113fcbffad8cc89266dfd936c67b66
|
| 3 |
+
size 417649
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/AUTHORS
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Creator: Sebastian Thiel
|
| 2 |
+
|
| 3 |
+
Contributors:
|
| 4 |
+
- Ram Rachum (@cool-RR)
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (C) 2010, 2011 Sebastian Thiel and contributors
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without
|
| 5 |
+
modification, are permitted provided that the following conditions
|
| 6 |
+
are met:
|
| 7 |
+
|
| 8 |
+
* Redistributions of source code must retain the above copyright
|
| 9 |
+
notice, this list of conditions and the following disclaimer.
|
| 10 |
+
|
| 11 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 12 |
+
notice, this list of conditions and the following disclaimer in the
|
| 13 |
+
documentation and/or other materials provided with the distribution.
|
| 14 |
+
|
| 15 |
+
* Neither the name of the GitDB project nor the names of
|
| 16 |
+
its contributors may be used to endorse or promote products derived
|
| 17 |
+
from this software without specific prior written permission.
|
| 18 |
+
|
| 19 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 20 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 21 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 22 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 23 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 24 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 25 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 26 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 27 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 28 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 29 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Additional Licenses
|
| 33 |
+
-------------------
|
| 34 |
+
The files at
|
| 35 |
+
gitdb/test/fixtures/packs/pack-11fdfa9e156ab73caae3b6da867192221f2089c2.idx
|
| 36 |
+
and
|
| 37 |
+
gitdb/test/fixtures/packs/pack-11fdfa9e156ab73caae3b6da867192221f2089c2.pack
|
| 38 |
+
are licensed under GNU GPL as part of the git source repository,
|
| 39 |
+
see http://en.wikipedia.org/wiki/Git_%28software%29 for more information.
|
| 40 |
+
|
| 41 |
+
They are not required for the actual operation, which is why they are not found
|
| 42 |
+
in the distribution package.
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/METADATA
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: gitdb
|
| 3 |
+
Version: 4.0.12
|
| 4 |
+
Summary: Git Object Database
|
| 5 |
+
Home-page: https://github.com/gitpython-developers/gitdb
|
| 6 |
+
Author: Sebastian Thiel
|
| 7 |
+
Author-email: byronimo@gmail.com
|
| 8 |
+
License: BSD License
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Environment :: Console
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 13 |
+
Classifier: Operating System :: OS Independent
|
| 14 |
+
Classifier: Operating System :: POSIX
|
| 15 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 16 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 17 |
+
Classifier: Programming Language :: Python
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 26 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 27 |
+
Requires-Python: >=3.7
|
| 28 |
+
License-File: LICENSE
|
| 29 |
+
License-File: AUTHORS
|
| 30 |
+
Requires-Dist: smmap<6,>=3.0.1
|
| 31 |
+
|
| 32 |
+
GitDB is a pure-Python git object database
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/RECORD
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gitdb-4.0.12.dist-info/AUTHORS,sha256=aUmmuuKGJrGDzN5i-dDIbj00R1IOPcFTZDWznhEwZuM,66
|
| 2 |
+
gitdb-4.0.12.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 3 |
+
gitdb-4.0.12.dist-info/LICENSE,sha256=79KfWWoI6IV-aOdpSlC82nKDl5LafD8EG8v_XxgAkjk,1984
|
| 4 |
+
gitdb-4.0.12.dist-info/METADATA,sha256=lnDS3IZgOda3yR9SzYHH8iTNdGf3aFx8KebEaR0b89k,1230
|
| 5 |
+
gitdb-4.0.12.dist-info/RECORD,,
|
| 6 |
+
gitdb-4.0.12.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 7 |
+
gitdb-4.0.12.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
| 8 |
+
gitdb-4.0.12.dist-info/top_level.txt,sha256=ss6atT8cG4mQuAYXO6PokJ0r4Mm5cBiDbKsu2e3YHfs,6
|
| 9 |
+
gitdb/__init__.py,sha256=Zfj1Uasvn9KgccHILrsHFZGTGFm4mvmEmw0trh6HOrM,551
|
| 10 |
+
gitdb/base.py,sha256=krg61c_FKEvn4KAcX6pjH-hlpFfRCcM7mrki4Hnmxew,8023
|
| 11 |
+
gitdb/const.py,sha256=WWmEYKNDdm3J9fxYTFT_B6-QLDSMBClbz0LSBa1D1S8,90
|
| 12 |
+
gitdb/db/__init__.py,sha256=aQTZnxpfk6c76X1ubZzO9pBq4STnL6hCoGxZzXurEZ4,371
|
| 13 |
+
gitdb/db/base.py,sha256=_qpZ1VzwpoTcU3_-IIXmwIW0p63HXrtJ5jWNgjrLjRY,9061
|
| 14 |
+
gitdb/db/git.py,sha256=b5O01eZsnzldruzEENvqiw8Q7Daz2iETrlAqH0aggdE,2666
|
| 15 |
+
gitdb/db/loose.py,sha256=z7m0Cju-knikJi5UX6KWdWAJ9OOCeOE4gfYBso4XAQA,8734
|
| 16 |
+
gitdb/db/mem.py,sha256=VDscunT4EtRo2GBE52lup1ki3si8enImUSKmSVq8kwc,3343
|
| 17 |
+
gitdb/db/pack.py,sha256=iZPDF6rQ-kCrgbdsZRA83CL-zWsoQaZxo5rcTarjAoQ,7285
|
| 18 |
+
gitdb/db/ref.py,sha256=rGOzF3cAOBW9i0Owz_Iw6c4K5BgbYFwk5btMaXGvCoc,2591
|
| 19 |
+
gitdb/exc.py,sha256=B0N6I2rctCwd0Upoq2laTigbVZNOZ38nfobRcKDBtV4,1496
|
| 20 |
+
gitdb/fun.py,sha256=jw3paQMgxexUn2NENFavLXfABfNvDBRfRCvv2VHkvms,23243
|
| 21 |
+
gitdb/pack.py,sha256=buboXaTzXKEedNX5j1zIUIPhnLmHkDRl7Rg9ftclt14,39228
|
| 22 |
+
gitdb/stream.py,sha256=0-BWcggWWZniMXGGaAe3MR6iH9DBt5ir9YtgE2_rKKw,27541
|
| 23 |
+
gitdb/test/__init__.py,sha256=4cJQwIMepzCxK0hdxDegJGxNVK4dungjbPzCUJc1ZIU,204
|
| 24 |
+
gitdb/test/lib.py,sha256=iXBcJ3RDAN0uj9NbyEzt90TuCsDFt3SjHA61Ly6Xyxs,5489
|
| 25 |
+
gitdb/test/test_base.py,sha256=6zjmON19J7LRDidlMSz2iQArONdkK6_v-DzhAQJzChg,2836
|
| 26 |
+
gitdb/test/test_example.py,sha256=In7WgwvrGCbxPcuLCmkVIs4kdhCJ8rtcEvp115fHeU4,1350
|
| 27 |
+
gitdb/test/test_pack.py,sha256=bbkupZPBFlpjBcPZTZ0OmRrTA9I3-fVdfwLtNa14_3s,9228
|
| 28 |
+
gitdb/test/test_stream.py,sha256=RwSB49q6JHM7EFW413CZQeGRfkK92aQ0IVfTocIa3bo,5727
|
| 29 |
+
gitdb/test/test_util.py,sha256=WQKQBP2uPF4wwNJFlUd9-YE2Q3CmlgpoY4MRk5G0r54,3243
|
| 30 |
+
gitdb/typ.py,sha256=dZlbzfy5RFNHiZHEOwVy-6T-aZ3xLv0mGaJVyxKBd0M,373
|
| 31 |
+
gitdb/util.py,sha256=F3bE24b2QDihz4tqc3Km7wbC6N65EjwFoao-yzrRJSY,12302
|
| 32 |
+
gitdb/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 33 |
+
gitdb/utils/encoding.py,sha256=ceZZFb86LGJ71cwW6qkq_BFquAlNE7jaafNbwxYRSXk,372
|
lib/python3.10/site-packages/gitdb-4.0.12.dist-info/REQUESTED
ADDED
|
File without changes
|