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 +2 -0
- valley/lib/python3.10/site-packages/PIL/BdfFontFile.py +133 -0
- valley/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py +76 -0
- valley/lib/python3.10/site-packages/PIL/CurImagePlugin.py +75 -0
- valley/lib/python3.10/site-packages/PIL/DcxImagePlugin.py +80 -0
- valley/lib/python3.10/site-packages/PIL/DdsImagePlugin.py +575 -0
- valley/lib/python3.10/site-packages/PIL/FliImagePlugin.py +174 -0
- valley/lib/python3.10/site-packages/PIL/FontFile.py +134 -0
- valley/lib/python3.10/site-packages/PIL/FpxImagePlugin.py +255 -0
- valley/lib/python3.10/site-packages/PIL/GimpGradientFile.py +149 -0
- valley/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py +76 -0
- valley/lib/python3.10/site-packages/PIL/Hdf5StubImagePlugin.py +76 -0
- valley/lib/python3.10/site-packages/PIL/IcnsImagePlugin.py +399 -0
- valley/lib/python3.10/site-packages/PIL/IcoImagePlugin.py +360 -0
- valley/lib/python3.10/site-packages/PIL/ImImagePlugin.py +374 -0
- valley/lib/python3.10/site-packages/PIL/ImageCms.py +1127 -0
- valley/lib/python3.10/site-packages/PIL/ImageDraw2.py +206 -0
- valley/lib/python3.10/site-packages/PIL/ImageEnhance.py +107 -0
- valley/lib/python3.10/site-packages/PIL/ImageFile.py +810 -0
- valley/lib/python3.10/site-packages/PIL/ImageFont.py +1290 -0
- valley/lib/python3.10/site-packages/PIL/ImageGrab.py +194 -0
- valley/lib/python3.10/site-packages/PIL/ImagePalette.py +284 -0
- valley/lib/python3.10/site-packages/PIL/ImageQt.py +205 -0
- valley/lib/python3.10/site-packages/PIL/ImageSequence.py +86 -0
- valley/lib/python3.10/site-packages/PIL/ImageShow.py +363 -0
- valley/lib/python3.10/site-packages/PIL/ImageStat.py +160 -0
- valley/lib/python3.10/site-packages/PIL/ImageTk.py +284 -0
- valley/lib/python3.10/site-packages/PIL/ImageTransform.py +135 -0
- valley/lib/python3.10/site-packages/PIL/ImageWin.py +238 -0
- valley/lib/python3.10/site-packages/PIL/ImtImagePlugin.py +103 -0
- valley/lib/python3.10/site-packages/PIL/IptcImagePlugin.py +235 -0
- valley/lib/python3.10/site-packages/PIL/Jpeg2KImagePlugin.py +408 -0
- valley/lib/python3.10/site-packages/PIL/JpegImagePlugin.py +861 -0
- valley/lib/python3.10/site-packages/PIL/MicImagePlugin.py +107 -0
- valley/lib/python3.10/site-packages/PIL/MpegImagePlugin.py +88 -0
- valley/lib/python3.10/site-packages/PIL/MpoImagePlugin.py +180 -0
- valley/lib/python3.10/site-packages/PIL/MspImagePlugin.py +200 -0
- valley/lib/python3.10/site-packages/PIL/PSDraw.py +237 -0
- valley/lib/python3.10/site-packages/PIL/PaletteFile.py +54 -0
- valley/lib/python3.10/site-packages/PIL/PalmImagePlugin.py +229 -0
- valley/lib/python3.10/site-packages/PIL/PcdImagePlugin.py +66 -0
- valley/lib/python3.10/site-packages/PIL/PcfFontFile.py +254 -0
- valley/lib/python3.10/site-packages/PIL/PcxImagePlugin.py +227 -0
- valley/lib/python3.10/site-packages/PIL/PdfImagePlugin.py +304 -0
- valley/lib/python3.10/site-packages/PIL/PngImagePlugin.py +1489 -0
- valley/lib/python3.10/site-packages/PIL/PsdImagePlugin.py +326 -0
- valley/lib/python3.10/site-packages/PIL/PyAccess.py +381 -0
- valley/lib/python3.10/site-packages/PIL/SgiImagePlugin.py +238 -0
- valley/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py +325 -0
- valley/lib/python3.10/site-packages/PIL/SunImagePlugin.py +141 -0
.gitattributes
CHANGED
|
@@ -611,3 +611,5 @@ valley/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-c128ec02.so fil
|
|
| 611 |
valley/lib/python3.10/site-packages/skimage/restoration/_inpaint.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 612 |
valley/lib/python3.10/site-packages/skimage/restoration/_nl_means_denoising.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 613 |
valley/lib/python3.10/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 611 |
valley/lib/python3.10/site-packages/skimage/restoration/_inpaint.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 612 |
valley/lib/python3.10/site-packages/skimage/restoration/_nl_means_denoising.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 613 |
valley/lib/python3.10/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
|
| 614 |
+
valley/lib/python3.10/site-packages/PIL/_imaging.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 615 |
+
valley/lib/python3.10/site-packages/PIL/_imagingft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
valley/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
|
valley/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")
|
valley/lib/python3.10/site-packages/PIL/CurImagePlugin.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Windows Cursor support for PIL
|
| 6 |
+
#
|
| 7 |
+
# notes:
|
| 8 |
+
# uses BmpImagePlugin.py to read the bitmap data.
|
| 9 |
+
#
|
| 10 |
+
# history:
|
| 11 |
+
# 96-05-27 fl Created
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from . import BmpImagePlugin, Image
|
| 21 |
+
from ._binary import i16le as i16
|
| 22 |
+
from ._binary import i32le as i32
|
| 23 |
+
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _accept(prefix: bytes) -> bool:
|
| 29 |
+
return prefix[:4] == b"\0\0\2\0"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
##
|
| 33 |
+
# Image plugin for Windows Cursor files.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CurImageFile(BmpImagePlugin.BmpImageFile):
|
| 37 |
+
format = "CUR"
|
| 38 |
+
format_description = "Windows Cursor"
|
| 39 |
+
|
| 40 |
+
def _open(self) -> None:
|
| 41 |
+
offset = self.fp.tell()
|
| 42 |
+
|
| 43 |
+
# check magic
|
| 44 |
+
s = self.fp.read(6)
|
| 45 |
+
if not _accept(s):
|
| 46 |
+
msg = "not a CUR file"
|
| 47 |
+
raise SyntaxError(msg)
|
| 48 |
+
|
| 49 |
+
# pick the largest cursor in the file
|
| 50 |
+
m = b""
|
| 51 |
+
for i in range(i16(s, 4)):
|
| 52 |
+
s = self.fp.read(16)
|
| 53 |
+
if not m:
|
| 54 |
+
m = s
|
| 55 |
+
elif s[0] > m[0] and s[1] > m[1]:
|
| 56 |
+
m = s
|
| 57 |
+
if not m:
|
| 58 |
+
msg = "No cursors were found"
|
| 59 |
+
raise TypeError(msg)
|
| 60 |
+
|
| 61 |
+
# load as bitmap
|
| 62 |
+
self._bitmap(i32(m, 12) + offset)
|
| 63 |
+
|
| 64 |
+
# patch up the bitmap height
|
| 65 |
+
self._size = self.size[0], self.size[1] // 2
|
| 66 |
+
d, e, o, a = self.tile[0]
|
| 67 |
+
self.tile[0] = d, (0, 0) + self.size, o, a
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
#
|
| 71 |
+
# --------------------------------------------------------------------
|
| 72 |
+
|
| 73 |
+
Image.register_open(CurImageFile.format, CurImageFile, _accept)
|
| 74 |
+
|
| 75 |
+
Image.register_extension(CurImageFile.format, ".cur")
|
valley/lib/python3.10/site-packages/PIL/DcxImagePlugin.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# DCX file handling
|
| 6 |
+
#
|
| 7 |
+
# DCX is a container file format defined by Intel, commonly used
|
| 8 |
+
# for fax applications. Each DCX file consists of a directory
|
| 9 |
+
# (a list of file offsets) followed by a set of (usually 1-bit)
|
| 10 |
+
# PCX files.
|
| 11 |
+
#
|
| 12 |
+
# History:
|
| 13 |
+
# 1995-09-09 fl Created
|
| 14 |
+
# 1996-03-20 fl Properly derived from PcxImageFile.
|
| 15 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
| 16 |
+
# 2002-07-30 fl Fixed file handling
|
| 17 |
+
#
|
| 18 |
+
# Copyright (c) 1997-98 by Secret Labs AB.
|
| 19 |
+
# Copyright (c) 1995-96 by Fredrik Lundh.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
from . import Image
|
| 26 |
+
from ._binary import i32le as i32
|
| 27 |
+
from .PcxImagePlugin import PcxImageFile
|
| 28 |
+
|
| 29 |
+
MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _accept(prefix: bytes) -> bool:
|
| 33 |
+
return len(prefix) >= 4 and i32(prefix) == MAGIC
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
##
|
| 37 |
+
# Image plugin for the Intel DCX format.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DcxImageFile(PcxImageFile):
|
| 41 |
+
format = "DCX"
|
| 42 |
+
format_description = "Intel DCX"
|
| 43 |
+
_close_exclusive_fp_after_loading = False
|
| 44 |
+
|
| 45 |
+
def _open(self) -> None:
|
| 46 |
+
# Header
|
| 47 |
+
s = self.fp.read(4)
|
| 48 |
+
if not _accept(s):
|
| 49 |
+
msg = "not a DCX file"
|
| 50 |
+
raise SyntaxError(msg)
|
| 51 |
+
|
| 52 |
+
# Component directory
|
| 53 |
+
self._offset = []
|
| 54 |
+
for i in range(1024):
|
| 55 |
+
offset = i32(self.fp.read(4))
|
| 56 |
+
if not offset:
|
| 57 |
+
break
|
| 58 |
+
self._offset.append(offset)
|
| 59 |
+
|
| 60 |
+
self._fp = self.fp
|
| 61 |
+
self.frame = -1
|
| 62 |
+
self.n_frames = len(self._offset)
|
| 63 |
+
self.is_animated = self.n_frames > 1
|
| 64 |
+
self.seek(0)
|
| 65 |
+
|
| 66 |
+
def seek(self, frame: int) -> None:
|
| 67 |
+
if not self._seek_check(frame):
|
| 68 |
+
return
|
| 69 |
+
self.frame = frame
|
| 70 |
+
self.fp = self._fp
|
| 71 |
+
self.fp.seek(self._offset[frame])
|
| 72 |
+
PcxImageFile._open(self)
|
| 73 |
+
|
| 74 |
+
def tell(self) -> int:
|
| 75 |
+
return self.frame
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
|
| 79 |
+
|
| 80 |
+
Image.register_extension(DcxImageFile.format, ".dcx")
|
valley/lib/python3.10/site-packages/PIL/DdsImagePlugin.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 = [("dds_rgb", extents, 0, (bitcount, masks))]
|
| 371 |
+
return
|
| 372 |
+
elif pfflags & DDPF.LUMINANCE:
|
| 373 |
+
if bitcount == 8:
|
| 374 |
+
self._mode = "L"
|
| 375 |
+
elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
|
| 376 |
+
self._mode = "LA"
|
| 377 |
+
else:
|
| 378 |
+
msg = f"Unsupported bitcount {bitcount} for {pfflags}"
|
| 379 |
+
raise OSError(msg)
|
| 380 |
+
elif pfflags & DDPF.PALETTEINDEXED8:
|
| 381 |
+
self._mode = "P"
|
| 382 |
+
self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
|
| 383 |
+
self.palette.mode = "RGBA"
|
| 384 |
+
elif pfflags & DDPF.FOURCC:
|
| 385 |
+
offset = header_size + 4
|
| 386 |
+
if fourcc == D3DFMT.DXT1:
|
| 387 |
+
self._mode = "RGBA"
|
| 388 |
+
self.pixel_format = "DXT1"
|
| 389 |
+
n = 1
|
| 390 |
+
elif fourcc == D3DFMT.DXT3:
|
| 391 |
+
self._mode = "RGBA"
|
| 392 |
+
self.pixel_format = "DXT3"
|
| 393 |
+
n = 2
|
| 394 |
+
elif fourcc == D3DFMT.DXT5:
|
| 395 |
+
self._mode = "RGBA"
|
| 396 |
+
self.pixel_format = "DXT5"
|
| 397 |
+
n = 3
|
| 398 |
+
elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
|
| 399 |
+
self._mode = "L"
|
| 400 |
+
self.pixel_format = "BC4"
|
| 401 |
+
n = 4
|
| 402 |
+
elif fourcc == D3DFMT.BC5S:
|
| 403 |
+
self._mode = "RGB"
|
| 404 |
+
self.pixel_format = "BC5S"
|
| 405 |
+
n = 5
|
| 406 |
+
elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
|
| 407 |
+
self._mode = "RGB"
|
| 408 |
+
self.pixel_format = "BC5"
|
| 409 |
+
n = 5
|
| 410 |
+
elif fourcc == D3DFMT.DX10:
|
| 411 |
+
offset += 20
|
| 412 |
+
# ignoring flags which pertain to volume textures and cubemaps
|
| 413 |
+
(dxgi_format,) = struct.unpack("<I", self.fp.read(4))
|
| 414 |
+
self.fp.read(16)
|
| 415 |
+
if dxgi_format in (
|
| 416 |
+
DXGI_FORMAT.BC1_UNORM,
|
| 417 |
+
DXGI_FORMAT.BC1_TYPELESS,
|
| 418 |
+
):
|
| 419 |
+
self._mode = "RGBA"
|
| 420 |
+
self.pixel_format = "BC1"
|
| 421 |
+
n = 1
|
| 422 |
+
elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
|
| 423 |
+
self._mode = "L"
|
| 424 |
+
self.pixel_format = "BC4"
|
| 425 |
+
n = 4
|
| 426 |
+
elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
|
| 427 |
+
self._mode = "RGB"
|
| 428 |
+
self.pixel_format = "BC5"
|
| 429 |
+
n = 5
|
| 430 |
+
elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
|
| 431 |
+
self._mode = "RGB"
|
| 432 |
+
self.pixel_format = "BC5S"
|
| 433 |
+
n = 5
|
| 434 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
|
| 435 |
+
self._mode = "RGB"
|
| 436 |
+
self.pixel_format = "BC6H"
|
| 437 |
+
n = 6
|
| 438 |
+
elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
|
| 439 |
+
self._mode = "RGB"
|
| 440 |
+
self.pixel_format = "BC6HS"
|
| 441 |
+
n = 6
|
| 442 |
+
elif dxgi_format in (
|
| 443 |
+
DXGI_FORMAT.BC7_TYPELESS,
|
| 444 |
+
DXGI_FORMAT.BC7_UNORM,
|
| 445 |
+
DXGI_FORMAT.BC7_UNORM_SRGB,
|
| 446 |
+
):
|
| 447 |
+
self._mode = "RGBA"
|
| 448 |
+
self.pixel_format = "BC7"
|
| 449 |
+
n = 7
|
| 450 |
+
if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
|
| 451 |
+
self.info["gamma"] = 1 / 2.2
|
| 452 |
+
elif dxgi_format in (
|
| 453 |
+
DXGI_FORMAT.R8G8B8A8_TYPELESS,
|
| 454 |
+
DXGI_FORMAT.R8G8B8A8_UNORM,
|
| 455 |
+
DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
|
| 456 |
+
):
|
| 457 |
+
self._mode = "RGBA"
|
| 458 |
+
if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
|
| 459 |
+
self.info["gamma"] = 1 / 2.2
|
| 460 |
+
else:
|
| 461 |
+
msg = f"Unimplemented DXGI format {dxgi_format}"
|
| 462 |
+
raise NotImplementedError(msg)
|
| 463 |
+
else:
|
| 464 |
+
msg = f"Unimplemented pixel format {repr(fourcc)}"
|
| 465 |
+
raise NotImplementedError(msg)
|
| 466 |
+
else:
|
| 467 |
+
msg = f"Unknown pixel format flags {pfflags}"
|
| 468 |
+
raise NotImplementedError(msg)
|
| 469 |
+
|
| 470 |
+
if n:
|
| 471 |
+
self.tile = [
|
| 472 |
+
ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
|
| 473 |
+
]
|
| 474 |
+
else:
|
| 475 |
+
self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
|
| 476 |
+
|
| 477 |
+
def load_seek(self, pos: int) -> None:
|
| 478 |
+
pass
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class DdsRgbDecoder(ImageFile.PyDecoder):
|
| 482 |
+
_pulls_fd = True
|
| 483 |
+
|
| 484 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 485 |
+
assert self.fd is not None
|
| 486 |
+
bitcount, masks = self.args
|
| 487 |
+
|
| 488 |
+
# Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
|
| 489 |
+
# Calculate how many zeros each mask is padded with
|
| 490 |
+
mask_offsets = []
|
| 491 |
+
# And the maximum value of each channel without the padding
|
| 492 |
+
mask_totals = []
|
| 493 |
+
for mask in masks:
|
| 494 |
+
offset = 0
|
| 495 |
+
if mask != 0:
|
| 496 |
+
while mask >> (offset + 1) << (offset + 1) == mask:
|
| 497 |
+
offset += 1
|
| 498 |
+
mask_offsets.append(offset)
|
| 499 |
+
mask_totals.append(mask >> offset)
|
| 500 |
+
|
| 501 |
+
data = bytearray()
|
| 502 |
+
bytecount = bitcount // 8
|
| 503 |
+
dest_length = self.state.xsize * self.state.ysize * len(masks)
|
| 504 |
+
while len(data) < dest_length:
|
| 505 |
+
value = int.from_bytes(self.fd.read(bytecount), "little")
|
| 506 |
+
for i, mask in enumerate(masks):
|
| 507 |
+
masked_value = value & mask
|
| 508 |
+
# Remove the zero padding, and scale it to 8 bits
|
| 509 |
+
data += o8(
|
| 510 |
+
int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
|
| 511 |
+
)
|
| 512 |
+
self.set_as_raw(data)
|
| 513 |
+
return -1, 0
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 517 |
+
if im.mode not in ("RGB", "RGBA", "L", "LA"):
|
| 518 |
+
msg = f"cannot write mode {im.mode} as DDS"
|
| 519 |
+
raise OSError(msg)
|
| 520 |
+
|
| 521 |
+
alpha = im.mode[-1] == "A"
|
| 522 |
+
if im.mode[0] == "L":
|
| 523 |
+
pixel_flags = DDPF.LUMINANCE
|
| 524 |
+
rawmode = im.mode
|
| 525 |
+
if alpha:
|
| 526 |
+
rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
|
| 527 |
+
else:
|
| 528 |
+
rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
|
| 529 |
+
else:
|
| 530 |
+
pixel_flags = DDPF.RGB
|
| 531 |
+
rawmode = im.mode[::-1]
|
| 532 |
+
rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
|
| 533 |
+
|
| 534 |
+
if alpha:
|
| 535 |
+
r, g, b, a = im.split()
|
| 536 |
+
im = Image.merge("RGBA", (a, r, g, b))
|
| 537 |
+
if alpha:
|
| 538 |
+
pixel_flags |= DDPF.ALPHAPIXELS
|
| 539 |
+
rgba_mask.append(0xFF000000 if alpha else 0)
|
| 540 |
+
|
| 541 |
+
flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PITCH | DDSD.PIXELFORMAT
|
| 542 |
+
bitcount = len(im.getbands()) * 8
|
| 543 |
+
pitch = (im.width * bitcount + 7) // 8
|
| 544 |
+
|
| 545 |
+
fp.write(
|
| 546 |
+
o32(DDS_MAGIC)
|
| 547 |
+
+ struct.pack(
|
| 548 |
+
"<7I",
|
| 549 |
+
124, # header size
|
| 550 |
+
flags, # flags
|
| 551 |
+
im.height,
|
| 552 |
+
im.width,
|
| 553 |
+
pitch,
|
| 554 |
+
0, # depth
|
| 555 |
+
0, # mipmaps
|
| 556 |
+
)
|
| 557 |
+
+ struct.pack("11I", *((0,) * 11)) # reserved
|
| 558 |
+
# pfsize, pfflags, fourcc, bitcount
|
| 559 |
+
+ struct.pack("<4I", 32, pixel_flags, 0, bitcount)
|
| 560 |
+
+ struct.pack("<4I", *rgba_mask) # dwRGBABitMask
|
| 561 |
+
+ struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
|
| 562 |
+
)
|
| 563 |
+
ImageFile._save(
|
| 564 |
+
im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _accept(prefix: bytes) -> bool:
|
| 569 |
+
return prefix[:4] == b"DDS "
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
|
| 573 |
+
Image.register_decoder("dds_rgb", DdsRgbDecoder)
|
| 574 |
+
Image.register_save(DdsImageFile.format, _save)
|
| 575 |
+
Image.register_extension(DdsImageFile.format, ".dds")
|
valley/lib/python3.10/site-packages/PIL/FliImagePlugin.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# FLI/FLC file handling.
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-09-01 fl Created
|
| 9 |
+
# 97-01-03 fl Fixed parser, setup decoder tile
|
| 10 |
+
# 98-07-15 fl Renamed offset attribute to avoid name clash
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile, ImagePalette
|
| 22 |
+
from ._binary import i16le as i16
|
| 23 |
+
from ._binary import i32le as i32
|
| 24 |
+
from ._binary import o8
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# decoder
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _accept(prefix: bytes) -> bool:
|
| 31 |
+
return (
|
| 32 |
+
len(prefix) >= 6
|
| 33 |
+
and i16(prefix, 4) in [0xAF11, 0xAF12]
|
| 34 |
+
and i16(prefix, 14) in [0, 3] # flags
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
##
|
| 39 |
+
# Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
|
| 40 |
+
# method to load individual frames.
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class FliImageFile(ImageFile.ImageFile):
|
| 44 |
+
format = "FLI"
|
| 45 |
+
format_description = "Autodesk FLI/FLC Animation"
|
| 46 |
+
_close_exclusive_fp_after_loading = False
|
| 47 |
+
|
| 48 |
+
def _open(self):
|
| 49 |
+
# HEAD
|
| 50 |
+
s = self.fp.read(128)
|
| 51 |
+
if not (_accept(s) and s[20:22] == b"\x00\x00"):
|
| 52 |
+
msg = "not an FLI/FLC file"
|
| 53 |
+
raise SyntaxError(msg)
|
| 54 |
+
|
| 55 |
+
# frames
|
| 56 |
+
self.n_frames = i16(s, 6)
|
| 57 |
+
self.is_animated = self.n_frames > 1
|
| 58 |
+
|
| 59 |
+
# image characteristics
|
| 60 |
+
self._mode = "P"
|
| 61 |
+
self._size = i16(s, 8), i16(s, 10)
|
| 62 |
+
|
| 63 |
+
# animation speed
|
| 64 |
+
duration = i32(s, 16)
|
| 65 |
+
magic = i16(s, 4)
|
| 66 |
+
if magic == 0xAF11:
|
| 67 |
+
duration = (duration * 1000) // 70
|
| 68 |
+
self.info["duration"] = duration
|
| 69 |
+
|
| 70 |
+
# look for palette
|
| 71 |
+
palette = [(a, a, a) for a in range(256)]
|
| 72 |
+
|
| 73 |
+
s = self.fp.read(16)
|
| 74 |
+
|
| 75 |
+
self.__offset = 128
|
| 76 |
+
|
| 77 |
+
if i16(s, 4) == 0xF100:
|
| 78 |
+
# prefix chunk; ignore it
|
| 79 |
+
self.__offset = self.__offset + i32(s)
|
| 80 |
+
self.fp.seek(self.__offset)
|
| 81 |
+
s = self.fp.read(16)
|
| 82 |
+
|
| 83 |
+
if i16(s, 4) == 0xF1FA:
|
| 84 |
+
# look for palette chunk
|
| 85 |
+
number_of_subchunks = i16(s, 6)
|
| 86 |
+
chunk_size = None
|
| 87 |
+
for _ in range(number_of_subchunks):
|
| 88 |
+
if chunk_size is not None:
|
| 89 |
+
self.fp.seek(chunk_size - 6, os.SEEK_CUR)
|
| 90 |
+
s = self.fp.read(6)
|
| 91 |
+
chunk_type = i16(s, 4)
|
| 92 |
+
if chunk_type in (4, 11):
|
| 93 |
+
self._palette(palette, 2 if chunk_type == 11 else 0)
|
| 94 |
+
break
|
| 95 |
+
chunk_size = i32(s)
|
| 96 |
+
if not chunk_size:
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette]
|
| 100 |
+
self.palette = ImagePalette.raw("RGB", b"".join(palette))
|
| 101 |
+
|
| 102 |
+
# set things up to decode first frame
|
| 103 |
+
self.__frame = -1
|
| 104 |
+
self._fp = self.fp
|
| 105 |
+
self.__rewind = self.fp.tell()
|
| 106 |
+
self.seek(0)
|
| 107 |
+
|
| 108 |
+
def _palette(self, palette, shift):
|
| 109 |
+
# load palette
|
| 110 |
+
|
| 111 |
+
i = 0
|
| 112 |
+
for e in range(i16(self.fp.read(2))):
|
| 113 |
+
s = self.fp.read(2)
|
| 114 |
+
i = i + s[0]
|
| 115 |
+
n = s[1]
|
| 116 |
+
if n == 0:
|
| 117 |
+
n = 256
|
| 118 |
+
s = self.fp.read(n * 3)
|
| 119 |
+
for n in range(0, len(s), 3):
|
| 120 |
+
r = s[n] << shift
|
| 121 |
+
g = s[n + 1] << shift
|
| 122 |
+
b = s[n + 2] << shift
|
| 123 |
+
palette[i] = (r, g, b)
|
| 124 |
+
i += 1
|
| 125 |
+
|
| 126 |
+
def seek(self, frame: int) -> None:
|
| 127 |
+
if not self._seek_check(frame):
|
| 128 |
+
return
|
| 129 |
+
if frame < self.__frame:
|
| 130 |
+
self._seek(0)
|
| 131 |
+
|
| 132 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 133 |
+
self._seek(f)
|
| 134 |
+
|
| 135 |
+
def _seek(self, frame: int) -> None:
|
| 136 |
+
if frame == 0:
|
| 137 |
+
self.__frame = -1
|
| 138 |
+
self._fp.seek(self.__rewind)
|
| 139 |
+
self.__offset = 128
|
| 140 |
+
else:
|
| 141 |
+
# ensure that the previous frame was loaded
|
| 142 |
+
self.load()
|
| 143 |
+
|
| 144 |
+
if frame != self.__frame + 1:
|
| 145 |
+
msg = f"cannot seek to frame {frame}"
|
| 146 |
+
raise ValueError(msg)
|
| 147 |
+
self.__frame = frame
|
| 148 |
+
|
| 149 |
+
# move to next frame
|
| 150 |
+
self.fp = self._fp
|
| 151 |
+
self.fp.seek(self.__offset)
|
| 152 |
+
|
| 153 |
+
s = self.fp.read(4)
|
| 154 |
+
if not s:
|
| 155 |
+
msg = "missing frame size"
|
| 156 |
+
raise EOFError(msg)
|
| 157 |
+
|
| 158 |
+
framesize = i32(s)
|
| 159 |
+
|
| 160 |
+
self.decodermaxblock = framesize
|
| 161 |
+
self.tile = [("fli", (0, 0) + self.size, self.__offset, None)]
|
| 162 |
+
|
| 163 |
+
self.__offset += framesize
|
| 164 |
+
|
| 165 |
+
def tell(self) -> int:
|
| 166 |
+
return self.__frame
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
#
|
| 170 |
+
# registry
|
| 171 |
+
|
| 172 |
+
Image.register_open(FliImageFile.format, FliImageFile, _accept)
|
| 173 |
+
|
| 174 |
+
Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
|
valley/lib/python3.10/site-packages/PIL/FontFile.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# base class for raster font file parsers
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1997-06-05 fl created
|
| 9 |
+
# 1997-08-19 fl restrict image width
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 1997-1998 by Secret Labs AB
|
| 12 |
+
# Copyright (c) 1997-1998 by Fredrik Lundh
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from typing import BinaryIO
|
| 20 |
+
|
| 21 |
+
from . import Image, _binary
|
| 22 |
+
|
| 23 |
+
WIDTH = 800
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def puti16(
|
| 27 |
+
fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
|
| 28 |
+
) -> None:
|
| 29 |
+
"""Write network order (big-endian) 16-bit sequence"""
|
| 30 |
+
for v in values:
|
| 31 |
+
if v < 0:
|
| 32 |
+
v += 65536
|
| 33 |
+
fp.write(_binary.o16be(v))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class FontFile:
|
| 37 |
+
"""Base class for raster font file handlers."""
|
| 38 |
+
|
| 39 |
+
bitmap: Image.Image | None = None
|
| 40 |
+
|
| 41 |
+
def __init__(self) -> None:
|
| 42 |
+
self.info: dict[bytes, bytes | int] = {}
|
| 43 |
+
self.glyph: list[
|
| 44 |
+
tuple[
|
| 45 |
+
tuple[int, int],
|
| 46 |
+
tuple[int, int, int, int],
|
| 47 |
+
tuple[int, int, int, int],
|
| 48 |
+
Image.Image,
|
| 49 |
+
]
|
| 50 |
+
| None
|
| 51 |
+
] = [None] * 256
|
| 52 |
+
|
| 53 |
+
def __getitem__(self, ix: int) -> (
|
| 54 |
+
tuple[
|
| 55 |
+
tuple[int, int],
|
| 56 |
+
tuple[int, int, int, int],
|
| 57 |
+
tuple[int, int, int, int],
|
| 58 |
+
Image.Image,
|
| 59 |
+
]
|
| 60 |
+
| None
|
| 61 |
+
):
|
| 62 |
+
return self.glyph[ix]
|
| 63 |
+
|
| 64 |
+
def compile(self) -> None:
|
| 65 |
+
"""Create metrics and bitmap"""
|
| 66 |
+
|
| 67 |
+
if self.bitmap:
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
# create bitmap large enough to hold all data
|
| 71 |
+
h = w = maxwidth = 0
|
| 72 |
+
lines = 1
|
| 73 |
+
for glyph in self.glyph:
|
| 74 |
+
if glyph:
|
| 75 |
+
d, dst, src, im = glyph
|
| 76 |
+
h = max(h, src[3] - src[1])
|
| 77 |
+
w = w + (src[2] - src[0])
|
| 78 |
+
if w > WIDTH:
|
| 79 |
+
lines += 1
|
| 80 |
+
w = src[2] - src[0]
|
| 81 |
+
maxwidth = max(maxwidth, w)
|
| 82 |
+
|
| 83 |
+
xsize = maxwidth
|
| 84 |
+
ysize = lines * h
|
| 85 |
+
|
| 86 |
+
if xsize == 0 and ysize == 0:
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
self.ysize = h
|
| 90 |
+
|
| 91 |
+
# paste glyphs into bitmap
|
| 92 |
+
self.bitmap = Image.new("1", (xsize, ysize))
|
| 93 |
+
self.metrics: list[
|
| 94 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
|
| 95 |
+
| None
|
| 96 |
+
] = [None] * 256
|
| 97 |
+
x = y = 0
|
| 98 |
+
for i in range(256):
|
| 99 |
+
glyph = self[i]
|
| 100 |
+
if glyph:
|
| 101 |
+
d, dst, src, im = glyph
|
| 102 |
+
xx = src[2] - src[0]
|
| 103 |
+
x0, y0 = x, y
|
| 104 |
+
x = x + xx
|
| 105 |
+
if x > WIDTH:
|
| 106 |
+
x, y = 0, y + h
|
| 107 |
+
x0, y0 = x, y
|
| 108 |
+
x = xx
|
| 109 |
+
s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
|
| 110 |
+
self.bitmap.paste(im.crop(src), s)
|
| 111 |
+
self.metrics[i] = d, dst, s
|
| 112 |
+
|
| 113 |
+
def save(self, filename: str) -> None:
|
| 114 |
+
"""Save font"""
|
| 115 |
+
|
| 116 |
+
self.compile()
|
| 117 |
+
|
| 118 |
+
# font data
|
| 119 |
+
if not self.bitmap:
|
| 120 |
+
msg = "No bitmap created"
|
| 121 |
+
raise ValueError(msg)
|
| 122 |
+
self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
|
| 123 |
+
|
| 124 |
+
# font metrics
|
| 125 |
+
with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
|
| 126 |
+
fp.write(b"PILfont\n")
|
| 127 |
+
fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
|
| 128 |
+
fp.write(b"DATA\n")
|
| 129 |
+
for id in range(256):
|
| 130 |
+
m = self.metrics[id]
|
| 131 |
+
if not m:
|
| 132 |
+
puti16(fp, (0,) * 10)
|
| 133 |
+
else:
|
| 134 |
+
puti16(fp, m[0] + m[1] + m[2])
|
valley/lib/python3.10/site-packages/PIL/FpxImagePlugin.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
#
|
| 4 |
+
# The Python Imaging Library.
|
| 5 |
+
# $Id$
|
| 6 |
+
#
|
| 7 |
+
# FlashPix support for PIL
|
| 8 |
+
#
|
| 9 |
+
# History:
|
| 10 |
+
# 97-01-25 fl Created (reads uncompressed RGB images only)
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import olefile
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile
|
| 22 |
+
from ._binary import i32le as i32
|
| 23 |
+
|
| 24 |
+
# we map from colour field tuples to (mode, rawmode) descriptors
|
| 25 |
+
MODES = {
|
| 26 |
+
# opacity
|
| 27 |
+
(0x00007FFE,): ("A", "L"),
|
| 28 |
+
# monochrome
|
| 29 |
+
(0x00010000,): ("L", "L"),
|
| 30 |
+
(0x00018000, 0x00017FFE): ("RGBA", "LA"),
|
| 31 |
+
# photo YCC
|
| 32 |
+
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
|
| 33 |
+
(0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
|
| 34 |
+
# standard RGB (NIFRGB)
|
| 35 |
+
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
|
| 36 |
+
(0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
#
|
| 41 |
+
# --------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _accept(prefix: bytes) -> bool:
|
| 45 |
+
return prefix[:8] == olefile.MAGIC
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
##
|
| 49 |
+
# Image plugin for the FlashPix images.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FpxImageFile(ImageFile.ImageFile):
|
| 53 |
+
format = "FPX"
|
| 54 |
+
format_description = "FlashPix"
|
| 55 |
+
|
| 56 |
+
def _open(self):
|
| 57 |
+
#
|
| 58 |
+
# read the OLE directory and see if this is a likely
|
| 59 |
+
# to be a FlashPix file
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
self.ole = olefile.OleFileIO(self.fp)
|
| 63 |
+
except OSError as e:
|
| 64 |
+
msg = "not an FPX file; invalid OLE file"
|
| 65 |
+
raise SyntaxError(msg) from e
|
| 66 |
+
|
| 67 |
+
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
|
| 68 |
+
msg = "not an FPX file; bad root CLSID"
|
| 69 |
+
raise SyntaxError(msg)
|
| 70 |
+
|
| 71 |
+
self._open_index(1)
|
| 72 |
+
|
| 73 |
+
def _open_index(self, index: int = 1) -> None:
|
| 74 |
+
#
|
| 75 |
+
# get the Image Contents Property Set
|
| 76 |
+
|
| 77 |
+
prop = self.ole.getproperties(
|
| 78 |
+
[f"Data Object Store {index:06d}", "\005Image Contents"]
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# size (highest resolution)
|
| 82 |
+
|
| 83 |
+
self._size = prop[0x1000002], prop[0x1000003]
|
| 84 |
+
|
| 85 |
+
size = max(self.size)
|
| 86 |
+
i = 1
|
| 87 |
+
while size > 64:
|
| 88 |
+
size = size // 2
|
| 89 |
+
i += 1
|
| 90 |
+
self.maxid = i - 1
|
| 91 |
+
|
| 92 |
+
# mode. instead of using a single field for this, flashpix
|
| 93 |
+
# requires you to specify the mode for each channel in each
|
| 94 |
+
# resolution subimage, and leaves it to the decoder to make
|
| 95 |
+
# sure that they all match. for now, we'll cheat and assume
|
| 96 |
+
# that this is always the case.
|
| 97 |
+
|
| 98 |
+
id = self.maxid << 16
|
| 99 |
+
|
| 100 |
+
s = prop[0x2000002 | id]
|
| 101 |
+
|
| 102 |
+
bands = i32(s, 4)
|
| 103 |
+
if bands > 4:
|
| 104 |
+
msg = "Invalid number of bands"
|
| 105 |
+
raise OSError(msg)
|
| 106 |
+
|
| 107 |
+
# note: for now, we ignore the "uncalibrated" flag
|
| 108 |
+
colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
|
| 109 |
+
|
| 110 |
+
self._mode, self.rawmode = MODES[colors]
|
| 111 |
+
|
| 112 |
+
# load JPEG tables, if any
|
| 113 |
+
self.jpeg = {}
|
| 114 |
+
for i in range(256):
|
| 115 |
+
id = 0x3000001 | (i << 16)
|
| 116 |
+
if id in prop:
|
| 117 |
+
self.jpeg[i] = prop[id]
|
| 118 |
+
|
| 119 |
+
self._open_subimage(1, self.maxid)
|
| 120 |
+
|
| 121 |
+
def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
|
| 122 |
+
#
|
| 123 |
+
# setup tile descriptors for a given subimage
|
| 124 |
+
|
| 125 |
+
stream = [
|
| 126 |
+
f"Data Object Store {index:06d}",
|
| 127 |
+
f"Resolution {subimage:04d}",
|
| 128 |
+
"Subimage 0000 Header",
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
fp = self.ole.openstream(stream)
|
| 132 |
+
|
| 133 |
+
# skip prefix
|
| 134 |
+
fp.read(28)
|
| 135 |
+
|
| 136 |
+
# header stream
|
| 137 |
+
s = fp.read(36)
|
| 138 |
+
|
| 139 |
+
size = i32(s, 4), i32(s, 8)
|
| 140 |
+
# tilecount = i32(s, 12)
|
| 141 |
+
tilesize = i32(s, 16), i32(s, 20)
|
| 142 |
+
# channels = i32(s, 24)
|
| 143 |
+
offset = i32(s, 28)
|
| 144 |
+
length = i32(s, 32)
|
| 145 |
+
|
| 146 |
+
if size != self.size:
|
| 147 |
+
msg = "subimage mismatch"
|
| 148 |
+
raise OSError(msg)
|
| 149 |
+
|
| 150 |
+
# get tile descriptors
|
| 151 |
+
fp.seek(28 + offset)
|
| 152 |
+
s = fp.read(i32(s, 12) * length)
|
| 153 |
+
|
| 154 |
+
x = y = 0
|
| 155 |
+
xsize, ysize = size
|
| 156 |
+
xtile, ytile = tilesize
|
| 157 |
+
self.tile = []
|
| 158 |
+
|
| 159 |
+
for i in range(0, len(s), length):
|
| 160 |
+
x1 = min(xsize, x + xtile)
|
| 161 |
+
y1 = min(ysize, y + ytile)
|
| 162 |
+
|
| 163 |
+
compression = i32(s, i + 8)
|
| 164 |
+
|
| 165 |
+
if compression == 0:
|
| 166 |
+
self.tile.append(
|
| 167 |
+
(
|
| 168 |
+
"raw",
|
| 169 |
+
(x, y, x1, y1),
|
| 170 |
+
i32(s, i) + 28,
|
| 171 |
+
(self.rawmode,),
|
| 172 |
+
)
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
elif compression == 1:
|
| 176 |
+
# FIXME: the fill decoder is not implemented
|
| 177 |
+
self.tile.append(
|
| 178 |
+
(
|
| 179 |
+
"fill",
|
| 180 |
+
(x, y, x1, y1),
|
| 181 |
+
i32(s, i) + 28,
|
| 182 |
+
(self.rawmode, s[12:16]),
|
| 183 |
+
)
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
elif compression == 2:
|
| 187 |
+
internal_color_conversion = s[14]
|
| 188 |
+
jpeg_tables = s[15]
|
| 189 |
+
rawmode = self.rawmode
|
| 190 |
+
|
| 191 |
+
if internal_color_conversion:
|
| 192 |
+
# The image is stored as usual (usually YCbCr).
|
| 193 |
+
if rawmode == "RGBA":
|
| 194 |
+
# For "RGBA", data is stored as YCbCrA based on
|
| 195 |
+
# negative RGB. The following trick works around
|
| 196 |
+
# this problem :
|
| 197 |
+
jpegmode, rawmode = "YCbCrK", "CMYK"
|
| 198 |
+
else:
|
| 199 |
+
jpegmode = None # let the decoder decide
|
| 200 |
+
|
| 201 |
+
else:
|
| 202 |
+
# The image is stored as defined by rawmode
|
| 203 |
+
jpegmode = rawmode
|
| 204 |
+
|
| 205 |
+
self.tile.append(
|
| 206 |
+
(
|
| 207 |
+
"jpeg",
|
| 208 |
+
(x, y, x1, y1),
|
| 209 |
+
i32(s, i) + 28,
|
| 210 |
+
(rawmode, jpegmode),
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# FIXME: jpeg tables are tile dependent; the prefix
|
| 215 |
+
# data must be placed in the tile descriptor itself!
|
| 216 |
+
|
| 217 |
+
if jpeg_tables:
|
| 218 |
+
self.tile_prefix = self.jpeg[jpeg_tables]
|
| 219 |
+
|
| 220 |
+
else:
|
| 221 |
+
msg = "unknown/invalid compression"
|
| 222 |
+
raise OSError(msg)
|
| 223 |
+
|
| 224 |
+
x = x + xtile
|
| 225 |
+
if x >= xsize:
|
| 226 |
+
x, y = 0, y + ytile
|
| 227 |
+
if y >= ysize:
|
| 228 |
+
break # isn't really required
|
| 229 |
+
|
| 230 |
+
self.stream = stream
|
| 231 |
+
self._fp = self.fp
|
| 232 |
+
self.fp = None
|
| 233 |
+
|
| 234 |
+
def load(self):
|
| 235 |
+
if not self.fp:
|
| 236 |
+
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
|
| 237 |
+
|
| 238 |
+
return ImageFile.ImageFile.load(self)
|
| 239 |
+
|
| 240 |
+
def close(self) -> None:
|
| 241 |
+
self.ole.close()
|
| 242 |
+
super().close()
|
| 243 |
+
|
| 244 |
+
def __exit__(self, *args: object) -> None:
|
| 245 |
+
self.ole.close()
|
| 246 |
+
super().__exit__()
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
#
|
| 250 |
+
# --------------------------------------------------------------------
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
|
| 254 |
+
|
| 255 |
+
Image.register_extension(FpxImageFile.format, ".fpx")
|
valley/lib/python3.10/site-packages/PIL/GimpGradientFile.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
#
|
| 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))
|
valley/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# GRIB stub adapter
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
| 8 |
+
#
|
| 9 |
+
# See the README file for information on usage and redistribution.
|
| 10 |
+
#
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import IO
|
| 14 |
+
|
| 15 |
+
from . import Image, ImageFile
|
| 16 |
+
|
| 17 |
+
_handler = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 21 |
+
"""
|
| 22 |
+
Install application-specific GRIB image handler.
|
| 23 |
+
|
| 24 |
+
:param handler: Handler object.
|
| 25 |
+
"""
|
| 26 |
+
global _handler
|
| 27 |
+
_handler = handler
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# --------------------------------------------------------------------
|
| 31 |
+
# Image adapter
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return prefix[:4] == b"GRIB" and prefix[7] == 1
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GribStubImageFile(ImageFile.StubImageFile):
|
| 39 |
+
format = "GRIB"
|
| 40 |
+
format_description = "GRIB"
|
| 41 |
+
|
| 42 |
+
def _open(self) -> None:
|
| 43 |
+
offset = self.fp.tell()
|
| 44 |
+
|
| 45 |
+
if not _accept(self.fp.read(8)):
|
| 46 |
+
msg = "Not a GRIB file"
|
| 47 |
+
raise SyntaxError(msg)
|
| 48 |
+
|
| 49 |
+
self.fp.seek(offset)
|
| 50 |
+
|
| 51 |
+
# make something up
|
| 52 |
+
self._mode = "F"
|
| 53 |
+
self._size = 1, 1
|
| 54 |
+
|
| 55 |
+
loader = self._load()
|
| 56 |
+
if loader:
|
| 57 |
+
loader.open(self)
|
| 58 |
+
|
| 59 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 60 |
+
return _handler
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 64 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 65 |
+
msg = "GRIB save handler not installed"
|
| 66 |
+
raise OSError(msg)
|
| 67 |
+
_handler.save(im, fp, filename)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --------------------------------------------------------------------
|
| 71 |
+
# Registry
|
| 72 |
+
|
| 73 |
+
Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
|
| 74 |
+
Image.register_save(GribStubImageFile.format, _save)
|
| 75 |
+
|
| 76 |
+
Image.register_extension(GribStubImageFile.format, ".grib")
|
valley/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"])
|
valley/lib/python3.10/site-packages/PIL/IcnsImagePlugin.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
#
|
| 5 |
+
# macOS icns file decoder, based on icns.py by Bob Ippolito.
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
|
| 9 |
+
# 2020-04-04 Allow saving on all operating systems.
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2004 by Bob Ippolito.
|
| 12 |
+
# Copyright (c) 2004 by Secret Labs.
|
| 13 |
+
# Copyright (c) 2004 by Fredrik Lundh.
|
| 14 |
+
# Copyright (c) 2014 by Alastair Houghton.
|
| 15 |
+
# Copyright (c) 2020 by Pan Jing.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import io
|
| 22 |
+
import os
|
| 23 |
+
import struct
|
| 24 |
+
import sys
|
| 25 |
+
from typing import IO
|
| 26 |
+
|
| 27 |
+
from . import Image, ImageFile, PngImagePlugin, features
|
| 28 |
+
|
| 29 |
+
enable_jpeg2k = features.check_codec("jpg_2000")
|
| 30 |
+
if enable_jpeg2k:
|
| 31 |
+
from . import Jpeg2KImagePlugin
|
| 32 |
+
|
| 33 |
+
MAGIC = b"icns"
|
| 34 |
+
HEADERSIZE = 8
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def nextheader(fobj):
|
| 38 |
+
return struct.unpack(">4sI", fobj.read(HEADERSIZE))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def read_32t(fobj, start_length, size):
|
| 42 |
+
# The 128x128 icon seems to have an extra header for some reason.
|
| 43 |
+
(start, length) = start_length
|
| 44 |
+
fobj.seek(start)
|
| 45 |
+
sig = fobj.read(4)
|
| 46 |
+
if sig != b"\x00\x00\x00\x00":
|
| 47 |
+
msg = "Unknown signature, expecting 0x00000000"
|
| 48 |
+
raise SyntaxError(msg)
|
| 49 |
+
return read_32(fobj, (start + 4, length - 4), size)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def read_32(fobj, start_length, size):
|
| 53 |
+
"""
|
| 54 |
+
Read a 32bit RGB icon resource. Seems to be either uncompressed or
|
| 55 |
+
an RLE packbits-like scheme.
|
| 56 |
+
"""
|
| 57 |
+
(start, length) = start_length
|
| 58 |
+
fobj.seek(start)
|
| 59 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 60 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 61 |
+
if length == sizesq * 3:
|
| 62 |
+
# uncompressed ("RGBRGBGB")
|
| 63 |
+
indata = fobj.read(length)
|
| 64 |
+
im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
|
| 65 |
+
else:
|
| 66 |
+
# decode image
|
| 67 |
+
im = Image.new("RGB", pixel_size, None)
|
| 68 |
+
for band_ix in range(3):
|
| 69 |
+
data = []
|
| 70 |
+
bytesleft = sizesq
|
| 71 |
+
while bytesleft > 0:
|
| 72 |
+
byte = fobj.read(1)
|
| 73 |
+
if not byte:
|
| 74 |
+
break
|
| 75 |
+
byte = byte[0]
|
| 76 |
+
if byte & 0x80:
|
| 77 |
+
blocksize = byte - 125
|
| 78 |
+
byte = fobj.read(1)
|
| 79 |
+
for i in range(blocksize):
|
| 80 |
+
data.append(byte)
|
| 81 |
+
else:
|
| 82 |
+
blocksize = byte + 1
|
| 83 |
+
data.append(fobj.read(blocksize))
|
| 84 |
+
bytesleft -= blocksize
|
| 85 |
+
if bytesleft <= 0:
|
| 86 |
+
break
|
| 87 |
+
if bytesleft != 0:
|
| 88 |
+
msg = f"Error reading channel [{repr(bytesleft)} left]"
|
| 89 |
+
raise SyntaxError(msg)
|
| 90 |
+
band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
|
| 91 |
+
im.im.putband(band.im, band_ix)
|
| 92 |
+
return {"RGB": im}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def read_mk(fobj, start_length, size):
|
| 96 |
+
# Alpha masks seem to be uncompressed
|
| 97 |
+
start = start_length[0]
|
| 98 |
+
fobj.seek(start)
|
| 99 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 100 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 101 |
+
band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
|
| 102 |
+
return {"A": band}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def read_png_or_jpeg2000(fobj, start_length, size):
|
| 106 |
+
(start, length) = start_length
|
| 107 |
+
fobj.seek(start)
|
| 108 |
+
sig = fobj.read(12)
|
| 109 |
+
if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
|
| 110 |
+
fobj.seek(start)
|
| 111 |
+
im = PngImagePlugin.PngImageFile(fobj)
|
| 112 |
+
Image._decompression_bomb_check(im.size)
|
| 113 |
+
return {"RGBA": im}
|
| 114 |
+
elif (
|
| 115 |
+
sig[:4] == b"\xff\x4f\xff\x51"
|
| 116 |
+
or sig[:4] == b"\x0d\x0a\x87\x0a"
|
| 117 |
+
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
| 118 |
+
):
|
| 119 |
+
if not enable_jpeg2k:
|
| 120 |
+
msg = (
|
| 121 |
+
"Unsupported icon subimage format (rebuild PIL "
|
| 122 |
+
"with JPEG 2000 support to fix this)"
|
| 123 |
+
)
|
| 124 |
+
raise ValueError(msg)
|
| 125 |
+
# j2k, jpc or j2c
|
| 126 |
+
fobj.seek(start)
|
| 127 |
+
jp2kstream = fobj.read(length)
|
| 128 |
+
f = io.BytesIO(jp2kstream)
|
| 129 |
+
im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
|
| 130 |
+
Image._decompression_bomb_check(im.size)
|
| 131 |
+
if im.mode != "RGBA":
|
| 132 |
+
im = im.convert("RGBA")
|
| 133 |
+
return {"RGBA": im}
|
| 134 |
+
else:
|
| 135 |
+
msg = "Unsupported icon subimage format"
|
| 136 |
+
raise ValueError(msg)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class IcnsFile:
|
| 140 |
+
SIZES = {
|
| 141 |
+
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
|
| 142 |
+
(512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
|
| 143 |
+
(256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
|
| 144 |
+
(256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
|
| 145 |
+
(128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
|
| 146 |
+
(128, 128, 1): [
|
| 147 |
+
(b"ic07", read_png_or_jpeg2000),
|
| 148 |
+
(b"it32", read_32t),
|
| 149 |
+
(b"t8mk", read_mk),
|
| 150 |
+
],
|
| 151 |
+
(64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
|
| 152 |
+
(32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
|
| 153 |
+
(48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
|
| 154 |
+
(32, 32, 1): [
|
| 155 |
+
(b"icp5", read_png_or_jpeg2000),
|
| 156 |
+
(b"il32", read_32),
|
| 157 |
+
(b"l8mk", read_mk),
|
| 158 |
+
],
|
| 159 |
+
(16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
|
| 160 |
+
(16, 16, 1): [
|
| 161 |
+
(b"icp4", read_png_or_jpeg2000),
|
| 162 |
+
(b"is32", read_32),
|
| 163 |
+
(b"s8mk", read_mk),
|
| 164 |
+
],
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
def __init__(self, fobj):
|
| 168 |
+
"""
|
| 169 |
+
fobj is a file-like object as an icns resource
|
| 170 |
+
"""
|
| 171 |
+
# signature : (start, length)
|
| 172 |
+
self.dct = dct = {}
|
| 173 |
+
self.fobj = fobj
|
| 174 |
+
sig, filesize = nextheader(fobj)
|
| 175 |
+
if not _accept(sig):
|
| 176 |
+
msg = "not an icns file"
|
| 177 |
+
raise SyntaxError(msg)
|
| 178 |
+
i = HEADERSIZE
|
| 179 |
+
while i < filesize:
|
| 180 |
+
sig, blocksize = nextheader(fobj)
|
| 181 |
+
if blocksize <= 0:
|
| 182 |
+
msg = "invalid block header"
|
| 183 |
+
raise SyntaxError(msg)
|
| 184 |
+
i += HEADERSIZE
|
| 185 |
+
blocksize -= HEADERSIZE
|
| 186 |
+
dct[sig] = (i, blocksize)
|
| 187 |
+
fobj.seek(blocksize, io.SEEK_CUR)
|
| 188 |
+
i += blocksize
|
| 189 |
+
|
| 190 |
+
def itersizes(self):
|
| 191 |
+
sizes = []
|
| 192 |
+
for size, fmts in self.SIZES.items():
|
| 193 |
+
for fmt, reader in fmts:
|
| 194 |
+
if fmt in self.dct:
|
| 195 |
+
sizes.append(size)
|
| 196 |
+
break
|
| 197 |
+
return sizes
|
| 198 |
+
|
| 199 |
+
def bestsize(self):
|
| 200 |
+
sizes = self.itersizes()
|
| 201 |
+
if not sizes:
|
| 202 |
+
msg = "No 32bit icon resources found"
|
| 203 |
+
raise SyntaxError(msg)
|
| 204 |
+
return max(sizes)
|
| 205 |
+
|
| 206 |
+
def dataforsize(self, size):
|
| 207 |
+
"""
|
| 208 |
+
Get an icon resource as {channel: array}. Note that
|
| 209 |
+
the arrays are bottom-up like windows bitmaps and will likely
|
| 210 |
+
need to be flipped or transposed in some way.
|
| 211 |
+
"""
|
| 212 |
+
dct = {}
|
| 213 |
+
for code, reader in self.SIZES[size]:
|
| 214 |
+
desc = self.dct.get(code)
|
| 215 |
+
if desc is not None:
|
| 216 |
+
dct.update(reader(self.fobj, desc, size))
|
| 217 |
+
return dct
|
| 218 |
+
|
| 219 |
+
def getimage(self, size=None):
|
| 220 |
+
if size is None:
|
| 221 |
+
size = self.bestsize()
|
| 222 |
+
if len(size) == 2:
|
| 223 |
+
size = (size[0], size[1], 1)
|
| 224 |
+
channels = self.dataforsize(size)
|
| 225 |
+
|
| 226 |
+
im = channels.get("RGBA", None)
|
| 227 |
+
if im:
|
| 228 |
+
return im
|
| 229 |
+
|
| 230 |
+
im = channels.get("RGB").copy()
|
| 231 |
+
try:
|
| 232 |
+
im.putalpha(channels["A"])
|
| 233 |
+
except KeyError:
|
| 234 |
+
pass
|
| 235 |
+
return im
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
##
|
| 239 |
+
# Image plugin for Mac OS icons.
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class IcnsImageFile(ImageFile.ImageFile):
|
| 243 |
+
"""
|
| 244 |
+
PIL image support for Mac OS .icns files.
|
| 245 |
+
Chooses the best resolution, but will possibly load
|
| 246 |
+
a different size image if you mutate the size attribute
|
| 247 |
+
before calling 'load'.
|
| 248 |
+
|
| 249 |
+
The info dictionary has a key 'sizes' that is a list
|
| 250 |
+
of sizes that the icns file has.
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
format = "ICNS"
|
| 254 |
+
format_description = "Mac OS icns resource"
|
| 255 |
+
|
| 256 |
+
def _open(self) -> None:
|
| 257 |
+
self.icns = IcnsFile(self.fp)
|
| 258 |
+
self._mode = "RGBA"
|
| 259 |
+
self.info["sizes"] = self.icns.itersizes()
|
| 260 |
+
self.best_size = self.icns.bestsize()
|
| 261 |
+
self.size = (
|
| 262 |
+
self.best_size[0] * self.best_size[2],
|
| 263 |
+
self.best_size[1] * self.best_size[2],
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def size(self):
|
| 268 |
+
return self._size
|
| 269 |
+
|
| 270 |
+
@size.setter
|
| 271 |
+
def size(self, value):
|
| 272 |
+
info_size = value
|
| 273 |
+
if info_size not in self.info["sizes"] and len(info_size) == 2:
|
| 274 |
+
info_size = (info_size[0], info_size[1], 1)
|
| 275 |
+
if (
|
| 276 |
+
info_size not in self.info["sizes"]
|
| 277 |
+
and len(info_size) == 3
|
| 278 |
+
and info_size[2] == 1
|
| 279 |
+
):
|
| 280 |
+
simple_sizes = [
|
| 281 |
+
(size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
|
| 282 |
+
]
|
| 283 |
+
if value in simple_sizes:
|
| 284 |
+
info_size = self.info["sizes"][simple_sizes.index(value)]
|
| 285 |
+
if info_size not in self.info["sizes"]:
|
| 286 |
+
msg = "This is not one of the allowed sizes of this image"
|
| 287 |
+
raise ValueError(msg)
|
| 288 |
+
self._size = value
|
| 289 |
+
|
| 290 |
+
def load(self):
|
| 291 |
+
if len(self.size) == 3:
|
| 292 |
+
self.best_size = self.size
|
| 293 |
+
self.size = (
|
| 294 |
+
self.best_size[0] * self.best_size[2],
|
| 295 |
+
self.best_size[1] * self.best_size[2],
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
px = Image.Image.load(self)
|
| 299 |
+
if self.im is not None and self.im.size == self.size:
|
| 300 |
+
# Already loaded
|
| 301 |
+
return px
|
| 302 |
+
self.load_prepare()
|
| 303 |
+
# This is likely NOT the best way to do it, but whatever.
|
| 304 |
+
im = self.icns.getimage(self.best_size)
|
| 305 |
+
|
| 306 |
+
# If this is a PNG or JPEG 2000, it won't be loaded yet
|
| 307 |
+
px = im.load()
|
| 308 |
+
|
| 309 |
+
self.im = im.im
|
| 310 |
+
self._mode = im.mode
|
| 311 |
+
self.size = im.size
|
| 312 |
+
|
| 313 |
+
return px
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 317 |
+
"""
|
| 318 |
+
Saves the image as a series of PNG files,
|
| 319 |
+
that are then combined into a .icns file.
|
| 320 |
+
"""
|
| 321 |
+
if hasattr(fp, "flush"):
|
| 322 |
+
fp.flush()
|
| 323 |
+
|
| 324 |
+
sizes = {
|
| 325 |
+
b"ic07": 128,
|
| 326 |
+
b"ic08": 256,
|
| 327 |
+
b"ic09": 512,
|
| 328 |
+
b"ic10": 1024,
|
| 329 |
+
b"ic11": 32,
|
| 330 |
+
b"ic12": 64,
|
| 331 |
+
b"ic13": 256,
|
| 332 |
+
b"ic14": 512,
|
| 333 |
+
}
|
| 334 |
+
provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
|
| 335 |
+
size_streams = {}
|
| 336 |
+
for size in set(sizes.values()):
|
| 337 |
+
image = (
|
| 338 |
+
provided_images[size]
|
| 339 |
+
if size in provided_images
|
| 340 |
+
else im.resize((size, size))
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
temp = io.BytesIO()
|
| 344 |
+
image.save(temp, "png")
|
| 345 |
+
size_streams[size] = temp.getvalue()
|
| 346 |
+
|
| 347 |
+
entries = []
|
| 348 |
+
for type, size in sizes.items():
|
| 349 |
+
stream = size_streams[size]
|
| 350 |
+
entries.append((type, HEADERSIZE + len(stream), stream))
|
| 351 |
+
|
| 352 |
+
# Header
|
| 353 |
+
fp.write(MAGIC)
|
| 354 |
+
file_length = HEADERSIZE # Header
|
| 355 |
+
file_length += HEADERSIZE + 8 * len(entries) # TOC
|
| 356 |
+
file_length += sum(entry[1] for entry in entries)
|
| 357 |
+
fp.write(struct.pack(">i", file_length))
|
| 358 |
+
|
| 359 |
+
# TOC
|
| 360 |
+
fp.write(b"TOC ")
|
| 361 |
+
fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
|
| 362 |
+
for entry in entries:
|
| 363 |
+
fp.write(entry[0])
|
| 364 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 365 |
+
|
| 366 |
+
# Data
|
| 367 |
+
for entry in entries:
|
| 368 |
+
fp.write(entry[0])
|
| 369 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 370 |
+
fp.write(entry[2])
|
| 371 |
+
|
| 372 |
+
if hasattr(fp, "flush"):
|
| 373 |
+
fp.flush()
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _accept(prefix: bytes) -> bool:
|
| 377 |
+
return prefix[:4] == MAGIC
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
|
| 381 |
+
Image.register_extension(IcnsImageFile.format, ".icns")
|
| 382 |
+
|
| 383 |
+
Image.register_save(IcnsImageFile.format, _save)
|
| 384 |
+
Image.register_mime(IcnsImageFile.format, "image/icns")
|
| 385 |
+
|
| 386 |
+
if __name__ == "__main__":
|
| 387 |
+
if len(sys.argv) < 2:
|
| 388 |
+
print("Syntax: python3 IcnsImagePlugin.py [file]")
|
| 389 |
+
sys.exit()
|
| 390 |
+
|
| 391 |
+
with open(sys.argv[1], "rb") as fp:
|
| 392 |
+
imf = IcnsImageFile(fp)
|
| 393 |
+
for size in imf.info["sizes"]:
|
| 394 |
+
width, height, scale = imf.size = size
|
| 395 |
+
imf.save(f"out-{width}-{height}-{scale}.png")
|
| 396 |
+
with Image.open(sys.argv[1]) as im:
|
| 397 |
+
im.save("out.png")
|
| 398 |
+
if sys.platform == "windows":
|
| 399 |
+
os.startfile("out.png")
|
valley/lib/python3.10/site-packages/PIL/IcoImagePlugin.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Windows Icon support for PIL
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-05-27 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
| 17 |
+
# <casadebender@gmail.com>.
|
| 18 |
+
# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
| 19 |
+
#
|
| 20 |
+
# Icon format references:
|
| 21 |
+
# * https://en.wikipedia.org/wiki/ICO_(file_format)
|
| 22 |
+
# * https://msdn.microsoft.com/en-us/library/ms997538.aspx
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import warnings
|
| 26 |
+
from io import BytesIO
|
| 27 |
+
from math import ceil, log
|
| 28 |
+
from typing import IO
|
| 29 |
+
|
| 30 |
+
from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
|
| 31 |
+
from ._binary import i16le as i16
|
| 32 |
+
from ._binary import i32le as i32
|
| 33 |
+
from ._binary import o8
|
| 34 |
+
from ._binary import o16le as o16
|
| 35 |
+
from ._binary import o32le as o32
|
| 36 |
+
|
| 37 |
+
#
|
| 38 |
+
# --------------------------------------------------------------------
|
| 39 |
+
|
| 40 |
+
_MAGIC = b"\0\0\1\0"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 44 |
+
fp.write(_MAGIC) # (2+2)
|
| 45 |
+
bmp = im.encoderinfo.get("bitmap_format") == "bmp"
|
| 46 |
+
sizes = im.encoderinfo.get(
|
| 47 |
+
"sizes",
|
| 48 |
+
[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
|
| 49 |
+
)
|
| 50 |
+
frames = []
|
| 51 |
+
provided_ims = [im] + im.encoderinfo.get("append_images", [])
|
| 52 |
+
width, height = im.size
|
| 53 |
+
for size in sorted(set(sizes)):
|
| 54 |
+
if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
|
| 55 |
+
continue
|
| 56 |
+
|
| 57 |
+
for provided_im in provided_ims:
|
| 58 |
+
if provided_im.size != size:
|
| 59 |
+
continue
|
| 60 |
+
frames.append(provided_im)
|
| 61 |
+
if bmp:
|
| 62 |
+
bits = BmpImagePlugin.SAVE[provided_im.mode][1]
|
| 63 |
+
bits_used = [bits]
|
| 64 |
+
for other_im in provided_ims:
|
| 65 |
+
if other_im.size != size:
|
| 66 |
+
continue
|
| 67 |
+
bits = BmpImagePlugin.SAVE[other_im.mode][1]
|
| 68 |
+
if bits not in bits_used:
|
| 69 |
+
# Another image has been supplied for this size
|
| 70 |
+
# with a different bit depth
|
| 71 |
+
frames.append(other_im)
|
| 72 |
+
bits_used.append(bits)
|
| 73 |
+
break
|
| 74 |
+
else:
|
| 75 |
+
# TODO: invent a more convenient method for proportional scalings
|
| 76 |
+
frame = provided_im.copy()
|
| 77 |
+
frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
|
| 78 |
+
frames.append(frame)
|
| 79 |
+
fp.write(o16(len(frames))) # idCount(2)
|
| 80 |
+
offset = fp.tell() + len(frames) * 16
|
| 81 |
+
for frame in frames:
|
| 82 |
+
width, height = frame.size
|
| 83 |
+
# 0 means 256
|
| 84 |
+
fp.write(o8(width if width < 256 else 0)) # bWidth(1)
|
| 85 |
+
fp.write(o8(height if height < 256 else 0)) # bHeight(1)
|
| 86 |
+
|
| 87 |
+
bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
|
| 88 |
+
fp.write(o8(colors)) # bColorCount(1)
|
| 89 |
+
fp.write(b"\0") # bReserved(1)
|
| 90 |
+
fp.write(b"\0\0") # wPlanes(2)
|
| 91 |
+
fp.write(o16(bits)) # wBitCount(2)
|
| 92 |
+
|
| 93 |
+
image_io = BytesIO()
|
| 94 |
+
if bmp:
|
| 95 |
+
frame.save(image_io, "dib")
|
| 96 |
+
|
| 97 |
+
if bits != 32:
|
| 98 |
+
and_mask = Image.new("1", size)
|
| 99 |
+
ImageFile._save(
|
| 100 |
+
and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
frame.save(image_io, "png")
|
| 104 |
+
image_io.seek(0)
|
| 105 |
+
image_bytes = image_io.read()
|
| 106 |
+
if bmp:
|
| 107 |
+
image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
|
| 108 |
+
bytes_len = len(image_bytes)
|
| 109 |
+
fp.write(o32(bytes_len)) # dwBytesInRes(4)
|
| 110 |
+
fp.write(o32(offset)) # dwImageOffset(4)
|
| 111 |
+
current = fp.tell()
|
| 112 |
+
fp.seek(offset)
|
| 113 |
+
fp.write(image_bytes)
|
| 114 |
+
offset = offset + bytes_len
|
| 115 |
+
fp.seek(current)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _accept(prefix: bytes) -> bool:
|
| 119 |
+
return prefix[:4] == _MAGIC
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class IcoFile:
|
| 123 |
+
def __init__(self, buf):
|
| 124 |
+
"""
|
| 125 |
+
Parse image from file-like object containing ico file data
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
# check magic
|
| 129 |
+
s = buf.read(6)
|
| 130 |
+
if not _accept(s):
|
| 131 |
+
msg = "not an ICO file"
|
| 132 |
+
raise SyntaxError(msg)
|
| 133 |
+
|
| 134 |
+
self.buf = buf
|
| 135 |
+
self.entry = []
|
| 136 |
+
|
| 137 |
+
# Number of items in file
|
| 138 |
+
self.nb_items = i16(s, 4)
|
| 139 |
+
|
| 140 |
+
# Get headers for each item
|
| 141 |
+
for i in range(self.nb_items):
|
| 142 |
+
s = buf.read(16)
|
| 143 |
+
|
| 144 |
+
icon_header = {
|
| 145 |
+
"width": s[0],
|
| 146 |
+
"height": s[1],
|
| 147 |
+
"nb_color": s[2], # No. of colors in image (0 if >=8bpp)
|
| 148 |
+
"reserved": s[3],
|
| 149 |
+
"planes": i16(s, 4),
|
| 150 |
+
"bpp": i16(s, 6),
|
| 151 |
+
"size": i32(s, 8),
|
| 152 |
+
"offset": i32(s, 12),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# See Wikipedia
|
| 156 |
+
for j in ("width", "height"):
|
| 157 |
+
if not icon_header[j]:
|
| 158 |
+
icon_header[j] = 256
|
| 159 |
+
|
| 160 |
+
# See Wikipedia notes about color depth.
|
| 161 |
+
# We need this just to differ images with equal sizes
|
| 162 |
+
icon_header["color_depth"] = (
|
| 163 |
+
icon_header["bpp"]
|
| 164 |
+
or (
|
| 165 |
+
icon_header["nb_color"] != 0
|
| 166 |
+
and ceil(log(icon_header["nb_color"], 2))
|
| 167 |
+
)
|
| 168 |
+
or 256
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
icon_header["dim"] = (icon_header["width"], icon_header["height"])
|
| 172 |
+
icon_header["square"] = icon_header["width"] * icon_header["height"]
|
| 173 |
+
|
| 174 |
+
self.entry.append(icon_header)
|
| 175 |
+
|
| 176 |
+
self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
|
| 177 |
+
# ICO images are usually squares
|
| 178 |
+
self.entry = sorted(self.entry, key=lambda x: x["square"], reverse=True)
|
| 179 |
+
|
| 180 |
+
def sizes(self):
|
| 181 |
+
"""
|
| 182 |
+
Get a list of all available icon sizes and color depths.
|
| 183 |
+
"""
|
| 184 |
+
return {(h["width"], h["height"]) for h in self.entry}
|
| 185 |
+
|
| 186 |
+
def getentryindex(self, size, bpp=False):
|
| 187 |
+
for i, h in enumerate(self.entry):
|
| 188 |
+
if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
|
| 189 |
+
return i
|
| 190 |
+
return 0
|
| 191 |
+
|
| 192 |
+
def getimage(self, size, bpp=False):
|
| 193 |
+
"""
|
| 194 |
+
Get an image from the icon
|
| 195 |
+
"""
|
| 196 |
+
return self.frame(self.getentryindex(size, bpp))
|
| 197 |
+
|
| 198 |
+
def frame(self, idx: int) -> Image.Image:
|
| 199 |
+
"""
|
| 200 |
+
Get an image from frame idx
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
header = self.entry[idx]
|
| 204 |
+
|
| 205 |
+
self.buf.seek(header["offset"])
|
| 206 |
+
data = self.buf.read(8)
|
| 207 |
+
self.buf.seek(header["offset"])
|
| 208 |
+
|
| 209 |
+
im: Image.Image
|
| 210 |
+
if data[:8] == PngImagePlugin._MAGIC:
|
| 211 |
+
# png frame
|
| 212 |
+
im = PngImagePlugin.PngImageFile(self.buf)
|
| 213 |
+
Image._decompression_bomb_check(im.size)
|
| 214 |
+
else:
|
| 215 |
+
# XOR + AND mask bmp frame
|
| 216 |
+
im = BmpImagePlugin.DibImageFile(self.buf)
|
| 217 |
+
Image._decompression_bomb_check(im.size)
|
| 218 |
+
|
| 219 |
+
# change tile dimension to only encompass XOR image
|
| 220 |
+
im._size = (im.size[0], int(im.size[1] / 2))
|
| 221 |
+
d, e, o, a = im.tile[0]
|
| 222 |
+
im.tile[0] = d, (0, 0) + im.size, o, a
|
| 223 |
+
|
| 224 |
+
# figure out where AND mask image starts
|
| 225 |
+
bpp = header["bpp"]
|
| 226 |
+
if 32 == bpp:
|
| 227 |
+
# 32-bit color depth icon image allows semitransparent areas
|
| 228 |
+
# PIL's DIB format ignores transparency bits, recover them.
|
| 229 |
+
# The DIB is packed in BGRX byte order where X is the alpha
|
| 230 |
+
# channel.
|
| 231 |
+
|
| 232 |
+
# Back up to start of bmp data
|
| 233 |
+
self.buf.seek(o)
|
| 234 |
+
# extract every 4th byte (eg. 3,7,11,15,...)
|
| 235 |
+
alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
|
| 236 |
+
|
| 237 |
+
# convert to an 8bpp grayscale image
|
| 238 |
+
mask = Image.frombuffer(
|
| 239 |
+
"L", # 8bpp
|
| 240 |
+
im.size, # (w, h)
|
| 241 |
+
alpha_bytes, # source chars
|
| 242 |
+
"raw", # raw decoder
|
| 243 |
+
("L", 0, -1), # 8bpp inverted, unpadded, reversed
|
| 244 |
+
)
|
| 245 |
+
else:
|
| 246 |
+
# get AND image from end of bitmap
|
| 247 |
+
w = im.size[0]
|
| 248 |
+
if (w % 32) > 0:
|
| 249 |
+
# bitmap row data is aligned to word boundaries
|
| 250 |
+
w += 32 - (im.size[0] % 32)
|
| 251 |
+
|
| 252 |
+
# the total mask data is
|
| 253 |
+
# padded row size * height / bits per char
|
| 254 |
+
|
| 255 |
+
total_bytes = int((w * im.size[1]) / 8)
|
| 256 |
+
and_mask_offset = header["offset"] + header["size"] - total_bytes
|
| 257 |
+
|
| 258 |
+
self.buf.seek(and_mask_offset)
|
| 259 |
+
mask_data = self.buf.read(total_bytes)
|
| 260 |
+
|
| 261 |
+
# convert raw data to image
|
| 262 |
+
mask = Image.frombuffer(
|
| 263 |
+
"1", # 1 bpp
|
| 264 |
+
im.size, # (w, h)
|
| 265 |
+
mask_data, # source chars
|
| 266 |
+
"raw", # raw decoder
|
| 267 |
+
("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# now we have two images, im is XOR image and mask is AND image
|
| 271 |
+
|
| 272 |
+
# apply mask image as alpha channel
|
| 273 |
+
im = im.convert("RGBA")
|
| 274 |
+
im.putalpha(mask)
|
| 275 |
+
|
| 276 |
+
return im
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
##
|
| 280 |
+
# Image plugin for Windows Icon files.
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class IcoImageFile(ImageFile.ImageFile):
|
| 284 |
+
"""
|
| 285 |
+
PIL read-only image support for Microsoft Windows .ico files.
|
| 286 |
+
|
| 287 |
+
By default the largest resolution image in the file will be loaded. This
|
| 288 |
+
can be changed by altering the 'size' attribute before calling 'load'.
|
| 289 |
+
|
| 290 |
+
The info dictionary has a key 'sizes' that is a list of the sizes available
|
| 291 |
+
in the icon file.
|
| 292 |
+
|
| 293 |
+
Handles classic, XP and Vista icon formats.
|
| 294 |
+
|
| 295 |
+
When saving, PNG compression is used. Support for this was only added in
|
| 296 |
+
Windows Vista. If you are unable to view the icon in Windows, convert the
|
| 297 |
+
image to "RGBA" mode before saving.
|
| 298 |
+
|
| 299 |
+
This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
|
| 300 |
+
<casadebender@gmail.com>.
|
| 301 |
+
https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
format = "ICO"
|
| 305 |
+
format_description = "Windows Icon"
|
| 306 |
+
|
| 307 |
+
def _open(self) -> None:
|
| 308 |
+
self.ico = IcoFile(self.fp)
|
| 309 |
+
self.info["sizes"] = self.ico.sizes()
|
| 310 |
+
self.size = self.ico.entry[0]["dim"]
|
| 311 |
+
self.load()
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def size(self):
|
| 315 |
+
return self._size
|
| 316 |
+
|
| 317 |
+
@size.setter
|
| 318 |
+
def size(self, value):
|
| 319 |
+
if value not in self.info["sizes"]:
|
| 320 |
+
msg = "This is not one of the allowed sizes of this image"
|
| 321 |
+
raise ValueError(msg)
|
| 322 |
+
self._size = value
|
| 323 |
+
|
| 324 |
+
def load(self):
|
| 325 |
+
if self.im is not None and self.im.size == self.size:
|
| 326 |
+
# Already loaded
|
| 327 |
+
return Image.Image.load(self)
|
| 328 |
+
im = self.ico.getimage(self.size)
|
| 329 |
+
# if tile is PNG, it won't really be loaded yet
|
| 330 |
+
im.load()
|
| 331 |
+
self.im = im.im
|
| 332 |
+
self.pyaccess = None
|
| 333 |
+
self._mode = im.mode
|
| 334 |
+
if im.palette:
|
| 335 |
+
self.palette = im.palette
|
| 336 |
+
if im.size != self.size:
|
| 337 |
+
warnings.warn("Image was not the expected size")
|
| 338 |
+
|
| 339 |
+
index = self.ico.getentryindex(self.size)
|
| 340 |
+
sizes = list(self.info["sizes"])
|
| 341 |
+
sizes[index] = im.size
|
| 342 |
+
self.info["sizes"] = set(sizes)
|
| 343 |
+
|
| 344 |
+
self.size = im.size
|
| 345 |
+
|
| 346 |
+
def load_seek(self, pos: int) -> None:
|
| 347 |
+
# Flag the ImageFile.Parser so that it
|
| 348 |
+
# just does all the decode at the end.
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
#
|
| 353 |
+
# --------------------------------------------------------------------
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
|
| 357 |
+
Image.register_save(IcoImageFile.format, _save)
|
| 358 |
+
Image.register_extension(IcoImageFile.format, ".ico")
|
| 359 |
+
|
| 360 |
+
Image.register_mime(IcoImageFile.format, "image/x-icon")
|
valley/lib/python3.10/site-packages/PIL/ImImagePlugin.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# IFUNC IM file handling for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1995-09-01 fl Created.
|
| 9 |
+
# 1997-01-03 fl Save palette images
|
| 10 |
+
# 1997-01-08 fl Added sequence support
|
| 11 |
+
# 1997-01-23 fl Added P and RGB save support
|
| 12 |
+
# 1997-05-31 fl Read floating point images
|
| 13 |
+
# 1997-06-22 fl Save floating point images
|
| 14 |
+
# 1997-08-27 fl Read and save 1-bit images
|
| 15 |
+
# 1998-06-25 fl Added support for RGB+LUT images
|
| 16 |
+
# 1998-07-02 fl Added support for YCC images
|
| 17 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
| 18 |
+
# 1998-12-29 fl Added I;16 support
|
| 19 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
|
| 20 |
+
# 2003-09-26 fl Added LA/PA support
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 23 |
+
# Copyright (c) 1995-2001 by Fredrik Lundh.
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
from typing import IO, Any
|
| 32 |
+
|
| 33 |
+
from . import Image, ImageFile, ImagePalette
|
| 34 |
+
|
| 35 |
+
# --------------------------------------------------------------------
|
| 36 |
+
# Standard tags
|
| 37 |
+
|
| 38 |
+
COMMENT = "Comment"
|
| 39 |
+
DATE = "Date"
|
| 40 |
+
EQUIPMENT = "Digitalization equipment"
|
| 41 |
+
FRAMES = "File size (no of images)"
|
| 42 |
+
LUT = "Lut"
|
| 43 |
+
NAME = "Name"
|
| 44 |
+
SCALE = "Scale (x,y)"
|
| 45 |
+
SIZE = "Image size (x*y)"
|
| 46 |
+
MODE = "Image type"
|
| 47 |
+
|
| 48 |
+
TAGS = {
|
| 49 |
+
COMMENT: 0,
|
| 50 |
+
DATE: 0,
|
| 51 |
+
EQUIPMENT: 0,
|
| 52 |
+
FRAMES: 0,
|
| 53 |
+
LUT: 0,
|
| 54 |
+
NAME: 0,
|
| 55 |
+
SCALE: 0,
|
| 56 |
+
SIZE: 0,
|
| 57 |
+
MODE: 0,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
OPEN = {
|
| 61 |
+
# ifunc93/p3cfunc formats
|
| 62 |
+
"0 1 image": ("1", "1"),
|
| 63 |
+
"L 1 image": ("1", "1"),
|
| 64 |
+
"Greyscale image": ("L", "L"),
|
| 65 |
+
"Grayscale image": ("L", "L"),
|
| 66 |
+
"RGB image": ("RGB", "RGB;L"),
|
| 67 |
+
"RLB image": ("RGB", "RLB"),
|
| 68 |
+
"RYB image": ("RGB", "RLB"),
|
| 69 |
+
"B1 image": ("1", "1"),
|
| 70 |
+
"B2 image": ("P", "P;2"),
|
| 71 |
+
"B4 image": ("P", "P;4"),
|
| 72 |
+
"X 24 image": ("RGB", "RGB"),
|
| 73 |
+
"L 32 S image": ("I", "I;32"),
|
| 74 |
+
"L 32 F image": ("F", "F;32"),
|
| 75 |
+
# old p3cfunc formats
|
| 76 |
+
"RGB3 image": ("RGB", "RGB;T"),
|
| 77 |
+
"RYB3 image": ("RGB", "RYB;T"),
|
| 78 |
+
# extensions
|
| 79 |
+
"LA image": ("LA", "LA;L"),
|
| 80 |
+
"PA image": ("LA", "PA;L"),
|
| 81 |
+
"RGBA image": ("RGBA", "RGBA;L"),
|
| 82 |
+
"RGBX image": ("RGB", "RGBX;L"),
|
| 83 |
+
"CMYK image": ("CMYK", "CMYK;L"),
|
| 84 |
+
"YCC image": ("YCbCr", "YCbCr;L"),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
# ifunc95 extensions
|
| 88 |
+
for i in ["8", "8S", "16", "16S", "32", "32F"]:
|
| 89 |
+
OPEN[f"L {i} image"] = ("F", f"F;{i}")
|
| 90 |
+
OPEN[f"L*{i} image"] = ("F", f"F;{i}")
|
| 91 |
+
for i in ["16", "16L", "16B"]:
|
| 92 |
+
OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
|
| 93 |
+
OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
|
| 94 |
+
for i in ["32S"]:
|
| 95 |
+
OPEN[f"L {i} image"] = ("I", f"I;{i}")
|
| 96 |
+
OPEN[f"L*{i} image"] = ("I", f"I;{i}")
|
| 97 |
+
for j in range(2, 33):
|
| 98 |
+
OPEN[f"L*{j} image"] = ("F", f"F;{j}")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# --------------------------------------------------------------------
|
| 102 |
+
# Read IM directory
|
| 103 |
+
|
| 104 |
+
split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def number(s: Any) -> float:
|
| 108 |
+
try:
|
| 109 |
+
return int(s)
|
| 110 |
+
except ValueError:
|
| 111 |
+
return float(s)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
##
|
| 115 |
+
# Image plugin for the IFUNC IM file format.
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class ImImageFile(ImageFile.ImageFile):
|
| 119 |
+
format = "IM"
|
| 120 |
+
format_description = "IFUNC Image Memory"
|
| 121 |
+
_close_exclusive_fp_after_loading = False
|
| 122 |
+
|
| 123 |
+
def _open(self) -> None:
|
| 124 |
+
# Quick rejection: if there's not an LF among the first
|
| 125 |
+
# 100 bytes, this is (probably) not a text header.
|
| 126 |
+
|
| 127 |
+
if b"\n" not in self.fp.read(100):
|
| 128 |
+
msg = "not an IM file"
|
| 129 |
+
raise SyntaxError(msg)
|
| 130 |
+
self.fp.seek(0)
|
| 131 |
+
|
| 132 |
+
n = 0
|
| 133 |
+
|
| 134 |
+
# Default values
|
| 135 |
+
self.info[MODE] = "L"
|
| 136 |
+
self.info[SIZE] = (512, 512)
|
| 137 |
+
self.info[FRAMES] = 1
|
| 138 |
+
|
| 139 |
+
self.rawmode = "L"
|
| 140 |
+
|
| 141 |
+
while True:
|
| 142 |
+
s = self.fp.read(1)
|
| 143 |
+
|
| 144 |
+
# Some versions of IFUNC uses \n\r instead of \r\n...
|
| 145 |
+
if s == b"\r":
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
if not s or s == b"\0" or s == b"\x1A":
|
| 149 |
+
break
|
| 150 |
+
|
| 151 |
+
# FIXME: this may read whole file if not a text file
|
| 152 |
+
s = s + self.fp.readline()
|
| 153 |
+
|
| 154 |
+
if len(s) > 100:
|
| 155 |
+
msg = "not an IM file"
|
| 156 |
+
raise SyntaxError(msg)
|
| 157 |
+
|
| 158 |
+
if s[-2:] == b"\r\n":
|
| 159 |
+
s = s[:-2]
|
| 160 |
+
elif s[-1:] == b"\n":
|
| 161 |
+
s = s[:-1]
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
m = split.match(s)
|
| 165 |
+
except re.error as e:
|
| 166 |
+
msg = "not an IM file"
|
| 167 |
+
raise SyntaxError(msg) from e
|
| 168 |
+
|
| 169 |
+
if m:
|
| 170 |
+
k, v = m.group(1, 2)
|
| 171 |
+
|
| 172 |
+
# Don't know if this is the correct encoding,
|
| 173 |
+
# but a decent guess (I guess)
|
| 174 |
+
k = k.decode("latin-1", "replace")
|
| 175 |
+
v = v.decode("latin-1", "replace")
|
| 176 |
+
|
| 177 |
+
# Convert value as appropriate
|
| 178 |
+
if k in [FRAMES, SCALE, SIZE]:
|
| 179 |
+
v = v.replace("*", ",")
|
| 180 |
+
v = tuple(map(number, v.split(",")))
|
| 181 |
+
if len(v) == 1:
|
| 182 |
+
v = v[0]
|
| 183 |
+
elif k == MODE and v in OPEN:
|
| 184 |
+
v, self.rawmode = OPEN[v]
|
| 185 |
+
|
| 186 |
+
# Add to dictionary. Note that COMMENT tags are
|
| 187 |
+
# combined into a list of strings.
|
| 188 |
+
if k == COMMENT:
|
| 189 |
+
if k in self.info:
|
| 190 |
+
self.info[k].append(v)
|
| 191 |
+
else:
|
| 192 |
+
self.info[k] = [v]
|
| 193 |
+
else:
|
| 194 |
+
self.info[k] = v
|
| 195 |
+
|
| 196 |
+
if k in TAGS:
|
| 197 |
+
n += 1
|
| 198 |
+
|
| 199 |
+
else:
|
| 200 |
+
msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
|
| 201 |
+
raise SyntaxError(msg)
|
| 202 |
+
|
| 203 |
+
if not n:
|
| 204 |
+
msg = "Not an IM file"
|
| 205 |
+
raise SyntaxError(msg)
|
| 206 |
+
|
| 207 |
+
# Basic attributes
|
| 208 |
+
self._size = self.info[SIZE]
|
| 209 |
+
self._mode = self.info[MODE]
|
| 210 |
+
|
| 211 |
+
# Skip forward to start of image data
|
| 212 |
+
while s and s[:1] != b"\x1A":
|
| 213 |
+
s = self.fp.read(1)
|
| 214 |
+
if not s:
|
| 215 |
+
msg = "File truncated"
|
| 216 |
+
raise SyntaxError(msg)
|
| 217 |
+
|
| 218 |
+
if LUT in self.info:
|
| 219 |
+
# convert lookup table to palette or lut attribute
|
| 220 |
+
palette = self.fp.read(768)
|
| 221 |
+
greyscale = 1 # greyscale palette
|
| 222 |
+
linear = 1 # linear greyscale palette
|
| 223 |
+
for i in range(256):
|
| 224 |
+
if palette[i] == palette[i + 256] == palette[i + 512]:
|
| 225 |
+
if palette[i] != i:
|
| 226 |
+
linear = 0
|
| 227 |
+
else:
|
| 228 |
+
greyscale = 0
|
| 229 |
+
if self.mode in ["L", "LA", "P", "PA"]:
|
| 230 |
+
if greyscale:
|
| 231 |
+
if not linear:
|
| 232 |
+
self.lut = list(palette[:256])
|
| 233 |
+
else:
|
| 234 |
+
if self.mode in ["L", "P"]:
|
| 235 |
+
self._mode = self.rawmode = "P"
|
| 236 |
+
elif self.mode in ["LA", "PA"]:
|
| 237 |
+
self._mode = "PA"
|
| 238 |
+
self.rawmode = "PA;L"
|
| 239 |
+
self.palette = ImagePalette.raw("RGB;L", palette)
|
| 240 |
+
elif self.mode == "RGB":
|
| 241 |
+
if not greyscale or not linear:
|
| 242 |
+
self.lut = list(palette)
|
| 243 |
+
|
| 244 |
+
self.frame = 0
|
| 245 |
+
|
| 246 |
+
self.__offset = offs = self.fp.tell()
|
| 247 |
+
|
| 248 |
+
self._fp = self.fp # FIXME: hack
|
| 249 |
+
|
| 250 |
+
if self.rawmode[:2] == "F;":
|
| 251 |
+
# ifunc95 formats
|
| 252 |
+
try:
|
| 253 |
+
# use bit decoder (if necessary)
|
| 254 |
+
bits = int(self.rawmode[2:])
|
| 255 |
+
if bits not in [8, 16, 32]:
|
| 256 |
+
self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
|
| 257 |
+
return
|
| 258 |
+
except ValueError:
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
if self.rawmode in ["RGB;T", "RYB;T"]:
|
| 262 |
+
# Old LabEye/3PC files. Would be very surprised if anyone
|
| 263 |
+
# ever stumbled upon such a file ;-)
|
| 264 |
+
size = self.size[0] * self.size[1]
|
| 265 |
+
self.tile = [
|
| 266 |
+
("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
|
| 267 |
+
("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
|
| 268 |
+
("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
|
| 269 |
+
]
|
| 270 |
+
else:
|
| 271 |
+
# LabEye/IFUNC files
|
| 272 |
+
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
| 273 |
+
|
| 274 |
+
@property
|
| 275 |
+
def n_frames(self) -> int:
|
| 276 |
+
return self.info[FRAMES]
|
| 277 |
+
|
| 278 |
+
@property
|
| 279 |
+
def is_animated(self) -> bool:
|
| 280 |
+
return self.info[FRAMES] > 1
|
| 281 |
+
|
| 282 |
+
def seek(self, frame: int) -> None:
|
| 283 |
+
if not self._seek_check(frame):
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
self.frame = frame
|
| 287 |
+
|
| 288 |
+
if self.mode == "1":
|
| 289 |
+
bits = 1
|
| 290 |
+
else:
|
| 291 |
+
bits = 8 * len(self.mode)
|
| 292 |
+
|
| 293 |
+
size = ((self.size[0] * bits + 7) // 8) * self.size[1]
|
| 294 |
+
offs = self.__offset + frame * size
|
| 295 |
+
|
| 296 |
+
self.fp = self._fp
|
| 297 |
+
|
| 298 |
+
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
|
| 299 |
+
|
| 300 |
+
def tell(self) -> int:
|
| 301 |
+
return self.frame
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
#
|
| 305 |
+
# --------------------------------------------------------------------
|
| 306 |
+
# Save IM files
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
SAVE = {
|
| 310 |
+
# mode: (im type, raw mode)
|
| 311 |
+
"1": ("0 1", "1"),
|
| 312 |
+
"L": ("Greyscale", "L"),
|
| 313 |
+
"LA": ("LA", "LA;L"),
|
| 314 |
+
"P": ("Greyscale", "P"),
|
| 315 |
+
"PA": ("LA", "PA;L"),
|
| 316 |
+
"I": ("L 32S", "I;32S"),
|
| 317 |
+
"I;16": ("L 16", "I;16"),
|
| 318 |
+
"I;16L": ("L 16L", "I;16L"),
|
| 319 |
+
"I;16B": ("L 16B", "I;16B"),
|
| 320 |
+
"F": ("L 32F", "F;32F"),
|
| 321 |
+
"RGB": ("RGB", "RGB;L"),
|
| 322 |
+
"RGBA": ("RGBA", "RGBA;L"),
|
| 323 |
+
"RGBX": ("RGBX", "RGBX;L"),
|
| 324 |
+
"CMYK": ("CMYK", "CMYK;L"),
|
| 325 |
+
"YCbCr": ("YCC", "YCbCr;L"),
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 330 |
+
try:
|
| 331 |
+
image_type, rawmode = SAVE[im.mode]
|
| 332 |
+
except KeyError as e:
|
| 333 |
+
msg = f"Cannot save {im.mode} images as IM"
|
| 334 |
+
raise ValueError(msg) from e
|
| 335 |
+
|
| 336 |
+
frames = im.encoderinfo.get("frames", 1)
|
| 337 |
+
|
| 338 |
+
fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
|
| 339 |
+
if filename:
|
| 340 |
+
# Each line must be 100 characters or less,
|
| 341 |
+
# or: SyntaxError("not an IM file")
|
| 342 |
+
# 8 characters are used for "Name: " and "\r\n"
|
| 343 |
+
# Keep just the filename, ditch the potentially overlong path
|
| 344 |
+
if isinstance(filename, bytes):
|
| 345 |
+
filename = filename.decode("ascii")
|
| 346 |
+
name, ext = os.path.splitext(os.path.basename(filename))
|
| 347 |
+
name = "".join([name[: 92 - len(ext)], ext])
|
| 348 |
+
|
| 349 |
+
fp.write(f"Name: {name}\r\n".encode("ascii"))
|
| 350 |
+
fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
|
| 351 |
+
fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
|
| 352 |
+
if im.mode in ["P", "PA"]:
|
| 353 |
+
fp.write(b"Lut: 1\r\n")
|
| 354 |
+
fp.write(b"\000" * (511 - fp.tell()) + b"\032")
|
| 355 |
+
if im.mode in ["P", "PA"]:
|
| 356 |
+
im_palette = im.im.getpalette("RGB", "RGB;L")
|
| 357 |
+
colors = len(im_palette) // 3
|
| 358 |
+
palette = b""
|
| 359 |
+
for i in range(3):
|
| 360 |
+
palette += im_palette[colors * i : colors * (i + 1)]
|
| 361 |
+
palette += b"\x00" * (256 - colors)
|
| 362 |
+
fp.write(palette) # 768 bytes
|
| 363 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
#
|
| 367 |
+
# --------------------------------------------------------------------
|
| 368 |
+
# Registry
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
Image.register_open(ImImageFile.format, ImImageFile)
|
| 372 |
+
Image.register_save(ImImageFile.format, _save)
|
| 373 |
+
|
| 374 |
+
Image.register_extension(ImImageFile.format, ".im")
|
valley/lib/python3.10/site-packages/PIL/ImageCms.py
ADDED
|
@@ -0,0 +1,1127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The Python Imaging Library.
|
| 2 |
+
# $Id$
|
| 3 |
+
|
| 4 |
+
# Optional color management support, based on Kevin Cazabon's PyCMS
|
| 5 |
+
# library.
|
| 6 |
+
|
| 7 |
+
# Originally released under LGPL. Graciously donated to PIL in
|
| 8 |
+
# March 2009, for distribution under the standard PIL license
|
| 9 |
+
|
| 10 |
+
# History:
|
| 11 |
+
|
| 12 |
+
# 2009-03-08 fl Added to PIL.
|
| 13 |
+
|
| 14 |
+
# Copyright (C) 2002-2003 Kevin Cazabon
|
| 15 |
+
# Copyright (c) 2009 by Fredrik Lundh
|
| 16 |
+
# Copyright (c) 2013 by Eric Soroos
|
| 17 |
+
|
| 18 |
+
# See the README file for information on usage and redistribution. See
|
| 19 |
+
# below for the original description.
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import operator
|
| 23 |
+
import sys
|
| 24 |
+
from enum import IntEnum, IntFlag
|
| 25 |
+
from functools import reduce
|
| 26 |
+
from typing import Any, Literal, SupportsFloat, SupportsInt, Union
|
| 27 |
+
|
| 28 |
+
from . import Image, __version__
|
| 29 |
+
from ._deprecate import deprecate
|
| 30 |
+
from ._typing import SupportsRead
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
from . import _imagingcms as core
|
| 34 |
+
except ImportError as ex:
|
| 35 |
+
# Allow error import for doc purposes, but error out when accessing
|
| 36 |
+
# anything in core.
|
| 37 |
+
from ._util import DeferredError
|
| 38 |
+
|
| 39 |
+
core = DeferredError.new(ex)
|
| 40 |
+
|
| 41 |
+
_DESCRIPTION = """
|
| 42 |
+
pyCMS
|
| 43 |
+
|
| 44 |
+
a Python / PIL interface to the littleCMS ICC Color Management System
|
| 45 |
+
Copyright (C) 2002-2003 Kevin Cazabon
|
| 46 |
+
kevin@cazabon.com
|
| 47 |
+
https://www.cazabon.com
|
| 48 |
+
|
| 49 |
+
pyCMS home page: https://www.cazabon.com/pyCMS
|
| 50 |
+
littleCMS home page: https://www.littlecms.com
|
| 51 |
+
(littleCMS is Copyright (C) 1998-2001 Marti Maria)
|
| 52 |
+
|
| 53 |
+
Originally released under LGPL. Graciously donated to PIL in
|
| 54 |
+
March 2009, for distribution under the standard PIL license
|
| 55 |
+
|
| 56 |
+
The pyCMS.py module provides a "clean" interface between Python/PIL and
|
| 57 |
+
pyCMSdll, taking care of some of the more complex handling of the direct
|
| 58 |
+
pyCMSdll functions, as well as error-checking and making sure that all
|
| 59 |
+
relevant data is kept together.
|
| 60 |
+
|
| 61 |
+
While it is possible to call pyCMSdll functions directly, it's not highly
|
| 62 |
+
recommended.
|
| 63 |
+
|
| 64 |
+
Version History:
|
| 65 |
+
|
| 66 |
+
1.0.0 pil Oct 2013 Port to LCMS 2.
|
| 67 |
+
|
| 68 |
+
0.1.0 pil mod March 10, 2009
|
| 69 |
+
|
| 70 |
+
Renamed display profile to proof profile. The proof
|
| 71 |
+
profile is the profile of the device that is being
|
| 72 |
+
simulated, not the profile of the device which is
|
| 73 |
+
actually used to display/print the final simulation
|
| 74 |
+
(that'd be the output profile) - also see LCMSAPI.txt
|
| 75 |
+
input colorspace -> using 'renderingIntent' -> proof
|
| 76 |
+
colorspace -> using 'proofRenderingIntent' -> output
|
| 77 |
+
colorspace
|
| 78 |
+
|
| 79 |
+
Added LCMS FLAGS support.
|
| 80 |
+
Added FLAGS["SOFTPROOFING"] as default flag for
|
| 81 |
+
buildProofTransform (otherwise the proof profile/intent
|
| 82 |
+
would be ignored).
|
| 83 |
+
|
| 84 |
+
0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
|
| 85 |
+
|
| 86 |
+
0.0.2 alpha Jan 6, 2002
|
| 87 |
+
|
| 88 |
+
Added try/except statements around type() checks of
|
| 89 |
+
potential CObjects... Python won't let you use type()
|
| 90 |
+
on them, and raises a TypeError (stupid, if you ask
|
| 91 |
+
me!)
|
| 92 |
+
|
| 93 |
+
Added buildProofTransformFromOpenProfiles() function.
|
| 94 |
+
Additional fixes in DLL, see DLL code for details.
|
| 95 |
+
|
| 96 |
+
0.0.1 alpha first public release, Dec. 26, 2002
|
| 97 |
+
|
| 98 |
+
Known to-do list with current version (of Python interface, not pyCMSdll):
|
| 99 |
+
|
| 100 |
+
none
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
_VERSION = "1.0.0 pil"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def __getattr__(name: str) -> Any:
|
| 108 |
+
if name == "DESCRIPTION":
|
| 109 |
+
deprecate("PIL.ImageCms.DESCRIPTION", 12)
|
| 110 |
+
return _DESCRIPTION
|
| 111 |
+
elif name == "VERSION":
|
| 112 |
+
deprecate("PIL.ImageCms.VERSION", 12)
|
| 113 |
+
return _VERSION
|
| 114 |
+
elif name == "FLAGS":
|
| 115 |
+
deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
|
| 116 |
+
return _FLAGS
|
| 117 |
+
msg = f"module '{__name__}' has no attribute '{name}'"
|
| 118 |
+
raise AttributeError(msg)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# --------------------------------------------------------------------.
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
#
|
| 125 |
+
# intent/direction values
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Intent(IntEnum):
|
| 129 |
+
PERCEPTUAL = 0
|
| 130 |
+
RELATIVE_COLORIMETRIC = 1
|
| 131 |
+
SATURATION = 2
|
| 132 |
+
ABSOLUTE_COLORIMETRIC = 3
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class Direction(IntEnum):
|
| 136 |
+
INPUT = 0
|
| 137 |
+
OUTPUT = 1
|
| 138 |
+
PROOF = 2
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
#
|
| 142 |
+
# flags
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Flags(IntFlag):
|
| 146 |
+
"""Flags and documentation are taken from ``lcms2.h``."""
|
| 147 |
+
|
| 148 |
+
NONE = 0
|
| 149 |
+
NOCACHE = 0x0040
|
| 150 |
+
"""Inhibit 1-pixel cache"""
|
| 151 |
+
NOOPTIMIZE = 0x0100
|
| 152 |
+
"""Inhibit optimizations"""
|
| 153 |
+
NULLTRANSFORM = 0x0200
|
| 154 |
+
"""Don't transform anyway"""
|
| 155 |
+
GAMUTCHECK = 0x1000
|
| 156 |
+
"""Out of Gamut alarm"""
|
| 157 |
+
SOFTPROOFING = 0x4000
|
| 158 |
+
"""Do softproofing"""
|
| 159 |
+
BLACKPOINTCOMPENSATION = 0x2000
|
| 160 |
+
NOWHITEONWHITEFIXUP = 0x0004
|
| 161 |
+
"""Don't fix scum dot"""
|
| 162 |
+
HIGHRESPRECALC = 0x0400
|
| 163 |
+
"""Use more memory to give better accuracy"""
|
| 164 |
+
LOWRESPRECALC = 0x0800
|
| 165 |
+
"""Use less memory to minimize resources"""
|
| 166 |
+
# this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
|
| 167 |
+
USE_8BITS_DEVICELINK = 0x0008
|
| 168 |
+
"""Create 8 bits devicelinks"""
|
| 169 |
+
GUESSDEVICECLASS = 0x0020
|
| 170 |
+
"""Guess device class (for ``transform2devicelink``)"""
|
| 171 |
+
KEEP_SEQUENCE = 0x0080
|
| 172 |
+
"""Keep profile sequence for devicelink creation"""
|
| 173 |
+
FORCE_CLUT = 0x0002
|
| 174 |
+
"""Force CLUT optimization"""
|
| 175 |
+
CLUT_POST_LINEARIZATION = 0x0001
|
| 176 |
+
"""create postlinearization tables if possible"""
|
| 177 |
+
CLUT_PRE_LINEARIZATION = 0x0010
|
| 178 |
+
"""create prelinearization tables if possible"""
|
| 179 |
+
NONEGATIVES = 0x8000
|
| 180 |
+
"""Prevent negative numbers in floating point transforms"""
|
| 181 |
+
COPY_ALPHA = 0x04000000
|
| 182 |
+
"""Alpha channels are copied on ``cmsDoTransform()``"""
|
| 183 |
+
NODEFAULTRESOURCEDEF = 0x01000000
|
| 184 |
+
|
| 185 |
+
_GRIDPOINTS_1 = 1 << 16
|
| 186 |
+
_GRIDPOINTS_2 = 2 << 16
|
| 187 |
+
_GRIDPOINTS_4 = 4 << 16
|
| 188 |
+
_GRIDPOINTS_8 = 8 << 16
|
| 189 |
+
_GRIDPOINTS_16 = 16 << 16
|
| 190 |
+
_GRIDPOINTS_32 = 32 << 16
|
| 191 |
+
_GRIDPOINTS_64 = 64 << 16
|
| 192 |
+
_GRIDPOINTS_128 = 128 << 16
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def GRIDPOINTS(n: int) -> Flags:
|
| 196 |
+
"""
|
| 197 |
+
Fine-tune control over number of gridpoints
|
| 198 |
+
|
| 199 |
+
:param n: :py:class:`int` in range ``0 <= n <= 255``
|
| 200 |
+
"""
|
| 201 |
+
return Flags.NONE | ((n & 0xFF) << 16)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
_MAX_FLAG = reduce(operator.or_, Flags)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
_FLAGS = {
|
| 208 |
+
"MATRIXINPUT": 1,
|
| 209 |
+
"MATRIXOUTPUT": 2,
|
| 210 |
+
"MATRIXONLY": (1 | 2),
|
| 211 |
+
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
|
| 212 |
+
# Don't create prelinearization tables on precalculated transforms
|
| 213 |
+
# (internal use):
|
| 214 |
+
"NOPRELINEARIZATION": 16,
|
| 215 |
+
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
|
| 216 |
+
"NOTCACHE": 64, # Inhibit 1-pixel cache
|
| 217 |
+
"NOTPRECALC": 256,
|
| 218 |
+
"NULLTRANSFORM": 512, # Don't transform anyway
|
| 219 |
+
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
|
| 220 |
+
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
|
| 221 |
+
"WHITEBLACKCOMPENSATION": 8192,
|
| 222 |
+
"BLACKPOINTCOMPENSATION": 8192,
|
| 223 |
+
"GAMUTCHECK": 4096, # Out of Gamut alarm
|
| 224 |
+
"SOFTPROOFING": 16384, # Do softproofing
|
| 225 |
+
"PRESERVEBLACK": 32768, # Black preservation
|
| 226 |
+
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
|
| 227 |
+
"GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# --------------------------------------------------------------------.
|
| 232 |
+
# Experimental PIL-level API
|
| 233 |
+
# --------------------------------------------------------------------.
|
| 234 |
+
|
| 235 |
+
##
|
| 236 |
+
# Profile.
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class ImageCmsProfile:
|
| 240 |
+
def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
|
| 241 |
+
"""
|
| 242 |
+
:param profile: Either a string representing a filename,
|
| 243 |
+
a file like object containing a profile or a
|
| 244 |
+
low-level profile object
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
if isinstance(profile, str):
|
| 249 |
+
if sys.platform == "win32":
|
| 250 |
+
profile_bytes_path = profile.encode()
|
| 251 |
+
try:
|
| 252 |
+
profile_bytes_path.decode("ascii")
|
| 253 |
+
except UnicodeDecodeError:
|
| 254 |
+
with open(profile, "rb") as f:
|
| 255 |
+
self._set(core.profile_frombytes(f.read()))
|
| 256 |
+
return
|
| 257 |
+
self._set(core.profile_open(profile), profile)
|
| 258 |
+
elif hasattr(profile, "read"):
|
| 259 |
+
self._set(core.profile_frombytes(profile.read()))
|
| 260 |
+
elif isinstance(profile, core.CmsProfile):
|
| 261 |
+
self._set(profile)
|
| 262 |
+
else:
|
| 263 |
+
msg = "Invalid type for Profile" # type: ignore[unreachable]
|
| 264 |
+
raise TypeError(msg)
|
| 265 |
+
|
| 266 |
+
def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
|
| 267 |
+
self.profile = profile
|
| 268 |
+
self.filename = filename
|
| 269 |
+
self.product_name = None # profile.product_name
|
| 270 |
+
self.product_info = None # profile.product_info
|
| 271 |
+
|
| 272 |
+
def tobytes(self) -> bytes:
|
| 273 |
+
"""
|
| 274 |
+
Returns the profile in a format suitable for embedding in
|
| 275 |
+
saved images.
|
| 276 |
+
|
| 277 |
+
:returns: a bytes object containing the ICC profile.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
return core.profile_tobytes(self.profile)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class ImageCmsTransform(Image.ImagePointHandler):
|
| 284 |
+
"""
|
| 285 |
+
Transform. This can be used with the procedural API, or with the standard
|
| 286 |
+
:py:func:`~PIL.Image.Image.point` method.
|
| 287 |
+
|
| 288 |
+
Will return the output profile in the ``output.info['icc_profile']``.
|
| 289 |
+
"""
|
| 290 |
+
|
| 291 |
+
def __init__(
|
| 292 |
+
self,
|
| 293 |
+
input: ImageCmsProfile,
|
| 294 |
+
output: ImageCmsProfile,
|
| 295 |
+
input_mode: str,
|
| 296 |
+
output_mode: str,
|
| 297 |
+
intent: Intent = Intent.PERCEPTUAL,
|
| 298 |
+
proof: ImageCmsProfile | None = None,
|
| 299 |
+
proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 300 |
+
flags: Flags = Flags.NONE,
|
| 301 |
+
):
|
| 302 |
+
supported_modes = (
|
| 303 |
+
"RGB",
|
| 304 |
+
"RGBA",
|
| 305 |
+
"RGBX",
|
| 306 |
+
"CMYK",
|
| 307 |
+
"I;16",
|
| 308 |
+
"I;16L",
|
| 309 |
+
"I;16B",
|
| 310 |
+
"YCbCr",
|
| 311 |
+
"LAB",
|
| 312 |
+
"L",
|
| 313 |
+
"1",
|
| 314 |
+
)
|
| 315 |
+
for mode in (input_mode, output_mode):
|
| 316 |
+
if mode not in supported_modes:
|
| 317 |
+
deprecate(
|
| 318 |
+
mode,
|
| 319 |
+
12,
|
| 320 |
+
{
|
| 321 |
+
"L;16": "I;16 or I;16L",
|
| 322 |
+
"L:16B": "I;16B",
|
| 323 |
+
"YCCA": "YCbCr",
|
| 324 |
+
"YCC": "YCbCr",
|
| 325 |
+
}.get(mode),
|
| 326 |
+
)
|
| 327 |
+
if proof is None:
|
| 328 |
+
self.transform = core.buildTransform(
|
| 329 |
+
input.profile, output.profile, input_mode, output_mode, intent, flags
|
| 330 |
+
)
|
| 331 |
+
else:
|
| 332 |
+
self.transform = core.buildProofTransform(
|
| 333 |
+
input.profile,
|
| 334 |
+
output.profile,
|
| 335 |
+
proof.profile,
|
| 336 |
+
input_mode,
|
| 337 |
+
output_mode,
|
| 338 |
+
intent,
|
| 339 |
+
proof_intent,
|
| 340 |
+
flags,
|
| 341 |
+
)
|
| 342 |
+
# Note: inputMode and outputMode are for pyCMS compatibility only
|
| 343 |
+
self.input_mode = self.inputMode = input_mode
|
| 344 |
+
self.output_mode = self.outputMode = output_mode
|
| 345 |
+
|
| 346 |
+
self.output_profile = output
|
| 347 |
+
|
| 348 |
+
def point(self, im: Image.Image) -> Image.Image:
|
| 349 |
+
return self.apply(im)
|
| 350 |
+
|
| 351 |
+
def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
|
| 352 |
+
im.load()
|
| 353 |
+
if imOut is None:
|
| 354 |
+
imOut = Image.new(self.output_mode, im.size, None)
|
| 355 |
+
self.transform.apply(im.im.id, imOut.im.id)
|
| 356 |
+
imOut.info["icc_profile"] = self.output_profile.tobytes()
|
| 357 |
+
return imOut
|
| 358 |
+
|
| 359 |
+
def apply_in_place(self, im: Image.Image) -> Image.Image:
|
| 360 |
+
im.load()
|
| 361 |
+
if im.mode != self.output_mode:
|
| 362 |
+
msg = "mode mismatch"
|
| 363 |
+
raise ValueError(msg) # wrong output mode
|
| 364 |
+
self.transform.apply(im.im.id, im.im.id)
|
| 365 |
+
im.info["icc_profile"] = self.output_profile.tobytes()
|
| 366 |
+
return im
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
|
| 370 |
+
"""
|
| 371 |
+
(experimental) Fetches the profile for the current display device.
|
| 372 |
+
|
| 373 |
+
:returns: ``None`` if the profile is not known.
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
if sys.platform != "win32":
|
| 377 |
+
return None
|
| 378 |
+
|
| 379 |
+
from . import ImageWin # type: ignore[unused-ignore, unreachable]
|
| 380 |
+
|
| 381 |
+
if isinstance(handle, ImageWin.HDC):
|
| 382 |
+
profile = core.get_display_profile_win32(int(handle), 1)
|
| 383 |
+
else:
|
| 384 |
+
profile = core.get_display_profile_win32(int(handle or 0))
|
| 385 |
+
if profile is None:
|
| 386 |
+
return None
|
| 387 |
+
return ImageCmsProfile(profile)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
# --------------------------------------------------------------------.
|
| 391 |
+
# pyCMS compatible layer
|
| 392 |
+
# --------------------------------------------------------------------.
|
| 393 |
+
|
| 394 |
+
_CmsProfileCompatible = Union[
|
| 395 |
+
str, SupportsRead[bytes], core.CmsProfile, ImageCmsProfile
|
| 396 |
+
]
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class PyCMSError(Exception):
|
| 400 |
+
"""(pyCMS) Exception class.
|
| 401 |
+
This is used for all errors in the pyCMS API."""
|
| 402 |
+
|
| 403 |
+
pass
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def profileToProfile(
|
| 407 |
+
im: Image.Image,
|
| 408 |
+
inputProfile: _CmsProfileCompatible,
|
| 409 |
+
outputProfile: _CmsProfileCompatible,
|
| 410 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 411 |
+
outputMode: str | None = None,
|
| 412 |
+
inPlace: bool = False,
|
| 413 |
+
flags: Flags = Flags.NONE,
|
| 414 |
+
) -> Image.Image | None:
|
| 415 |
+
"""
|
| 416 |
+
(pyCMS) Applies an ICC transformation to a given image, mapping from
|
| 417 |
+
``inputProfile`` to ``outputProfile``.
|
| 418 |
+
|
| 419 |
+
If the input or output profiles specified are not valid filenames, a
|
| 420 |
+
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
|
| 421 |
+
``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
|
| 422 |
+
If an error occurs during application of the profiles,
|
| 423 |
+
a :exc:`PyCMSError` will be raised.
|
| 424 |
+
If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
|
| 425 |
+
a :exc:`PyCMSError` will be raised.
|
| 426 |
+
|
| 427 |
+
This function applies an ICC transformation to im from ``inputProfile``'s
|
| 428 |
+
color space to ``outputProfile``'s color space using the specified rendering
|
| 429 |
+
intent to decide how to handle out-of-gamut colors.
|
| 430 |
+
|
| 431 |
+
``outputMode`` can be used to specify that a color mode conversion is to
|
| 432 |
+
be done using these profiles, but the specified profiles must be able
|
| 433 |
+
to handle that mode. I.e., if converting im from RGB to CMYK using
|
| 434 |
+
profiles, the input profile must handle RGB data, and the output
|
| 435 |
+
profile must handle CMYK data.
|
| 436 |
+
|
| 437 |
+
:param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
|
| 438 |
+
or Image.open(...), etc.)
|
| 439 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 440 |
+
profile you wish to use for this image, or a profile object
|
| 441 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 442 |
+
profile you wish to use for this image, or a profile object
|
| 443 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 444 |
+
wish to use for the transform
|
| 445 |
+
|
| 446 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 447 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 448 |
+
ImageCms.Intent.SATURATION = 2
|
| 449 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 450 |
+
|
| 451 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 452 |
+
they do.
|
| 453 |
+
:param outputMode: A valid PIL mode for the output image (i.e. "RGB",
|
| 454 |
+
"CMYK", etc.). Note: if rendering the image "inPlace", outputMode
|
| 455 |
+
MUST be the same mode as the input, or omitted completely. If
|
| 456 |
+
omitted, the outputMode will be the same as the mode of the input
|
| 457 |
+
image (im.mode)
|
| 458 |
+
:param inPlace: Boolean. If ``True``, the original image is modified in-place,
|
| 459 |
+
and ``None`` is returned. If ``False`` (default), a new
|
| 460 |
+
:py:class:`~PIL.Image.Image` object is returned with the transform applied.
|
| 461 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 462 |
+
:returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
|
| 463 |
+
the value of ``inPlace``
|
| 464 |
+
:exception PyCMSError:
|
| 465 |
+
"""
|
| 466 |
+
|
| 467 |
+
if outputMode is None:
|
| 468 |
+
outputMode = im.mode
|
| 469 |
+
|
| 470 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 471 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 472 |
+
raise PyCMSError(msg)
|
| 473 |
+
|
| 474 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 475 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 476 |
+
raise PyCMSError(msg)
|
| 477 |
+
|
| 478 |
+
try:
|
| 479 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 480 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 481 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 482 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 483 |
+
transform = ImageCmsTransform(
|
| 484 |
+
inputProfile,
|
| 485 |
+
outputProfile,
|
| 486 |
+
im.mode,
|
| 487 |
+
outputMode,
|
| 488 |
+
renderingIntent,
|
| 489 |
+
flags=flags,
|
| 490 |
+
)
|
| 491 |
+
if inPlace:
|
| 492 |
+
transform.apply_in_place(im)
|
| 493 |
+
imOut = None
|
| 494 |
+
else:
|
| 495 |
+
imOut = transform.apply(im)
|
| 496 |
+
except (OSError, TypeError, ValueError) as v:
|
| 497 |
+
raise PyCMSError(v) from v
|
| 498 |
+
|
| 499 |
+
return imOut
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def getOpenProfile(
|
| 503 |
+
profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
|
| 504 |
+
) -> ImageCmsProfile:
|
| 505 |
+
"""
|
| 506 |
+
(pyCMS) Opens an ICC profile file.
|
| 507 |
+
|
| 508 |
+
The PyCMSProfile object can be passed back into pyCMS for use in creating
|
| 509 |
+
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
|
| 510 |
+
|
| 511 |
+
If ``profileFilename`` is not a valid filename for an ICC profile,
|
| 512 |
+
a :exc:`PyCMSError` will be raised.
|
| 513 |
+
|
| 514 |
+
:param profileFilename: String, as a valid filename path to the ICC profile
|
| 515 |
+
you wish to open, or a file-like object.
|
| 516 |
+
:returns: A CmsProfile class object.
|
| 517 |
+
:exception PyCMSError:
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
try:
|
| 521 |
+
return ImageCmsProfile(profileFilename)
|
| 522 |
+
except (OSError, TypeError, ValueError) as v:
|
| 523 |
+
raise PyCMSError(v) from v
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def buildTransform(
|
| 527 |
+
inputProfile: _CmsProfileCompatible,
|
| 528 |
+
outputProfile: _CmsProfileCompatible,
|
| 529 |
+
inMode: str,
|
| 530 |
+
outMode: str,
|
| 531 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 532 |
+
flags: Flags = Flags.NONE,
|
| 533 |
+
) -> ImageCmsTransform:
|
| 534 |
+
"""
|
| 535 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 536 |
+
``outputProfile``. Use applyTransform to apply the transform to a given
|
| 537 |
+
image.
|
| 538 |
+
|
| 539 |
+
If the input or output profiles specified are not valid filenames, a
|
| 540 |
+
:exc:`PyCMSError` will be raised. If an error occurs during creation
|
| 541 |
+
of the transform, a :exc:`PyCMSError` will be raised.
|
| 542 |
+
|
| 543 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 544 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 545 |
+
|
| 546 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 547 |
+
to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
|
| 548 |
+
with out-of-gamut colors. It will ONLY work for converting images that
|
| 549 |
+
are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
|
| 550 |
+
i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 551 |
+
|
| 552 |
+
Building the transform is a fair part of the overhead in
|
| 553 |
+
ImageCms.profileToProfile(), so if you're planning on converting multiple
|
| 554 |
+
images using the same input/output settings, this can save you time.
|
| 555 |
+
Once you have a transform object, it can be used with
|
| 556 |
+
ImageCms.applyProfile() to convert images without the need to re-compute
|
| 557 |
+
the lookup table for the transform.
|
| 558 |
+
|
| 559 |
+
The reason pyCMS returns a class object rather than a handle directly
|
| 560 |
+
to the transform is that it needs to keep track of the PIL input/output
|
| 561 |
+
modes that the transform is meant for. These attributes are stored in
|
| 562 |
+
the ``inMode`` and ``outMode`` attributes of the object (which can be
|
| 563 |
+
manually overridden if you really want to, but I don't know of any
|
| 564 |
+
time that would be of use, or would even work).
|
| 565 |
+
|
| 566 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 567 |
+
profile you wish to use for this transform, or a profile object
|
| 568 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 569 |
+
profile you wish to use for this transform, or a profile object
|
| 570 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 571 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 572 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 573 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 574 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 575 |
+
wish to use for the transform
|
| 576 |
+
|
| 577 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 578 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 579 |
+
ImageCms.Intent.SATURATION = 2
|
| 580 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 581 |
+
|
| 582 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 583 |
+
they do.
|
| 584 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 585 |
+
:returns: A CmsTransform class object.
|
| 586 |
+
:exception PyCMSError:
|
| 587 |
+
"""
|
| 588 |
+
|
| 589 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 590 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 591 |
+
raise PyCMSError(msg)
|
| 592 |
+
|
| 593 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 594 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 595 |
+
raise PyCMSError(msg)
|
| 596 |
+
|
| 597 |
+
try:
|
| 598 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 599 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 600 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 601 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 602 |
+
return ImageCmsTransform(
|
| 603 |
+
inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
|
| 604 |
+
)
|
| 605 |
+
except (OSError, TypeError, ValueError) as v:
|
| 606 |
+
raise PyCMSError(v) from v
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def buildProofTransform(
|
| 610 |
+
inputProfile: _CmsProfileCompatible,
|
| 611 |
+
outputProfile: _CmsProfileCompatible,
|
| 612 |
+
proofProfile: _CmsProfileCompatible,
|
| 613 |
+
inMode: str,
|
| 614 |
+
outMode: str,
|
| 615 |
+
renderingIntent: Intent = Intent.PERCEPTUAL,
|
| 616 |
+
proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
|
| 617 |
+
flags: Flags = Flags.SOFTPROOFING,
|
| 618 |
+
) -> ImageCmsTransform:
|
| 619 |
+
"""
|
| 620 |
+
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
|
| 621 |
+
``outputProfile``, but tries to simulate the result that would be
|
| 622 |
+
obtained on the ``proofProfile`` device.
|
| 623 |
+
|
| 624 |
+
If the input, output, or proof profiles specified are not valid
|
| 625 |
+
filenames, a :exc:`PyCMSError` will be raised.
|
| 626 |
+
|
| 627 |
+
If an error occurs during creation of the transform,
|
| 628 |
+
a :exc:`PyCMSError` will be raised.
|
| 629 |
+
|
| 630 |
+
If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
|
| 631 |
+
(or by pyCMS), a :exc:`PyCMSError` will be raised.
|
| 632 |
+
|
| 633 |
+
This function builds and returns an ICC transform from the ``inputProfile``
|
| 634 |
+
to the ``outputProfile``, but tries to simulate the result that would be
|
| 635 |
+
obtained on the ``proofProfile`` device using ``renderingIntent`` and
|
| 636 |
+
``proofRenderingIntent`` to determine what to do with out-of-gamut
|
| 637 |
+
colors. This is known as "soft-proofing". It will ONLY work for
|
| 638 |
+
converting images that are in ``inMode`` to images that are in outMode
|
| 639 |
+
color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
|
| 640 |
+
|
| 641 |
+
Usage of the resulting transform object is exactly the same as with
|
| 642 |
+
ImageCms.buildTransform().
|
| 643 |
+
|
| 644 |
+
Proof profiling is generally used when using an output device to get a
|
| 645 |
+
good idea of what the final printed/displayed image would look like on
|
| 646 |
+
the ``proofProfile`` device when it's quicker and easier to use the
|
| 647 |
+
output device for judging color. Generally, this means that the
|
| 648 |
+
output device is a monitor, or a dye-sub printer (etc.), and the simulated
|
| 649 |
+
device is something more expensive, complicated, or time consuming
|
| 650 |
+
(making it difficult to make a real print for color judgement purposes).
|
| 651 |
+
|
| 652 |
+
Soft-proofing basically functions by adjusting the colors on the
|
| 653 |
+
output device to match the colors of the device being simulated. However,
|
| 654 |
+
when the simulated device has a much wider gamut than the output
|
| 655 |
+
device, you may obtain marginal results.
|
| 656 |
+
|
| 657 |
+
:param inputProfile: String, as a valid filename path to the ICC input
|
| 658 |
+
profile you wish to use for this transform, or a profile object
|
| 659 |
+
:param outputProfile: String, as a valid filename path to the ICC output
|
| 660 |
+
(monitor, usually) profile you wish to use for this transform, or a
|
| 661 |
+
profile object
|
| 662 |
+
:param proofProfile: String, as a valid filename path to the ICC proof
|
| 663 |
+
profile you wish to use for this transform, or a profile object
|
| 664 |
+
:param inMode: String, as a valid PIL mode that the appropriate profile
|
| 665 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 666 |
+
:param outMode: String, as a valid PIL mode that the appropriate profile
|
| 667 |
+
also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
|
| 668 |
+
:param renderingIntent: Integer (0-3) specifying the rendering intent you
|
| 669 |
+
wish to use for the input->proof (simulated) transform
|
| 670 |
+
|
| 671 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 672 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 673 |
+
ImageCms.Intent.SATURATION = 2
|
| 674 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 675 |
+
|
| 676 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 677 |
+
they do.
|
| 678 |
+
:param proofRenderingIntent: Integer (0-3) specifying the rendering intent
|
| 679 |
+
you wish to use for proof->output transform
|
| 680 |
+
|
| 681 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 682 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 683 |
+
ImageCms.Intent.SATURATION = 2
|
| 684 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 685 |
+
|
| 686 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 687 |
+
they do.
|
| 688 |
+
:param flags: Integer (0-...) specifying additional flags
|
| 689 |
+
:returns: A CmsTransform class object.
|
| 690 |
+
:exception PyCMSError:
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
|
| 694 |
+
msg = "renderingIntent must be an integer between 0 and 3"
|
| 695 |
+
raise PyCMSError(msg)
|
| 696 |
+
|
| 697 |
+
if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
|
| 698 |
+
msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
|
| 699 |
+
raise PyCMSError(msg)
|
| 700 |
+
|
| 701 |
+
try:
|
| 702 |
+
if not isinstance(inputProfile, ImageCmsProfile):
|
| 703 |
+
inputProfile = ImageCmsProfile(inputProfile)
|
| 704 |
+
if not isinstance(outputProfile, ImageCmsProfile):
|
| 705 |
+
outputProfile = ImageCmsProfile(outputProfile)
|
| 706 |
+
if not isinstance(proofProfile, ImageCmsProfile):
|
| 707 |
+
proofProfile = ImageCmsProfile(proofProfile)
|
| 708 |
+
return ImageCmsTransform(
|
| 709 |
+
inputProfile,
|
| 710 |
+
outputProfile,
|
| 711 |
+
inMode,
|
| 712 |
+
outMode,
|
| 713 |
+
renderingIntent,
|
| 714 |
+
proofProfile,
|
| 715 |
+
proofRenderingIntent,
|
| 716 |
+
flags,
|
| 717 |
+
)
|
| 718 |
+
except (OSError, TypeError, ValueError) as v:
|
| 719 |
+
raise PyCMSError(v) from v
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
buildTransformFromOpenProfiles = buildTransform
|
| 723 |
+
buildProofTransformFromOpenProfiles = buildProofTransform
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def applyTransform(
|
| 727 |
+
im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
|
| 728 |
+
) -> Image.Image | None:
|
| 729 |
+
"""
|
| 730 |
+
(pyCMS) Applies a transform to a given image.
|
| 731 |
+
|
| 732 |
+
If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
|
| 733 |
+
|
| 734 |
+
If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
|
| 735 |
+
:exc:`PyCMSError` is raised.
|
| 736 |
+
|
| 737 |
+
If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
|
| 738 |
+
supported by pyCMSdll or the profiles you used for the transform, a
|
| 739 |
+
:exc:`PyCMSError` is raised.
|
| 740 |
+
|
| 741 |
+
If an error occurs while the transform is being applied,
|
| 742 |
+
a :exc:`PyCMSError` is raised.
|
| 743 |
+
|
| 744 |
+
This function applies a pre-calculated transform (from
|
| 745 |
+
ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
|
| 746 |
+
to an image. The transform can be used for multiple images, saving
|
| 747 |
+
considerable calculation time if doing the same conversion multiple times.
|
| 748 |
+
|
| 749 |
+
If you want to modify im in-place instead of receiving a new image as
|
| 750 |
+
the return value, set ``inPlace`` to ``True``. This can only be done if
|
| 751 |
+
``transform.input_mode`` and ``transform.output_mode`` are the same, because we
|
| 752 |
+
can't change the mode in-place (the buffer sizes for some modes are
|
| 753 |
+
different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
|
| 754 |
+
object of the same dimensions in mode ``transform.output_mode``.
|
| 755 |
+
|
| 756 |
+
:param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
|
| 757 |
+
as the ``input_mode`` supported by the transform.
|
| 758 |
+
:param transform: A valid CmsTransform class object
|
| 759 |
+
:param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
|
| 760 |
+
returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
|
| 761 |
+
transform applied is returned (and ``im`` is not changed). The default is
|
| 762 |
+
``False``.
|
| 763 |
+
:returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
|
| 764 |
+
depending on the value of ``inPlace``. The profile will be returned in
|
| 765 |
+
the image's ``info['icc_profile']``.
|
| 766 |
+
:exception PyCMSError:
|
| 767 |
+
"""
|
| 768 |
+
|
| 769 |
+
try:
|
| 770 |
+
if inPlace:
|
| 771 |
+
transform.apply_in_place(im)
|
| 772 |
+
imOut = None
|
| 773 |
+
else:
|
| 774 |
+
imOut = transform.apply(im)
|
| 775 |
+
except (TypeError, ValueError) as v:
|
| 776 |
+
raise PyCMSError(v) from v
|
| 777 |
+
|
| 778 |
+
return imOut
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def createProfile(
|
| 782 |
+
colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
|
| 783 |
+
) -> core.CmsProfile:
|
| 784 |
+
"""
|
| 785 |
+
(pyCMS) Creates a profile.
|
| 786 |
+
|
| 787 |
+
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
|
| 788 |
+
a :exc:`PyCMSError` is raised.
|
| 789 |
+
|
| 790 |
+
If using LAB and ``colorTemp`` is not a positive integer,
|
| 791 |
+
a :exc:`PyCMSError` is raised.
|
| 792 |
+
|
| 793 |
+
If an error occurs while creating the profile,
|
| 794 |
+
a :exc:`PyCMSError` is raised.
|
| 795 |
+
|
| 796 |
+
Use this function to create common profiles on-the-fly instead of
|
| 797 |
+
having to supply a profile on disk and knowing the path to it. It
|
| 798 |
+
returns a normal CmsProfile object that can be passed to
|
| 799 |
+
ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
|
| 800 |
+
to images.
|
| 801 |
+
|
| 802 |
+
:param colorSpace: String, the color space of the profile you wish to
|
| 803 |
+
create.
|
| 804 |
+
Currently only "LAB", "XYZ", and "sRGB" are supported.
|
| 805 |
+
:param colorTemp: Positive number for the white point for the profile, in
|
| 806 |
+
degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
|
| 807 |
+
illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
|
| 808 |
+
profiles, and is ignored for XYZ and sRGB.
|
| 809 |
+
:returns: A CmsProfile class object
|
| 810 |
+
:exception PyCMSError:
|
| 811 |
+
"""
|
| 812 |
+
|
| 813 |
+
if colorSpace not in ["LAB", "XYZ", "sRGB"]:
|
| 814 |
+
msg = (
|
| 815 |
+
f"Color space not supported for on-the-fly profile creation ({colorSpace})"
|
| 816 |
+
)
|
| 817 |
+
raise PyCMSError(msg)
|
| 818 |
+
|
| 819 |
+
if colorSpace == "LAB":
|
| 820 |
+
try:
|
| 821 |
+
colorTemp = float(colorTemp)
|
| 822 |
+
except (TypeError, ValueError) as e:
|
| 823 |
+
msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
|
| 824 |
+
raise PyCMSError(msg) from e
|
| 825 |
+
|
| 826 |
+
try:
|
| 827 |
+
return core.createProfile(colorSpace, colorTemp)
|
| 828 |
+
except (TypeError, ValueError) as v:
|
| 829 |
+
raise PyCMSError(v) from v
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
def getProfileName(profile: _CmsProfileCompatible) -> str:
|
| 833 |
+
"""
|
| 834 |
+
|
| 835 |
+
(pyCMS) Gets the internal product name for the given profile.
|
| 836 |
+
|
| 837 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 838 |
+
a :exc:`PyCMSError` is raised If an error occurs while trying
|
| 839 |
+
to obtain the name tag, a :exc:`PyCMSError` is raised.
|
| 840 |
+
|
| 841 |
+
Use this function to obtain the INTERNAL name of the profile (stored
|
| 842 |
+
in an ICC tag in the profile itself), usually the one used when the
|
| 843 |
+
profile was originally created. Sometimes this tag also contains
|
| 844 |
+
additional information supplied by the creator.
|
| 845 |
+
|
| 846 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 847 |
+
filename of an ICC profile.
|
| 848 |
+
:returns: A string containing the internal name of the profile as stored
|
| 849 |
+
in an ICC tag.
|
| 850 |
+
:exception PyCMSError:
|
| 851 |
+
"""
|
| 852 |
+
|
| 853 |
+
try:
|
| 854 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 855 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 856 |
+
profile = ImageCmsProfile(profile)
|
| 857 |
+
# do it in python, not c.
|
| 858 |
+
# // name was "%s - %s" (model, manufacturer) || Description ,
|
| 859 |
+
# // but if the Model and Manufacturer were the same or the model
|
| 860 |
+
# // was long, Just the model, in 1.x
|
| 861 |
+
model = profile.profile.model
|
| 862 |
+
manufacturer = profile.profile.manufacturer
|
| 863 |
+
|
| 864 |
+
if not (model or manufacturer):
|
| 865 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 866 |
+
if not manufacturer or (model and len(model) > 30):
|
| 867 |
+
return f"{model}\n"
|
| 868 |
+
return f"{model} - {manufacturer}\n"
|
| 869 |
+
|
| 870 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 871 |
+
raise PyCMSError(v) from v
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def getProfileInfo(profile: _CmsProfileCompatible) -> str:
|
| 875 |
+
"""
|
| 876 |
+
(pyCMS) Gets the internal product information for the given profile.
|
| 877 |
+
|
| 878 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
|
| 879 |
+
a :exc:`PyCMSError` is raised.
|
| 880 |
+
|
| 881 |
+
If an error occurs while trying to obtain the info tag,
|
| 882 |
+
a :exc:`PyCMSError` is raised.
|
| 883 |
+
|
| 884 |
+
Use this function to obtain the information stored in the profile's
|
| 885 |
+
info tag. This often contains details about the profile, and how it
|
| 886 |
+
was created, as supplied by the creator.
|
| 887 |
+
|
| 888 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 889 |
+
filename of an ICC profile.
|
| 890 |
+
:returns: A string containing the internal profile information stored in
|
| 891 |
+
an ICC tag.
|
| 892 |
+
:exception PyCMSError:
|
| 893 |
+
"""
|
| 894 |
+
|
| 895 |
+
try:
|
| 896 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 897 |
+
profile = ImageCmsProfile(profile)
|
| 898 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 899 |
+
# Python, not C. the white point bits weren't working well,
|
| 900 |
+
# so skipping.
|
| 901 |
+
# info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
|
| 902 |
+
description = profile.profile.profile_description
|
| 903 |
+
cpright = profile.profile.copyright
|
| 904 |
+
elements = [element for element in (description, cpright) if element]
|
| 905 |
+
return "\r\n\r\n".join(elements) + "\r\n\r\n"
|
| 906 |
+
|
| 907 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 908 |
+
raise PyCMSError(v) from v
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
|
| 912 |
+
"""
|
| 913 |
+
(pyCMS) Gets the copyright for the given profile.
|
| 914 |
+
|
| 915 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 916 |
+
:exc:`PyCMSError` is raised.
|
| 917 |
+
|
| 918 |
+
If an error occurs while trying to obtain the copyright tag,
|
| 919 |
+
a :exc:`PyCMSError` is raised.
|
| 920 |
+
|
| 921 |
+
Use this function to obtain the information stored in the profile's
|
| 922 |
+
copyright tag.
|
| 923 |
+
|
| 924 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 925 |
+
filename of an ICC profile.
|
| 926 |
+
:returns: A string containing the internal profile information stored in
|
| 927 |
+
an ICC tag.
|
| 928 |
+
:exception PyCMSError:
|
| 929 |
+
"""
|
| 930 |
+
try:
|
| 931 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 932 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 933 |
+
profile = ImageCmsProfile(profile)
|
| 934 |
+
return (profile.profile.copyright or "") + "\n"
|
| 935 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 936 |
+
raise PyCMSError(v) from v
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
|
| 940 |
+
"""
|
| 941 |
+
(pyCMS) Gets the manufacturer for the given profile.
|
| 942 |
+
|
| 943 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 944 |
+
:exc:`PyCMSError` is raised.
|
| 945 |
+
|
| 946 |
+
If an error occurs while trying to obtain the manufacturer tag, a
|
| 947 |
+
:exc:`PyCMSError` is raised.
|
| 948 |
+
|
| 949 |
+
Use this function to obtain the information stored in the profile's
|
| 950 |
+
manufacturer tag.
|
| 951 |
+
|
| 952 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 953 |
+
filename of an ICC profile.
|
| 954 |
+
:returns: A string containing the internal profile information stored in
|
| 955 |
+
an ICC tag.
|
| 956 |
+
:exception PyCMSError:
|
| 957 |
+
"""
|
| 958 |
+
try:
|
| 959 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 960 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 961 |
+
profile = ImageCmsProfile(profile)
|
| 962 |
+
return (profile.profile.manufacturer or "") + "\n"
|
| 963 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 964 |
+
raise PyCMSError(v) from v
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
def getProfileModel(profile: _CmsProfileCompatible) -> str:
|
| 968 |
+
"""
|
| 969 |
+
(pyCMS) Gets the model for the given profile.
|
| 970 |
+
|
| 971 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 972 |
+
:exc:`PyCMSError` is raised.
|
| 973 |
+
|
| 974 |
+
If an error occurs while trying to obtain the model tag,
|
| 975 |
+
a :exc:`PyCMSError` is raised.
|
| 976 |
+
|
| 977 |
+
Use this function to obtain the information stored in the profile's
|
| 978 |
+
model tag.
|
| 979 |
+
|
| 980 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 981 |
+
filename of an ICC profile.
|
| 982 |
+
:returns: A string containing the internal profile information stored in
|
| 983 |
+
an ICC tag.
|
| 984 |
+
:exception PyCMSError:
|
| 985 |
+
"""
|
| 986 |
+
|
| 987 |
+
try:
|
| 988 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 989 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 990 |
+
profile = ImageCmsProfile(profile)
|
| 991 |
+
return (profile.profile.model or "") + "\n"
|
| 992 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 993 |
+
raise PyCMSError(v) from v
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def getProfileDescription(profile: _CmsProfileCompatible) -> str:
|
| 997 |
+
"""
|
| 998 |
+
(pyCMS) Gets the description for the given profile.
|
| 999 |
+
|
| 1000 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 1001 |
+
:exc:`PyCMSError` is raised.
|
| 1002 |
+
|
| 1003 |
+
If an error occurs while trying to obtain the description tag,
|
| 1004 |
+
a :exc:`PyCMSError` is raised.
|
| 1005 |
+
|
| 1006 |
+
Use this function to obtain the information stored in the profile's
|
| 1007 |
+
description tag.
|
| 1008 |
+
|
| 1009 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1010 |
+
filename of an ICC profile.
|
| 1011 |
+
:returns: A string containing the internal profile information stored in an
|
| 1012 |
+
ICC tag.
|
| 1013 |
+
:exception PyCMSError:
|
| 1014 |
+
"""
|
| 1015 |
+
|
| 1016 |
+
try:
|
| 1017 |
+
# add an extra newline to preserve pyCMS compatibility
|
| 1018 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1019 |
+
profile = ImageCmsProfile(profile)
|
| 1020 |
+
return (profile.profile.profile_description or "") + "\n"
|
| 1021 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1022 |
+
raise PyCMSError(v) from v
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
|
| 1026 |
+
"""
|
| 1027 |
+
(pyCMS) Gets the default intent name for the given profile.
|
| 1028 |
+
|
| 1029 |
+
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
|
| 1030 |
+
:exc:`PyCMSError` is raised.
|
| 1031 |
+
|
| 1032 |
+
If an error occurs while trying to obtain the default intent, a
|
| 1033 |
+
:exc:`PyCMSError` is raised.
|
| 1034 |
+
|
| 1035 |
+
Use this function to determine the default (and usually best optimized)
|
| 1036 |
+
rendering intent for this profile. Most profiles support multiple
|
| 1037 |
+
rendering intents, but are intended mostly for one type of conversion.
|
| 1038 |
+
If you wish to use a different intent than returned, use
|
| 1039 |
+
ImageCms.isIntentSupported() to verify it will work first.
|
| 1040 |
+
|
| 1041 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1042 |
+
filename of an ICC profile.
|
| 1043 |
+
:returns: Integer 0-3 specifying the default rendering intent for this
|
| 1044 |
+
profile.
|
| 1045 |
+
|
| 1046 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1047 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1048 |
+
ImageCms.Intent.SATURATION = 2
|
| 1049 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1050 |
+
|
| 1051 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1052 |
+
they do.
|
| 1053 |
+
:exception PyCMSError:
|
| 1054 |
+
"""
|
| 1055 |
+
|
| 1056 |
+
try:
|
| 1057 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1058 |
+
profile = ImageCmsProfile(profile)
|
| 1059 |
+
return profile.profile.rendering_intent
|
| 1060 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1061 |
+
raise PyCMSError(v) from v
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
def isIntentSupported(
|
| 1065 |
+
profile: _CmsProfileCompatible, intent: Intent, direction: Direction
|
| 1066 |
+
) -> Literal[-1, 1]:
|
| 1067 |
+
"""
|
| 1068 |
+
(pyCMS) Checks if a given intent is supported.
|
| 1069 |
+
|
| 1070 |
+
Use this function to verify that you can use your desired
|
| 1071 |
+
``intent`` with ``profile``, and that ``profile`` can be used for the
|
| 1072 |
+
input/output/proof profile as you desire.
|
| 1073 |
+
|
| 1074 |
+
Some profiles are created specifically for one "direction", can cannot
|
| 1075 |
+
be used for others. Some profiles can only be used for certain
|
| 1076 |
+
rendering intents, so it's best to either verify this before trying
|
| 1077 |
+
to create a transform with them (using this function), or catch the
|
| 1078 |
+
potential :exc:`PyCMSError` that will occur if they don't
|
| 1079 |
+
support the modes you select.
|
| 1080 |
+
|
| 1081 |
+
:param profile: EITHER a valid CmsProfile object, OR a string of the
|
| 1082 |
+
filename of an ICC profile.
|
| 1083 |
+
:param intent: Integer (0-3) specifying the rendering intent you wish to
|
| 1084 |
+
use with this profile
|
| 1085 |
+
|
| 1086 |
+
ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
|
| 1087 |
+
ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
|
| 1088 |
+
ImageCms.Intent.SATURATION = 2
|
| 1089 |
+
ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
|
| 1090 |
+
|
| 1091 |
+
see the pyCMS documentation for details on rendering intents and what
|
| 1092 |
+
they do.
|
| 1093 |
+
:param direction: Integer specifying if the profile is to be used for
|
| 1094 |
+
input, output, or proof
|
| 1095 |
+
|
| 1096 |
+
INPUT = 0 (or use ImageCms.Direction.INPUT)
|
| 1097 |
+
OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
|
| 1098 |
+
PROOF = 2 (or use ImageCms.Direction.PROOF)
|
| 1099 |
+
|
| 1100 |
+
:returns: 1 if the intent/direction are supported, -1 if they are not.
|
| 1101 |
+
:exception PyCMSError:
|
| 1102 |
+
"""
|
| 1103 |
+
|
| 1104 |
+
try:
|
| 1105 |
+
if not isinstance(profile, ImageCmsProfile):
|
| 1106 |
+
profile = ImageCmsProfile(profile)
|
| 1107 |
+
# FIXME: I get different results for the same data w. different
|
| 1108 |
+
# compilers. Bug in LittleCMS or in the binding?
|
| 1109 |
+
if profile.profile.is_intent_supported(intent, direction):
|
| 1110 |
+
return 1
|
| 1111 |
+
else:
|
| 1112 |
+
return -1
|
| 1113 |
+
except (AttributeError, OSError, TypeError, ValueError) as v:
|
| 1114 |
+
raise PyCMSError(v) from v
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def versions() -> tuple[str, str | None, str, str]:
|
| 1118 |
+
"""
|
| 1119 |
+
(pyCMS) Fetches versions.
|
| 1120 |
+
"""
|
| 1121 |
+
|
| 1122 |
+
deprecate(
|
| 1123 |
+
"PIL.ImageCms.versions()",
|
| 1124 |
+
12,
|
| 1125 |
+
'(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
|
| 1126 |
+
)
|
| 1127 |
+
return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
|
valley/lib/python3.10/site-packages/PIL/ImageDraw2.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# WCK-style drawing interface operations
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2003-12-07 fl created
|
| 9 |
+
# 2005-05-15 fl updated; added to PIL as ImageDraw2
|
| 10 |
+
# 2005-05-15 fl added text support
|
| 11 |
+
# 2005-05-20 fl added arc/chord/pieslice support
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 2003-2005 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 2003-2005 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
(Experimental) WCK-style drawing interface operations
|
| 22 |
+
|
| 23 |
+
.. seealso:: :py:mod:`PIL.ImageDraw`
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
from typing import BinaryIO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
|
| 30 |
+
from ._typing import StrOrBytesPath
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Pen:
|
| 34 |
+
"""Stores an outline color and width."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
|
| 37 |
+
self.color = ImageColor.getrgb(color)
|
| 38 |
+
self.width = width
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Brush:
|
| 42 |
+
"""Stores a fill color"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, color: str, opacity: int = 255) -> None:
|
| 45 |
+
self.color = ImageColor.getrgb(color)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Font:
|
| 49 |
+
"""Stores a TrueType font and color"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
|
| 53 |
+
) -> None:
|
| 54 |
+
# FIXME: add support for bitmap fonts
|
| 55 |
+
self.color = ImageColor.getrgb(color)
|
| 56 |
+
self.font = ImageFont.truetype(file, size)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Draw:
|
| 60 |
+
"""
|
| 61 |
+
(Experimental) WCK-style drawing interface
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
image: Image.Image | str,
|
| 67 |
+
size: tuple[int, int] | list[int] | None = None,
|
| 68 |
+
color: float | tuple[float, ...] | str | None = None,
|
| 69 |
+
) -> None:
|
| 70 |
+
if isinstance(image, str):
|
| 71 |
+
if size is None:
|
| 72 |
+
msg = "If image argument is mode string, size must be a list or tuple"
|
| 73 |
+
raise ValueError(msg)
|
| 74 |
+
image = Image.new(image, size, color)
|
| 75 |
+
self.draw = ImageDraw.Draw(image)
|
| 76 |
+
self.image = image
|
| 77 |
+
self.transform = None
|
| 78 |
+
|
| 79 |
+
def flush(self) -> Image.Image:
|
| 80 |
+
return self.image
|
| 81 |
+
|
| 82 |
+
def render(self, op, xy, pen, brush=None):
|
| 83 |
+
# handle color arguments
|
| 84 |
+
outline = fill = None
|
| 85 |
+
width = 1
|
| 86 |
+
if isinstance(pen, Pen):
|
| 87 |
+
outline = pen.color
|
| 88 |
+
width = pen.width
|
| 89 |
+
elif isinstance(brush, Pen):
|
| 90 |
+
outline = brush.color
|
| 91 |
+
width = brush.width
|
| 92 |
+
if isinstance(brush, Brush):
|
| 93 |
+
fill = brush.color
|
| 94 |
+
elif isinstance(pen, Brush):
|
| 95 |
+
fill = pen.color
|
| 96 |
+
# handle transformation
|
| 97 |
+
if self.transform:
|
| 98 |
+
xy = ImagePath.Path(xy)
|
| 99 |
+
xy.transform(self.transform)
|
| 100 |
+
# render the item
|
| 101 |
+
if op == "line":
|
| 102 |
+
self.draw.line(xy, fill=outline, width=width)
|
| 103 |
+
else:
|
| 104 |
+
getattr(self.draw, op)(xy, fill=fill, outline=outline)
|
| 105 |
+
|
| 106 |
+
def settransform(self, offset):
|
| 107 |
+
"""Sets a transformation offset."""
|
| 108 |
+
(xoffset, yoffset) = offset
|
| 109 |
+
self.transform = (1, 0, xoffset, 0, 1, yoffset)
|
| 110 |
+
|
| 111 |
+
def arc(self, xy, start, end, *options):
|
| 112 |
+
"""
|
| 113 |
+
Draws an arc (a portion of a circle outline) between the start and end
|
| 114 |
+
angles, inside the given bounding box.
|
| 115 |
+
|
| 116 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
| 117 |
+
"""
|
| 118 |
+
self.render("arc", xy, start, end, *options)
|
| 119 |
+
|
| 120 |
+
def chord(self, xy, start, end, *options):
|
| 121 |
+
"""
|
| 122 |
+
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
|
| 123 |
+
with a straight line.
|
| 124 |
+
|
| 125 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
| 126 |
+
"""
|
| 127 |
+
self.render("chord", xy, start, end, *options)
|
| 128 |
+
|
| 129 |
+
def ellipse(self, xy, *options):
|
| 130 |
+
"""
|
| 131 |
+
Draws an ellipse inside the given bounding box.
|
| 132 |
+
|
| 133 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
| 134 |
+
"""
|
| 135 |
+
self.render("ellipse", xy, *options)
|
| 136 |
+
|
| 137 |
+
def line(self, xy, *options):
|
| 138 |
+
"""
|
| 139 |
+
Draws a line between the coordinates in the ``xy`` list.
|
| 140 |
+
|
| 141 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
| 142 |
+
"""
|
| 143 |
+
self.render("line", xy, *options)
|
| 144 |
+
|
| 145 |
+
def pieslice(self, xy, start, end, *options):
|
| 146 |
+
"""
|
| 147 |
+
Same as arc, but also draws straight lines between the end points and the
|
| 148 |
+
center of the bounding box.
|
| 149 |
+
|
| 150 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
|
| 151 |
+
"""
|
| 152 |
+
self.render("pieslice", xy, start, end, *options)
|
| 153 |
+
|
| 154 |
+
def polygon(self, xy, *options):
|
| 155 |
+
"""
|
| 156 |
+
Draws a polygon.
|
| 157 |
+
|
| 158 |
+
The polygon outline consists of straight lines between the given
|
| 159 |
+
coordinates, plus a straight line between the last and the first
|
| 160 |
+
coordinate.
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
|
| 164 |
+
"""
|
| 165 |
+
self.render("polygon", xy, *options)
|
| 166 |
+
|
| 167 |
+
def rectangle(self, xy, *options):
|
| 168 |
+
"""
|
| 169 |
+
Draws a rectangle.
|
| 170 |
+
|
| 171 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
|
| 172 |
+
"""
|
| 173 |
+
self.render("rectangle", xy, *options)
|
| 174 |
+
|
| 175 |
+
def text(self, xy, text, font):
|
| 176 |
+
"""
|
| 177 |
+
Draws the string at the given position.
|
| 178 |
+
|
| 179 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
|
| 180 |
+
"""
|
| 181 |
+
if self.transform:
|
| 182 |
+
xy = ImagePath.Path(xy)
|
| 183 |
+
xy.transform(self.transform)
|
| 184 |
+
self.draw.text(xy, text, font=font.font, fill=font.color)
|
| 185 |
+
|
| 186 |
+
def textbbox(self, xy, text, font):
|
| 187 |
+
"""
|
| 188 |
+
Returns bounding box (in pixels) of given text.
|
| 189 |
+
|
| 190 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 191 |
+
|
| 192 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
|
| 193 |
+
"""
|
| 194 |
+
if self.transform:
|
| 195 |
+
xy = ImagePath.Path(xy)
|
| 196 |
+
xy.transform(self.transform)
|
| 197 |
+
return self.draw.textbbox(xy, text, font=font.font)
|
| 198 |
+
|
| 199 |
+
def textlength(self, text, font):
|
| 200 |
+
"""
|
| 201 |
+
Returns length (in pixels) of given text.
|
| 202 |
+
This is the amount by which following text should be offset.
|
| 203 |
+
|
| 204 |
+
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
|
| 205 |
+
"""
|
| 206 |
+
return self.draw.textlength(text, font=font.font)
|
valley/lib/python3.10/site-packages/PIL/ImageEnhance.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# image enhancement classes
|
| 6 |
+
#
|
| 7 |
+
# For a background, see "Image Processing By Interpolation and
|
| 8 |
+
# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
|
| 9 |
+
# at http://www.graficaobscura.com/interp/index.html
|
| 10 |
+
#
|
| 11 |
+
# History:
|
| 12 |
+
# 1996-03-23 fl Created
|
| 13 |
+
# 2009-06-16 fl Fixed mean calculation
|
| 14 |
+
#
|
| 15 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 16 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 17 |
+
#
|
| 18 |
+
# See the README file for information on usage and redistribution.
|
| 19 |
+
#
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from . import Image, ImageFilter, ImageStat
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class _Enhance:
|
| 26 |
+
image: Image.Image
|
| 27 |
+
degenerate: Image.Image
|
| 28 |
+
|
| 29 |
+
def enhance(self, factor: float) -> Image.Image:
|
| 30 |
+
"""
|
| 31 |
+
Returns an enhanced image.
|
| 32 |
+
|
| 33 |
+
:param factor: A floating point value controlling the enhancement.
|
| 34 |
+
Factor 1.0 always returns a copy of the original image,
|
| 35 |
+
lower factors mean less color (brightness, contrast,
|
| 36 |
+
etc), and higher values more. There are no restrictions
|
| 37 |
+
on this value.
|
| 38 |
+
:rtype: :py:class:`~PIL.Image.Image`
|
| 39 |
+
"""
|
| 40 |
+
return Image.blend(self.degenerate, self.image, factor)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Color(_Enhance):
|
| 44 |
+
"""Adjust image color balance.
|
| 45 |
+
|
| 46 |
+
This class can be used to adjust the colour balance of an image, in
|
| 47 |
+
a manner similar to the controls on a colour TV set. An enhancement
|
| 48 |
+
factor of 0.0 gives a black and white image. A factor of 1.0 gives
|
| 49 |
+
the original image.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, image: Image.Image) -> None:
|
| 53 |
+
self.image = image
|
| 54 |
+
self.intermediate_mode = "L"
|
| 55 |
+
if "A" in image.getbands():
|
| 56 |
+
self.intermediate_mode = "LA"
|
| 57 |
+
|
| 58 |
+
self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Contrast(_Enhance):
|
| 62 |
+
"""Adjust image contrast.
|
| 63 |
+
|
| 64 |
+
This class can be used to control the contrast of an image, similar
|
| 65 |
+
to the contrast control on a TV set. An enhancement factor of 0.0
|
| 66 |
+
gives a solid gray image. A factor of 1.0 gives the original image.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self, image: Image.Image) -> None:
|
| 70 |
+
self.image = image
|
| 71 |
+
mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
|
| 72 |
+
self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
|
| 73 |
+
|
| 74 |
+
if "A" in image.getbands():
|
| 75 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Brightness(_Enhance):
|
| 79 |
+
"""Adjust image brightness.
|
| 80 |
+
|
| 81 |
+
This class can be used to control the brightness of an image. An
|
| 82 |
+
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
|
| 83 |
+
original image.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, image: Image.Image) -> None:
|
| 87 |
+
self.image = image
|
| 88 |
+
self.degenerate = Image.new(image.mode, image.size, 0)
|
| 89 |
+
|
| 90 |
+
if "A" in image.getbands():
|
| 91 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Sharpness(_Enhance):
|
| 95 |
+
"""Adjust image sharpness.
|
| 96 |
+
|
| 97 |
+
This class can be used to adjust the sharpness of an image. An
|
| 98 |
+
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
|
| 99 |
+
original image, and a factor of 2.0 gives a sharpened image.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(self, image: Image.Image) -> None:
|
| 103 |
+
self.image = image
|
| 104 |
+
self.degenerate = image.filter(ImageFilter.SMOOTH)
|
| 105 |
+
|
| 106 |
+
if "A" in image.getbands():
|
| 107 |
+
self.degenerate.putalpha(image.getchannel("A"))
|
valley/lib/python3.10/site-packages/PIL/ImageFile.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# base class for image file handlers
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1995-09-09 fl Created
|
| 9 |
+
# 1996-03-11 fl Fixed load mechanism.
|
| 10 |
+
# 1996-04-15 fl Added pcx/xbm decoders.
|
| 11 |
+
# 1996-04-30 fl Added encoders.
|
| 12 |
+
# 1996-12-14 fl Added load helpers
|
| 13 |
+
# 1997-01-11 fl Use encode_to_file where possible
|
| 14 |
+
# 1997-08-27 fl Flush output in _save
|
| 15 |
+
# 1998-03-05 fl Use memory mapping for some modes
|
| 16 |
+
# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
|
| 17 |
+
# 1999-05-31 fl Added image parser
|
| 18 |
+
# 2000-10-12 fl Set readonly flag on memory-mapped images
|
| 19 |
+
# 2002-03-20 fl Use better messages for common decoder errors
|
| 20 |
+
# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
|
| 21 |
+
# 2003-10-30 fl Added StubImageFile class
|
| 22 |
+
# 2004-02-25 fl Made incremental parser more robust
|
| 23 |
+
#
|
| 24 |
+
# Copyright (c) 1997-2004 by Secret Labs AB
|
| 25 |
+
# Copyright (c) 1995-2004 by Fredrik Lundh
|
| 26 |
+
#
|
| 27 |
+
# See the README file for information on usage and redistribution.
|
| 28 |
+
#
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import abc
|
| 32 |
+
import io
|
| 33 |
+
import itertools
|
| 34 |
+
import struct
|
| 35 |
+
import sys
|
| 36 |
+
from typing import IO, Any, NamedTuple
|
| 37 |
+
|
| 38 |
+
from . import Image
|
| 39 |
+
from ._deprecate import deprecate
|
| 40 |
+
from ._util import is_path
|
| 41 |
+
|
| 42 |
+
MAXBLOCK = 65536
|
| 43 |
+
|
| 44 |
+
SAFEBLOCK = 1024 * 1024
|
| 45 |
+
|
| 46 |
+
LOAD_TRUNCATED_IMAGES = False
|
| 47 |
+
"""Whether or not to load truncated image files. User code may change this."""
|
| 48 |
+
|
| 49 |
+
ERRORS = {
|
| 50 |
+
-1: "image buffer overrun error",
|
| 51 |
+
-2: "decoding error",
|
| 52 |
+
-3: "unknown error",
|
| 53 |
+
-8: "bad configuration",
|
| 54 |
+
-9: "out of memory error",
|
| 55 |
+
}
|
| 56 |
+
"""
|
| 57 |
+
Dict of known error codes returned from :meth:`.PyDecoder.decode`,
|
| 58 |
+
:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
|
| 59 |
+
:meth:`.PyEncoder.encode_to_file`.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
#
|
| 64 |
+
# --------------------------------------------------------------------
|
| 65 |
+
# Helpers
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _get_oserror(error: int, *, encoder: bool) -> OSError:
|
| 69 |
+
try:
|
| 70 |
+
msg = Image.core.getcodecstatus(error)
|
| 71 |
+
except AttributeError:
|
| 72 |
+
msg = ERRORS.get(error)
|
| 73 |
+
if not msg:
|
| 74 |
+
msg = f"{'encoder' if encoder else 'decoder'} error {error}"
|
| 75 |
+
msg += f" when {'writing' if encoder else 'reading'} image file"
|
| 76 |
+
return OSError(msg)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def raise_oserror(error: int) -> OSError:
|
| 80 |
+
deprecate(
|
| 81 |
+
"raise_oserror",
|
| 82 |
+
12,
|
| 83 |
+
action="It is only useful for translating error codes returned by a codec's "
|
| 84 |
+
"decode() method, which ImageFile already does automatically.",
|
| 85 |
+
)
|
| 86 |
+
raise _get_oserror(error, encoder=False)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _tilesort(t):
|
| 90 |
+
# sort on offset
|
| 91 |
+
return t[2]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class _Tile(NamedTuple):
|
| 95 |
+
codec_name: str
|
| 96 |
+
extents: tuple[int, int, int, int]
|
| 97 |
+
offset: int
|
| 98 |
+
args: tuple[Any, ...] | str | None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
#
|
| 102 |
+
# --------------------------------------------------------------------
|
| 103 |
+
# ImageFile base class
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class ImageFile(Image.Image):
|
| 107 |
+
"""Base class for image file format handlers."""
|
| 108 |
+
|
| 109 |
+
def __init__(self, fp=None, filename=None):
|
| 110 |
+
super().__init__()
|
| 111 |
+
|
| 112 |
+
self._min_frame = 0
|
| 113 |
+
|
| 114 |
+
self.custom_mimetype = None
|
| 115 |
+
|
| 116 |
+
self.tile = None
|
| 117 |
+
""" A list of tile descriptors, or ``None`` """
|
| 118 |
+
|
| 119 |
+
self.readonly = 1 # until we know better
|
| 120 |
+
|
| 121 |
+
self.decoderconfig = ()
|
| 122 |
+
self.decodermaxblock = MAXBLOCK
|
| 123 |
+
|
| 124 |
+
if is_path(fp):
|
| 125 |
+
# filename
|
| 126 |
+
self.fp = open(fp, "rb")
|
| 127 |
+
self.filename = fp
|
| 128 |
+
self._exclusive_fp = True
|
| 129 |
+
else:
|
| 130 |
+
# stream
|
| 131 |
+
self.fp = fp
|
| 132 |
+
self.filename = filename
|
| 133 |
+
# can be overridden
|
| 134 |
+
self._exclusive_fp = None
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
try:
|
| 138 |
+
self._open()
|
| 139 |
+
except (
|
| 140 |
+
IndexError, # end of data
|
| 141 |
+
TypeError, # end of data (ord)
|
| 142 |
+
KeyError, # unsupported mode
|
| 143 |
+
EOFError, # got header but not the first frame
|
| 144 |
+
struct.error,
|
| 145 |
+
) as v:
|
| 146 |
+
raise SyntaxError(v) from v
|
| 147 |
+
|
| 148 |
+
if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
|
| 149 |
+
msg = "not identified by this driver"
|
| 150 |
+
raise SyntaxError(msg)
|
| 151 |
+
except BaseException:
|
| 152 |
+
# close the file only if we have opened it this constructor
|
| 153 |
+
if self._exclusive_fp:
|
| 154 |
+
self.fp.close()
|
| 155 |
+
raise
|
| 156 |
+
|
| 157 |
+
def get_format_mimetype(self) -> str | None:
|
| 158 |
+
if self.custom_mimetype:
|
| 159 |
+
return self.custom_mimetype
|
| 160 |
+
if self.format is not None:
|
| 161 |
+
return Image.MIME.get(self.format.upper())
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
def __setstate__(self, state):
|
| 165 |
+
self.tile = []
|
| 166 |
+
super().__setstate__(state)
|
| 167 |
+
|
| 168 |
+
def verify(self) -> None:
|
| 169 |
+
"""Check file integrity"""
|
| 170 |
+
|
| 171 |
+
# raise exception if something's wrong. must be called
|
| 172 |
+
# directly after open, and closes file when finished.
|
| 173 |
+
if self._exclusive_fp:
|
| 174 |
+
self.fp.close()
|
| 175 |
+
self.fp = None
|
| 176 |
+
|
| 177 |
+
def load(self):
|
| 178 |
+
"""Load image data based on tile list"""
|
| 179 |
+
|
| 180 |
+
if self.tile is None:
|
| 181 |
+
msg = "cannot load this image"
|
| 182 |
+
raise OSError(msg)
|
| 183 |
+
|
| 184 |
+
pixel = Image.Image.load(self)
|
| 185 |
+
if not self.tile:
|
| 186 |
+
return pixel
|
| 187 |
+
|
| 188 |
+
self.map = None
|
| 189 |
+
use_mmap = self.filename and len(self.tile) == 1
|
| 190 |
+
# As of pypy 2.1.0, memory mapping was failing here.
|
| 191 |
+
use_mmap = use_mmap and not hasattr(sys, "pypy_version_info")
|
| 192 |
+
|
| 193 |
+
readonly = 0
|
| 194 |
+
|
| 195 |
+
# look for read/seek overrides
|
| 196 |
+
try:
|
| 197 |
+
read = self.load_read
|
| 198 |
+
# don't use mmap if there are custom read/seek functions
|
| 199 |
+
use_mmap = False
|
| 200 |
+
except AttributeError:
|
| 201 |
+
read = self.fp.read
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
seek = self.load_seek
|
| 205 |
+
use_mmap = False
|
| 206 |
+
except AttributeError:
|
| 207 |
+
seek = self.fp.seek
|
| 208 |
+
|
| 209 |
+
if use_mmap:
|
| 210 |
+
# try memory mapping
|
| 211 |
+
decoder_name, extents, offset, args = self.tile[0]
|
| 212 |
+
if isinstance(args, str):
|
| 213 |
+
args = (args, 0, 1)
|
| 214 |
+
if (
|
| 215 |
+
decoder_name == "raw"
|
| 216 |
+
and len(args) >= 3
|
| 217 |
+
and args[0] == self.mode
|
| 218 |
+
and args[0] in Image._MAPMODES
|
| 219 |
+
):
|
| 220 |
+
try:
|
| 221 |
+
# use mmap, if possible
|
| 222 |
+
import mmap
|
| 223 |
+
|
| 224 |
+
with open(self.filename) as fp:
|
| 225 |
+
self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
|
| 226 |
+
if offset + self.size[1] * args[1] > self.map.size():
|
| 227 |
+
msg = "buffer is not large enough"
|
| 228 |
+
raise OSError(msg)
|
| 229 |
+
self.im = Image.core.map_buffer(
|
| 230 |
+
self.map, self.size, decoder_name, offset, args
|
| 231 |
+
)
|
| 232 |
+
readonly = 1
|
| 233 |
+
# After trashing self.im,
|
| 234 |
+
# we might need to reload the palette data.
|
| 235 |
+
if self.palette:
|
| 236 |
+
self.palette.dirty = 1
|
| 237 |
+
except (AttributeError, OSError, ImportError):
|
| 238 |
+
self.map = None
|
| 239 |
+
|
| 240 |
+
self.load_prepare()
|
| 241 |
+
err_code = -3 # initialize to unknown error
|
| 242 |
+
if not self.map:
|
| 243 |
+
# sort tiles in file order
|
| 244 |
+
self.tile.sort(key=_tilesort)
|
| 245 |
+
|
| 246 |
+
try:
|
| 247 |
+
# FIXME: This is a hack to handle TIFF's JpegTables tag.
|
| 248 |
+
prefix = self.tile_prefix
|
| 249 |
+
except AttributeError:
|
| 250 |
+
prefix = b""
|
| 251 |
+
|
| 252 |
+
# Remove consecutive duplicates that only differ by their offset
|
| 253 |
+
self.tile = [
|
| 254 |
+
list(tiles)[-1]
|
| 255 |
+
for _, tiles in itertools.groupby(
|
| 256 |
+
self.tile, lambda tile: (tile[0], tile[1], tile[3])
|
| 257 |
+
)
|
| 258 |
+
]
|
| 259 |
+
for decoder_name, extents, offset, args in self.tile:
|
| 260 |
+
seek(offset)
|
| 261 |
+
decoder = Image._getdecoder(
|
| 262 |
+
self.mode, decoder_name, args, self.decoderconfig
|
| 263 |
+
)
|
| 264 |
+
try:
|
| 265 |
+
decoder.setimage(self.im, extents)
|
| 266 |
+
if decoder.pulls_fd:
|
| 267 |
+
decoder.setfd(self.fp)
|
| 268 |
+
err_code = decoder.decode(b"")[1]
|
| 269 |
+
else:
|
| 270 |
+
b = prefix
|
| 271 |
+
while True:
|
| 272 |
+
try:
|
| 273 |
+
s = read(self.decodermaxblock)
|
| 274 |
+
except (IndexError, struct.error) as e:
|
| 275 |
+
# truncated png/gif
|
| 276 |
+
if LOAD_TRUNCATED_IMAGES:
|
| 277 |
+
break
|
| 278 |
+
else:
|
| 279 |
+
msg = "image file is truncated"
|
| 280 |
+
raise OSError(msg) from e
|
| 281 |
+
|
| 282 |
+
if not s: # truncated jpeg
|
| 283 |
+
if LOAD_TRUNCATED_IMAGES:
|
| 284 |
+
break
|
| 285 |
+
else:
|
| 286 |
+
msg = (
|
| 287 |
+
"image file is truncated "
|
| 288 |
+
f"({len(b)} bytes not processed)"
|
| 289 |
+
)
|
| 290 |
+
raise OSError(msg)
|
| 291 |
+
|
| 292 |
+
b = b + s
|
| 293 |
+
n, err_code = decoder.decode(b)
|
| 294 |
+
if n < 0:
|
| 295 |
+
break
|
| 296 |
+
b = b[n:]
|
| 297 |
+
finally:
|
| 298 |
+
# Need to cleanup here to prevent leaks
|
| 299 |
+
decoder.cleanup()
|
| 300 |
+
|
| 301 |
+
self.tile = []
|
| 302 |
+
self.readonly = readonly
|
| 303 |
+
|
| 304 |
+
self.load_end()
|
| 305 |
+
|
| 306 |
+
if self._exclusive_fp and self._close_exclusive_fp_after_loading:
|
| 307 |
+
self.fp.close()
|
| 308 |
+
self.fp = None
|
| 309 |
+
|
| 310 |
+
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
|
| 311 |
+
# still raised if decoder fails to return anything
|
| 312 |
+
raise _get_oserror(err_code, encoder=False)
|
| 313 |
+
|
| 314 |
+
return Image.Image.load(self)
|
| 315 |
+
|
| 316 |
+
def load_prepare(self) -> None:
|
| 317 |
+
# create image memory if necessary
|
| 318 |
+
if not self.im or self.im.mode != self.mode or self.im.size != self.size:
|
| 319 |
+
self.im = Image.core.new(self.mode, self.size)
|
| 320 |
+
# create palette (optional)
|
| 321 |
+
if self.mode == "P":
|
| 322 |
+
Image.Image.load(self)
|
| 323 |
+
|
| 324 |
+
def load_end(self) -> None:
|
| 325 |
+
# may be overridden
|
| 326 |
+
pass
|
| 327 |
+
|
| 328 |
+
# may be defined for contained formats
|
| 329 |
+
# def load_seek(self, pos: int) -> None:
|
| 330 |
+
# pass
|
| 331 |
+
|
| 332 |
+
# may be defined for blocked formats (e.g. PNG)
|
| 333 |
+
# def load_read(self, read_bytes: int) -> bytes:
|
| 334 |
+
# pass
|
| 335 |
+
|
| 336 |
+
def _seek_check(self, frame):
|
| 337 |
+
if (
|
| 338 |
+
frame < self._min_frame
|
| 339 |
+
# Only check upper limit on frames if additional seek operations
|
| 340 |
+
# are not required to do so
|
| 341 |
+
or (
|
| 342 |
+
not (hasattr(self, "_n_frames") and self._n_frames is None)
|
| 343 |
+
and frame >= self.n_frames + self._min_frame
|
| 344 |
+
)
|
| 345 |
+
):
|
| 346 |
+
msg = "attempt to seek outside sequence"
|
| 347 |
+
raise EOFError(msg)
|
| 348 |
+
|
| 349 |
+
return self.tell() != frame
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class StubHandler:
|
| 353 |
+
def open(self, im: StubImageFile) -> None:
|
| 354 |
+
pass
|
| 355 |
+
|
| 356 |
+
@abc.abstractmethod
|
| 357 |
+
def load(self, im: StubImageFile) -> Image.Image:
|
| 358 |
+
pass
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class StubImageFile(ImageFile):
|
| 362 |
+
"""
|
| 363 |
+
Base class for stub image loaders.
|
| 364 |
+
|
| 365 |
+
A stub loader is an image loader that can identify files of a
|
| 366 |
+
certain format, but relies on external code to load the file.
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
def _open(self) -> None:
|
| 370 |
+
msg = "StubImageFile subclass must implement _open"
|
| 371 |
+
raise NotImplementedError(msg)
|
| 372 |
+
|
| 373 |
+
def load(self):
|
| 374 |
+
loader = self._load()
|
| 375 |
+
if loader is None:
|
| 376 |
+
msg = f"cannot find loader for this {self.format} file"
|
| 377 |
+
raise OSError(msg)
|
| 378 |
+
image = loader.load(self)
|
| 379 |
+
assert image is not None
|
| 380 |
+
# become the other object (!)
|
| 381 |
+
self.__class__ = image.__class__
|
| 382 |
+
self.__dict__ = image.__dict__
|
| 383 |
+
return image.load()
|
| 384 |
+
|
| 385 |
+
def _load(self) -> StubHandler | None:
|
| 386 |
+
"""(Hook) Find actual image loader."""
|
| 387 |
+
msg = "StubImageFile subclass must implement _load"
|
| 388 |
+
raise NotImplementedError(msg)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class Parser:
|
| 392 |
+
"""
|
| 393 |
+
Incremental image parser. This class implements the standard
|
| 394 |
+
feed/close consumer interface.
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
incremental = None
|
| 398 |
+
image: Image.Image | None = None
|
| 399 |
+
data = None
|
| 400 |
+
decoder = None
|
| 401 |
+
offset = 0
|
| 402 |
+
finished = 0
|
| 403 |
+
|
| 404 |
+
def reset(self) -> None:
|
| 405 |
+
"""
|
| 406 |
+
(Consumer) Reset the parser. Note that you can only call this
|
| 407 |
+
method immediately after you've created a parser; parser
|
| 408 |
+
instances cannot be reused.
|
| 409 |
+
"""
|
| 410 |
+
assert self.data is None, "cannot reuse parsers"
|
| 411 |
+
|
| 412 |
+
def feed(self, data):
|
| 413 |
+
"""
|
| 414 |
+
(Consumer) Feed data to the parser.
|
| 415 |
+
|
| 416 |
+
:param data: A string buffer.
|
| 417 |
+
:exception OSError: If the parser failed to parse the image file.
|
| 418 |
+
"""
|
| 419 |
+
# collect data
|
| 420 |
+
|
| 421 |
+
if self.finished:
|
| 422 |
+
return
|
| 423 |
+
|
| 424 |
+
if self.data is None:
|
| 425 |
+
self.data = data
|
| 426 |
+
else:
|
| 427 |
+
self.data = self.data + data
|
| 428 |
+
|
| 429 |
+
# parse what we have
|
| 430 |
+
if self.decoder:
|
| 431 |
+
if self.offset > 0:
|
| 432 |
+
# skip header
|
| 433 |
+
skip = min(len(self.data), self.offset)
|
| 434 |
+
self.data = self.data[skip:]
|
| 435 |
+
self.offset = self.offset - skip
|
| 436 |
+
if self.offset > 0 or not self.data:
|
| 437 |
+
return
|
| 438 |
+
|
| 439 |
+
n, e = self.decoder.decode(self.data)
|
| 440 |
+
|
| 441 |
+
if n < 0:
|
| 442 |
+
# end of stream
|
| 443 |
+
self.data = None
|
| 444 |
+
self.finished = 1
|
| 445 |
+
if e < 0:
|
| 446 |
+
# decoding error
|
| 447 |
+
self.image = None
|
| 448 |
+
raise _get_oserror(e, encoder=False)
|
| 449 |
+
else:
|
| 450 |
+
# end of image
|
| 451 |
+
return
|
| 452 |
+
self.data = self.data[n:]
|
| 453 |
+
|
| 454 |
+
elif self.image:
|
| 455 |
+
# if we end up here with no decoder, this file cannot
|
| 456 |
+
# be incrementally parsed. wait until we've gotten all
|
| 457 |
+
# available data
|
| 458 |
+
pass
|
| 459 |
+
|
| 460 |
+
else:
|
| 461 |
+
# attempt to open this file
|
| 462 |
+
try:
|
| 463 |
+
with io.BytesIO(self.data) as fp:
|
| 464 |
+
im = Image.open(fp)
|
| 465 |
+
except OSError:
|
| 466 |
+
pass # not enough data
|
| 467 |
+
else:
|
| 468 |
+
flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
|
| 469 |
+
if flag or len(im.tile) != 1:
|
| 470 |
+
# custom load code, or multiple tiles
|
| 471 |
+
self.decode = None
|
| 472 |
+
else:
|
| 473 |
+
# initialize decoder
|
| 474 |
+
im.load_prepare()
|
| 475 |
+
d, e, o, a = im.tile[0]
|
| 476 |
+
im.tile = []
|
| 477 |
+
self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
|
| 478 |
+
self.decoder.setimage(im.im, e)
|
| 479 |
+
|
| 480 |
+
# calculate decoder offset
|
| 481 |
+
self.offset = o
|
| 482 |
+
if self.offset <= len(self.data):
|
| 483 |
+
self.data = self.data[self.offset :]
|
| 484 |
+
self.offset = 0
|
| 485 |
+
|
| 486 |
+
self.image = im
|
| 487 |
+
|
| 488 |
+
def __enter__(self):
|
| 489 |
+
return self
|
| 490 |
+
|
| 491 |
+
def __exit__(self, *args: object) -> None:
|
| 492 |
+
self.close()
|
| 493 |
+
|
| 494 |
+
def close(self):
|
| 495 |
+
"""
|
| 496 |
+
(Consumer) Close the stream.
|
| 497 |
+
|
| 498 |
+
:returns: An image object.
|
| 499 |
+
:exception OSError: If the parser failed to parse the image file either
|
| 500 |
+
because it cannot be identified or cannot be
|
| 501 |
+
decoded.
|
| 502 |
+
"""
|
| 503 |
+
# finish decoding
|
| 504 |
+
if self.decoder:
|
| 505 |
+
# get rid of what's left in the buffers
|
| 506 |
+
self.feed(b"")
|
| 507 |
+
self.data = self.decoder = None
|
| 508 |
+
if not self.finished:
|
| 509 |
+
msg = "image was incomplete"
|
| 510 |
+
raise OSError(msg)
|
| 511 |
+
if not self.image:
|
| 512 |
+
msg = "cannot parse this image"
|
| 513 |
+
raise OSError(msg)
|
| 514 |
+
if self.data:
|
| 515 |
+
# incremental parsing not possible; reopen the file
|
| 516 |
+
# not that we have all data
|
| 517 |
+
with io.BytesIO(self.data) as fp:
|
| 518 |
+
try:
|
| 519 |
+
self.image = Image.open(fp)
|
| 520 |
+
finally:
|
| 521 |
+
self.image.load()
|
| 522 |
+
return self.image
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
# --------------------------------------------------------------------
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _save(im, fp, tile, bufsize=0) -> None:
|
| 529 |
+
"""Helper to save image based on tile list
|
| 530 |
+
|
| 531 |
+
:param im: Image object.
|
| 532 |
+
:param fp: File object.
|
| 533 |
+
:param tile: Tile list.
|
| 534 |
+
:param bufsize: Optional buffer size
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
im.load()
|
| 538 |
+
if not hasattr(im, "encoderconfig"):
|
| 539 |
+
im.encoderconfig = ()
|
| 540 |
+
tile.sort(key=_tilesort)
|
| 541 |
+
# FIXME: make MAXBLOCK a configuration parameter
|
| 542 |
+
# It would be great if we could have the encoder specify what it needs
|
| 543 |
+
# But, it would need at least the image size in most cases. RawEncode is
|
| 544 |
+
# a tricky case.
|
| 545 |
+
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
|
| 546 |
+
try:
|
| 547 |
+
fh = fp.fileno()
|
| 548 |
+
fp.flush()
|
| 549 |
+
_encode_tile(im, fp, tile, bufsize, fh)
|
| 550 |
+
except (AttributeError, io.UnsupportedOperation) as exc:
|
| 551 |
+
_encode_tile(im, fp, tile, bufsize, None, exc)
|
| 552 |
+
if hasattr(fp, "flush"):
|
| 553 |
+
fp.flush()
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _encode_tile(im, fp, tile: list[_Tile], bufsize, fh, exc=None):
|
| 557 |
+
for encoder_name, extents, offset, args in tile:
|
| 558 |
+
if offset > 0:
|
| 559 |
+
fp.seek(offset)
|
| 560 |
+
encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
|
| 561 |
+
try:
|
| 562 |
+
encoder.setimage(im.im, extents)
|
| 563 |
+
if encoder.pushes_fd:
|
| 564 |
+
encoder.setfd(fp)
|
| 565 |
+
errcode = encoder.encode_to_pyfd()[1]
|
| 566 |
+
else:
|
| 567 |
+
if exc:
|
| 568 |
+
# compress to Python file-compatible object
|
| 569 |
+
while True:
|
| 570 |
+
errcode, data = encoder.encode(bufsize)[1:]
|
| 571 |
+
fp.write(data)
|
| 572 |
+
if errcode:
|
| 573 |
+
break
|
| 574 |
+
else:
|
| 575 |
+
# slight speedup: compress to real file object
|
| 576 |
+
errcode = encoder.encode_to_file(fh, bufsize)
|
| 577 |
+
if errcode < 0:
|
| 578 |
+
raise _get_oserror(errcode, encoder=True) from exc
|
| 579 |
+
finally:
|
| 580 |
+
encoder.cleanup()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _safe_read(fp, size):
|
| 584 |
+
"""
|
| 585 |
+
Reads large blocks in a safe way. Unlike fp.read(n), this function
|
| 586 |
+
doesn't trust the user. If the requested size is larger than
|
| 587 |
+
SAFEBLOCK, the file is read block by block.
|
| 588 |
+
|
| 589 |
+
:param fp: File handle. Must implement a <b>read</b> method.
|
| 590 |
+
:param size: Number of bytes to read.
|
| 591 |
+
:returns: A string containing <i>size</i> bytes of data.
|
| 592 |
+
|
| 593 |
+
Raises an OSError if the file is truncated and the read cannot be completed
|
| 594 |
+
|
| 595 |
+
"""
|
| 596 |
+
if size <= 0:
|
| 597 |
+
return b""
|
| 598 |
+
if size <= SAFEBLOCK:
|
| 599 |
+
data = fp.read(size)
|
| 600 |
+
if len(data) < size:
|
| 601 |
+
msg = "Truncated File Read"
|
| 602 |
+
raise OSError(msg)
|
| 603 |
+
return data
|
| 604 |
+
data = []
|
| 605 |
+
remaining_size = size
|
| 606 |
+
while remaining_size > 0:
|
| 607 |
+
block = fp.read(min(remaining_size, SAFEBLOCK))
|
| 608 |
+
if not block:
|
| 609 |
+
break
|
| 610 |
+
data.append(block)
|
| 611 |
+
remaining_size -= len(block)
|
| 612 |
+
if sum(len(d) for d in data) < size:
|
| 613 |
+
msg = "Truncated File Read"
|
| 614 |
+
raise OSError(msg)
|
| 615 |
+
return b"".join(data)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class PyCodecState:
|
| 619 |
+
def __init__(self) -> None:
|
| 620 |
+
self.xsize = 0
|
| 621 |
+
self.ysize = 0
|
| 622 |
+
self.xoff = 0
|
| 623 |
+
self.yoff = 0
|
| 624 |
+
|
| 625 |
+
def extents(self) -> tuple[int, int, int, int]:
|
| 626 |
+
return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class PyCodec:
|
| 630 |
+
fd: IO[bytes] | None
|
| 631 |
+
|
| 632 |
+
def __init__(self, mode, *args):
|
| 633 |
+
self.im = None
|
| 634 |
+
self.state = PyCodecState()
|
| 635 |
+
self.fd = None
|
| 636 |
+
self.mode = mode
|
| 637 |
+
self.init(args)
|
| 638 |
+
|
| 639 |
+
def init(self, args):
|
| 640 |
+
"""
|
| 641 |
+
Override to perform codec specific initialization
|
| 642 |
+
|
| 643 |
+
:param args: Array of args items from the tile entry
|
| 644 |
+
:returns: None
|
| 645 |
+
"""
|
| 646 |
+
self.args = args
|
| 647 |
+
|
| 648 |
+
def cleanup(self) -> None:
|
| 649 |
+
"""
|
| 650 |
+
Override to perform codec specific cleanup
|
| 651 |
+
|
| 652 |
+
:returns: None
|
| 653 |
+
"""
|
| 654 |
+
pass
|
| 655 |
+
|
| 656 |
+
def setfd(self, fd):
|
| 657 |
+
"""
|
| 658 |
+
Called from ImageFile to set the Python file-like object
|
| 659 |
+
|
| 660 |
+
:param fd: A Python file-like object
|
| 661 |
+
:returns: None
|
| 662 |
+
"""
|
| 663 |
+
self.fd = fd
|
| 664 |
+
|
| 665 |
+
def setimage(self, im, extents: tuple[int, int, int, int] | None = None) -> None:
|
| 666 |
+
"""
|
| 667 |
+
Called from ImageFile to set the core output image for the codec
|
| 668 |
+
|
| 669 |
+
:param im: A core image object
|
| 670 |
+
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
|
| 671 |
+
for this tile
|
| 672 |
+
:returns: None
|
| 673 |
+
"""
|
| 674 |
+
|
| 675 |
+
# following c code
|
| 676 |
+
self.im = im
|
| 677 |
+
|
| 678 |
+
if extents:
|
| 679 |
+
(x0, y0, x1, y1) = extents
|
| 680 |
+
else:
|
| 681 |
+
(x0, y0, x1, y1) = (0, 0, 0, 0)
|
| 682 |
+
|
| 683 |
+
if x0 == 0 and x1 == 0:
|
| 684 |
+
self.state.xsize, self.state.ysize = self.im.size
|
| 685 |
+
else:
|
| 686 |
+
self.state.xoff = x0
|
| 687 |
+
self.state.yoff = y0
|
| 688 |
+
self.state.xsize = x1 - x0
|
| 689 |
+
self.state.ysize = y1 - y0
|
| 690 |
+
|
| 691 |
+
if self.state.xsize <= 0 or self.state.ysize <= 0:
|
| 692 |
+
msg = "Size cannot be negative"
|
| 693 |
+
raise ValueError(msg)
|
| 694 |
+
|
| 695 |
+
if (
|
| 696 |
+
self.state.xsize + self.state.xoff > self.im.size[0]
|
| 697 |
+
or self.state.ysize + self.state.yoff > self.im.size[1]
|
| 698 |
+
):
|
| 699 |
+
msg = "Tile cannot extend outside image"
|
| 700 |
+
raise ValueError(msg)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class PyDecoder(PyCodec):
|
| 704 |
+
"""
|
| 705 |
+
Python implementation of a format decoder. Override this class and
|
| 706 |
+
add the decoding logic in the :meth:`decode` method.
|
| 707 |
+
|
| 708 |
+
See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
|
| 709 |
+
"""
|
| 710 |
+
|
| 711 |
+
_pulls_fd = False
|
| 712 |
+
|
| 713 |
+
@property
|
| 714 |
+
def pulls_fd(self) -> bool:
|
| 715 |
+
return self._pulls_fd
|
| 716 |
+
|
| 717 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 718 |
+
"""
|
| 719 |
+
Override to perform the decoding process.
|
| 720 |
+
|
| 721 |
+
:param buffer: A bytes object with the data to be decoded.
|
| 722 |
+
:returns: A tuple of ``(bytes consumed, errcode)``.
|
| 723 |
+
If finished with decoding return -1 for the bytes consumed.
|
| 724 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
| 725 |
+
"""
|
| 726 |
+
msg = "unavailable in base decoder"
|
| 727 |
+
raise NotImplementedError(msg)
|
| 728 |
+
|
| 729 |
+
def set_as_raw(self, data: bytes, rawmode=None) -> None:
|
| 730 |
+
"""
|
| 731 |
+
Convenience method to set the internal image from a stream of raw data
|
| 732 |
+
|
| 733 |
+
:param data: Bytes to be set
|
| 734 |
+
:param rawmode: The rawmode to be used for the decoder.
|
| 735 |
+
If not specified, it will default to the mode of the image
|
| 736 |
+
:returns: None
|
| 737 |
+
"""
|
| 738 |
+
|
| 739 |
+
if not rawmode:
|
| 740 |
+
rawmode = self.mode
|
| 741 |
+
d = Image._getdecoder(self.mode, "raw", rawmode)
|
| 742 |
+
assert self.im is not None
|
| 743 |
+
d.setimage(self.im, self.state.extents())
|
| 744 |
+
s = d.decode(data)
|
| 745 |
+
|
| 746 |
+
if s[0] >= 0:
|
| 747 |
+
msg = "not enough image data"
|
| 748 |
+
raise ValueError(msg)
|
| 749 |
+
if s[1] != 0:
|
| 750 |
+
msg = "cannot decode image data"
|
| 751 |
+
raise ValueError(msg)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class PyEncoder(PyCodec):
|
| 755 |
+
"""
|
| 756 |
+
Python implementation of a format encoder. Override this class and
|
| 757 |
+
add the decoding logic in the :meth:`encode` method.
|
| 758 |
+
|
| 759 |
+
See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
_pushes_fd = False
|
| 763 |
+
|
| 764 |
+
@property
|
| 765 |
+
def pushes_fd(self) -> bool:
|
| 766 |
+
return self._pushes_fd
|
| 767 |
+
|
| 768 |
+
def encode(self, bufsize: int) -> tuple[int, int, bytes]:
|
| 769 |
+
"""
|
| 770 |
+
Override to perform the encoding process.
|
| 771 |
+
|
| 772 |
+
:param bufsize: Buffer size.
|
| 773 |
+
:returns: A tuple of ``(bytes encoded, errcode, bytes)``.
|
| 774 |
+
If finished with encoding return 1 for the error code.
|
| 775 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
| 776 |
+
"""
|
| 777 |
+
msg = "unavailable in base encoder"
|
| 778 |
+
raise NotImplementedError(msg)
|
| 779 |
+
|
| 780 |
+
def encode_to_pyfd(self) -> tuple[int, int]:
|
| 781 |
+
"""
|
| 782 |
+
If ``pushes_fd`` is ``True``, then this method will be used,
|
| 783 |
+
and ``encode()`` will only be called once.
|
| 784 |
+
|
| 785 |
+
:returns: A tuple of ``(bytes consumed, errcode)``.
|
| 786 |
+
Err codes are from :data:`.ImageFile.ERRORS`.
|
| 787 |
+
"""
|
| 788 |
+
if not self.pushes_fd:
|
| 789 |
+
return 0, -8 # bad configuration
|
| 790 |
+
bytes_consumed, errcode, data = self.encode(0)
|
| 791 |
+
if data:
|
| 792 |
+
assert self.fd is not None
|
| 793 |
+
self.fd.write(data)
|
| 794 |
+
return bytes_consumed, errcode
|
| 795 |
+
|
| 796 |
+
def encode_to_file(self, fh, bufsize):
|
| 797 |
+
"""
|
| 798 |
+
:param fh: File handle.
|
| 799 |
+
:param bufsize: Buffer size.
|
| 800 |
+
|
| 801 |
+
:returns: If finished successfully, return 0.
|
| 802 |
+
Otherwise, return an error code. Err codes are from
|
| 803 |
+
:data:`.ImageFile.ERRORS`.
|
| 804 |
+
"""
|
| 805 |
+
errcode = 0
|
| 806 |
+
while errcode == 0:
|
| 807 |
+
status, errcode, buf = self.encode(bufsize)
|
| 808 |
+
if status > 0:
|
| 809 |
+
fh.write(buf[status:])
|
| 810 |
+
return errcode
|
valley/lib/python3.10/site-packages/PIL/ImageFont.py
ADDED
|
@@ -0,0 +1,1290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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adjustments to handle fonts from pilfont 0.3
|
| 10 |
+
# 1999-02-06 fl rewrote most font management stuff in C
|
| 11 |
+
# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
|
| 12 |
+
# 2001-02-17 fl added freetype support
|
| 13 |
+
# 2001-05-09 fl added TransposedFont wrapper class
|
| 14 |
+
# 2002-03-04 fl make sure we have a "L" or "1" font
|
| 15 |
+
# 2002-12-04 fl skip non-directory entries in the system path
|
| 16 |
+
# 2003-04-29 fl add embedded default font
|
| 17 |
+
# 2003-09-27 fl added support for truetype charmap encodings
|
| 18 |
+
#
|
| 19 |
+
# Todo:
|
| 20 |
+
# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB
|
| 23 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import base64
|
| 31 |
+
import os
|
| 32 |
+
import sys
|
| 33 |
+
import warnings
|
| 34 |
+
from enum import IntEnum
|
| 35 |
+
from io import BytesIO
|
| 36 |
+
from types import ModuleType
|
| 37 |
+
from typing import IO, TYPE_CHECKING, Any, BinaryIO
|
| 38 |
+
|
| 39 |
+
from . import Image
|
| 40 |
+
from ._typing import StrOrBytesPath
|
| 41 |
+
from ._util import DeferredError, is_path
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING:
|
| 44 |
+
from . import ImageFile
|
| 45 |
+
from ._imaging import ImagingFont
|
| 46 |
+
from ._imagingft import Font
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Layout(IntEnum):
|
| 50 |
+
BASIC = 0
|
| 51 |
+
RAQM = 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
MAX_STRING_LENGTH = 1_000_000
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
core: ModuleType | DeferredError
|
| 58 |
+
try:
|
| 59 |
+
from . import _imagingft as core
|
| 60 |
+
except ImportError as ex:
|
| 61 |
+
core = DeferredError.new(ex)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _string_length_check(text: str | bytes | bytearray) -> None:
|
| 65 |
+
if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
|
| 66 |
+
msg = "too many characters in string"
|
| 67 |
+
raise ValueError(msg)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# FIXME: add support for pilfont2 format (see FontFile.py)
|
| 71 |
+
|
| 72 |
+
# --------------------------------------------------------------------
|
| 73 |
+
# Font metrics format:
|
| 74 |
+
# "PILfont" LF
|
| 75 |
+
# fontdescriptor LF
|
| 76 |
+
# (optional) key=value... LF
|
| 77 |
+
# "DATA" LF
|
| 78 |
+
# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
|
| 79 |
+
#
|
| 80 |
+
# To place a character, cut out srcbox and paste at dstbox,
|
| 81 |
+
# relative to the character position. Then move the character
|
| 82 |
+
# position according to dx, dy.
|
| 83 |
+
# --------------------------------------------------------------------
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ImageFont:
|
| 87 |
+
"""PIL font wrapper"""
|
| 88 |
+
|
| 89 |
+
font: ImagingFont
|
| 90 |
+
|
| 91 |
+
def _load_pilfont(self, filename: str) -> None:
|
| 92 |
+
with open(filename, "rb") as fp:
|
| 93 |
+
image: ImageFile.ImageFile | None = None
|
| 94 |
+
for ext in (".png", ".gif", ".pbm"):
|
| 95 |
+
if image:
|
| 96 |
+
image.close()
|
| 97 |
+
try:
|
| 98 |
+
fullname = os.path.splitext(filename)[0] + ext
|
| 99 |
+
image = Image.open(fullname)
|
| 100 |
+
except Exception:
|
| 101 |
+
pass
|
| 102 |
+
else:
|
| 103 |
+
if image and image.mode in ("1", "L"):
|
| 104 |
+
break
|
| 105 |
+
else:
|
| 106 |
+
if image:
|
| 107 |
+
image.close()
|
| 108 |
+
msg = "cannot find glyph data file"
|
| 109 |
+
raise OSError(msg)
|
| 110 |
+
|
| 111 |
+
self.file = fullname
|
| 112 |
+
|
| 113 |
+
self._load_pilfont_data(fp, image)
|
| 114 |
+
image.close()
|
| 115 |
+
|
| 116 |
+
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
|
| 117 |
+
# read PILfont header
|
| 118 |
+
if file.readline() != b"PILfont\n":
|
| 119 |
+
msg = "Not a PILfont file"
|
| 120 |
+
raise SyntaxError(msg)
|
| 121 |
+
file.readline().split(b";")
|
| 122 |
+
self.info = [] # FIXME: should be a dictionary
|
| 123 |
+
while True:
|
| 124 |
+
s = file.readline()
|
| 125 |
+
if not s or s == b"DATA\n":
|
| 126 |
+
break
|
| 127 |
+
self.info.append(s)
|
| 128 |
+
|
| 129 |
+
# read PILfont metrics
|
| 130 |
+
data = file.read(256 * 20)
|
| 131 |
+
|
| 132 |
+
# check image
|
| 133 |
+
if image.mode not in ("1", "L"):
|
| 134 |
+
msg = "invalid font image mode"
|
| 135 |
+
raise TypeError(msg)
|
| 136 |
+
|
| 137 |
+
image.load()
|
| 138 |
+
|
| 139 |
+
self.font = Image.core.font(image.im, data)
|
| 140 |
+
|
| 141 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
| 142 |
+
"""
|
| 143 |
+
Create a bitmap for the text.
|
| 144 |
+
|
| 145 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 146 |
+
maximum value of 255. Otherwise, it should have mode ``1``.
|
| 147 |
+
|
| 148 |
+
:param text: Text to render.
|
| 149 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 150 |
+
driver prefers; if empty, the renderer may return either
|
| 151 |
+
mode. Note that the mode is always a string, to simplify
|
| 152 |
+
C-level implementations.
|
| 153 |
+
|
| 154 |
+
.. versionadded:: 1.1.5
|
| 155 |
+
|
| 156 |
+
:return: An internal PIL storage memory instance as defined by the
|
| 157 |
+
:py:mod:`PIL.Image.core` interface module.
|
| 158 |
+
"""
|
| 159 |
+
_string_length_check(text)
|
| 160 |
+
Image._decompression_bomb_check(self.font.getsize(text))
|
| 161 |
+
return self.font.getmask(text, mode)
|
| 162 |
+
|
| 163 |
+
def getbbox(
|
| 164 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
| 165 |
+
) -> tuple[int, int, int, int]:
|
| 166 |
+
"""
|
| 167 |
+
Returns bounding box (in pixels) of given text.
|
| 168 |
+
|
| 169 |
+
.. versionadded:: 9.2.0
|
| 170 |
+
|
| 171 |
+
:param text: Text to render.
|
| 172 |
+
|
| 173 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 174 |
+
"""
|
| 175 |
+
_string_length_check(text)
|
| 176 |
+
width, height = self.font.getsize(text)
|
| 177 |
+
return 0, 0, width, height
|
| 178 |
+
|
| 179 |
+
def getlength(
|
| 180 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
| 181 |
+
) -> int:
|
| 182 |
+
"""
|
| 183 |
+
Returns length (in pixels) of given text.
|
| 184 |
+
This is the amount by which following text should be offset.
|
| 185 |
+
|
| 186 |
+
.. versionadded:: 9.2.0
|
| 187 |
+
"""
|
| 188 |
+
_string_length_check(text)
|
| 189 |
+
width, height = self.font.getsize(text)
|
| 190 |
+
return width
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
##
|
| 194 |
+
# Wrapper for FreeType fonts. Application code should use the
|
| 195 |
+
# <b>truetype</b> factory function to create font objects.
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class FreeTypeFont:
|
| 199 |
+
"""FreeType font wrapper (requires _imagingft service)"""
|
| 200 |
+
|
| 201 |
+
font: Font
|
| 202 |
+
font_bytes: bytes
|
| 203 |
+
|
| 204 |
+
def __init__(
|
| 205 |
+
self,
|
| 206 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
| 207 |
+
size: float = 10,
|
| 208 |
+
index: int = 0,
|
| 209 |
+
encoding: str = "",
|
| 210 |
+
layout_engine: Layout | None = None,
|
| 211 |
+
) -> None:
|
| 212 |
+
# FIXME: use service provider instead
|
| 213 |
+
|
| 214 |
+
if isinstance(core, DeferredError):
|
| 215 |
+
raise core.ex
|
| 216 |
+
|
| 217 |
+
if size <= 0:
|
| 218 |
+
msg = "font size must be greater than 0"
|
| 219 |
+
raise ValueError(msg)
|
| 220 |
+
|
| 221 |
+
self.path = font
|
| 222 |
+
self.size = size
|
| 223 |
+
self.index = index
|
| 224 |
+
self.encoding = encoding
|
| 225 |
+
|
| 226 |
+
if layout_engine not in (Layout.BASIC, Layout.RAQM):
|
| 227 |
+
layout_engine = Layout.BASIC
|
| 228 |
+
if core.HAVE_RAQM:
|
| 229 |
+
layout_engine = Layout.RAQM
|
| 230 |
+
elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
|
| 231 |
+
warnings.warn(
|
| 232 |
+
"Raqm layout was requested, but Raqm is not available. "
|
| 233 |
+
"Falling back to basic layout."
|
| 234 |
+
)
|
| 235 |
+
layout_engine = Layout.BASIC
|
| 236 |
+
|
| 237 |
+
self.layout_engine = layout_engine
|
| 238 |
+
|
| 239 |
+
def load_from_bytes(f):
|
| 240 |
+
self.font_bytes = f.read()
|
| 241 |
+
self.font = core.getfont(
|
| 242 |
+
"", size, index, encoding, self.font_bytes, layout_engine
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
if is_path(font):
|
| 246 |
+
font = os.path.realpath(os.fspath(font))
|
| 247 |
+
if sys.platform == "win32":
|
| 248 |
+
font_bytes_path = font if isinstance(font, bytes) else font.encode()
|
| 249 |
+
try:
|
| 250 |
+
font_bytes_path.decode("ascii")
|
| 251 |
+
except UnicodeDecodeError:
|
| 252 |
+
# FreeType cannot load fonts with non-ASCII characters on Windows
|
| 253 |
+
# So load it into memory first
|
| 254 |
+
with open(font, "rb") as f:
|
| 255 |
+
load_from_bytes(f)
|
| 256 |
+
return
|
| 257 |
+
self.font = core.getfont(
|
| 258 |
+
font, size, index, encoding, layout_engine=layout_engine
|
| 259 |
+
)
|
| 260 |
+
else:
|
| 261 |
+
load_from_bytes(font)
|
| 262 |
+
|
| 263 |
+
def __getstate__(self):
|
| 264 |
+
return [self.path, self.size, self.index, self.encoding, self.layout_engine]
|
| 265 |
+
|
| 266 |
+
def __setstate__(self, state):
|
| 267 |
+
path, size, index, encoding, layout_engine = state
|
| 268 |
+
self.__init__(path, size, index, encoding, layout_engine)
|
| 269 |
+
|
| 270 |
+
def getname(self) -> tuple[str | None, str | None]:
|
| 271 |
+
"""
|
| 272 |
+
:return: A tuple of the font family (e.g. Helvetica) and the font style
|
| 273 |
+
(e.g. Bold)
|
| 274 |
+
"""
|
| 275 |
+
return self.font.family, self.font.style
|
| 276 |
+
|
| 277 |
+
def getmetrics(self) -> tuple[int, int]:
|
| 278 |
+
"""
|
| 279 |
+
:return: A tuple of the font ascent (the distance from the baseline to
|
| 280 |
+
the highest outline point) and descent (the distance from the
|
| 281 |
+
baseline to the lowest outline point, a negative value)
|
| 282 |
+
"""
|
| 283 |
+
return self.font.ascent, self.font.descent
|
| 284 |
+
|
| 285 |
+
def getlength(
|
| 286 |
+
self, text: str | bytes, mode="", direction=None, features=None, language=None
|
| 287 |
+
) -> float:
|
| 288 |
+
"""
|
| 289 |
+
Returns length (in pixels with 1/64 precision) of given text when rendered
|
| 290 |
+
in font with provided direction, features, and language.
|
| 291 |
+
|
| 292 |
+
This is the amount by which following text should be offset.
|
| 293 |
+
Text bounding box may extend past the length in some fonts,
|
| 294 |
+
e.g. when using italics or accents.
|
| 295 |
+
|
| 296 |
+
The result is returned as a float; it is a whole number if using basic layout.
|
| 297 |
+
|
| 298 |
+
Note that the sum of two lengths may not equal the length of a concatenated
|
| 299 |
+
string due to kerning. If you need to adjust for kerning, include the following
|
| 300 |
+
character and subtract its length.
|
| 301 |
+
|
| 302 |
+
For example, instead of ::
|
| 303 |
+
|
| 304 |
+
hello = font.getlength("Hello")
|
| 305 |
+
world = font.getlength("World")
|
| 306 |
+
hello_world = hello + world # not adjusted for kerning
|
| 307 |
+
assert hello_world == font.getlength("HelloWorld") # may fail
|
| 308 |
+
|
| 309 |
+
use ::
|
| 310 |
+
|
| 311 |
+
hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
|
| 312 |
+
world = font.getlength("World")
|
| 313 |
+
hello_world = hello + world # adjusted for kerning
|
| 314 |
+
assert hello_world == font.getlength("HelloWorld") # True
|
| 315 |
+
|
| 316 |
+
or disable kerning with (requires libraqm) ::
|
| 317 |
+
|
| 318 |
+
hello = draw.textlength("Hello", font, features=["-kern"])
|
| 319 |
+
world = draw.textlength("World", font, features=["-kern"])
|
| 320 |
+
hello_world = hello + world # kerning is disabled, no need to adjust
|
| 321 |
+
assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
|
| 322 |
+
|
| 323 |
+
.. versionadded:: 8.0.0
|
| 324 |
+
|
| 325 |
+
:param text: Text to measure.
|
| 326 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 327 |
+
driver prefers; if empty, the renderer may return either
|
| 328 |
+
mode. Note that the mode is always a string, to simplify
|
| 329 |
+
C-level implementations.
|
| 330 |
+
|
| 331 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 332 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 333 |
+
Requires libraqm.
|
| 334 |
+
|
| 335 |
+
:param features: A list of OpenType font features to be used during text
|
| 336 |
+
layout. This is usually used to turn on optional
|
| 337 |
+
font features that are not enabled by default,
|
| 338 |
+
for example 'dlig' or 'ss01', but can be also
|
| 339 |
+
used to turn off default font features for
|
| 340 |
+
example '-liga' to disable ligatures or '-kern'
|
| 341 |
+
to disable kerning. To get all supported
|
| 342 |
+
features, see
|
| 343 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 344 |
+
Requires libraqm.
|
| 345 |
+
|
| 346 |
+
:param language: Language of the text. Different languages may use
|
| 347 |
+
different glyph shapes or ligatures. This parameter tells
|
| 348 |
+
the font which language the text is in, and to apply the
|
| 349 |
+
correct substitutions as appropriate, if available.
|
| 350 |
+
It should be a `BCP 47 language code
|
| 351 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 352 |
+
Requires libraqm.
|
| 353 |
+
|
| 354 |
+
:return: Either width for horizontal text, or height for vertical text.
|
| 355 |
+
"""
|
| 356 |
+
_string_length_check(text)
|
| 357 |
+
return self.font.getlength(text, mode, direction, features, language) / 64
|
| 358 |
+
|
| 359 |
+
def getbbox(
|
| 360 |
+
self,
|
| 361 |
+
text: str | bytes,
|
| 362 |
+
mode: str = "",
|
| 363 |
+
direction: str | None = None,
|
| 364 |
+
features: list[str] | None = None,
|
| 365 |
+
language: str | None = None,
|
| 366 |
+
stroke_width: float = 0,
|
| 367 |
+
anchor: str | None = None,
|
| 368 |
+
) -> tuple[float, float, float, float]:
|
| 369 |
+
"""
|
| 370 |
+
Returns bounding box (in pixels) of given text relative to given anchor
|
| 371 |
+
when rendered in font with provided direction, features, and language.
|
| 372 |
+
|
| 373 |
+
Use :py:meth:`getlength()` to get the offset of following text with
|
| 374 |
+
1/64 pixel precision. The bounding box includes extra margins for
|
| 375 |
+
some fonts, e.g. italics or accents.
|
| 376 |
+
|
| 377 |
+
.. versionadded:: 8.0.0
|
| 378 |
+
|
| 379 |
+
:param text: Text to render.
|
| 380 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 381 |
+
driver prefers; if empty, the renderer may return either
|
| 382 |
+
mode. Note that the mode is always a string, to simplify
|
| 383 |
+
C-level implementations.
|
| 384 |
+
|
| 385 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 386 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 387 |
+
Requires libraqm.
|
| 388 |
+
|
| 389 |
+
:param features: A list of OpenType font features to be used during text
|
| 390 |
+
layout. This is usually used to turn on optional
|
| 391 |
+
font features that are not enabled by default,
|
| 392 |
+
for example 'dlig' or 'ss01', but can be also
|
| 393 |
+
used to turn off default font features for
|
| 394 |
+
example '-liga' to disable ligatures or '-kern'
|
| 395 |
+
to disable kerning. To get all supported
|
| 396 |
+
features, see
|
| 397 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 398 |
+
Requires libraqm.
|
| 399 |
+
|
| 400 |
+
:param language: Language of the text. Different languages may use
|
| 401 |
+
different glyph shapes or ligatures. This parameter tells
|
| 402 |
+
the font which language the text is in, and to apply the
|
| 403 |
+
correct substitutions as appropriate, if available.
|
| 404 |
+
It should be a `BCP 47 language code
|
| 405 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 406 |
+
Requires libraqm.
|
| 407 |
+
|
| 408 |
+
:param stroke_width: The width of the text stroke.
|
| 409 |
+
|
| 410 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 411 |
+
the anchor to the text. The default alignment is top left,
|
| 412 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 413 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 414 |
+
|
| 415 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 416 |
+
"""
|
| 417 |
+
_string_length_check(text)
|
| 418 |
+
size, offset = self.font.getsize(
|
| 419 |
+
text, mode, direction, features, language, anchor
|
| 420 |
+
)
|
| 421 |
+
left, top = offset[0] - stroke_width, offset[1] - stroke_width
|
| 422 |
+
width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
|
| 423 |
+
return left, top, left + width, top + height
|
| 424 |
+
|
| 425 |
+
def getmask(
|
| 426 |
+
self,
|
| 427 |
+
text,
|
| 428 |
+
mode="",
|
| 429 |
+
direction=None,
|
| 430 |
+
features=None,
|
| 431 |
+
language=None,
|
| 432 |
+
stroke_width=0,
|
| 433 |
+
anchor=None,
|
| 434 |
+
ink=0,
|
| 435 |
+
start=None,
|
| 436 |
+
):
|
| 437 |
+
"""
|
| 438 |
+
Create a bitmap for the text.
|
| 439 |
+
|
| 440 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 441 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
| 442 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
| 443 |
+
|
| 444 |
+
:param text: Text to render.
|
| 445 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 446 |
+
driver prefers; if empty, the renderer may return either
|
| 447 |
+
mode. Note that the mode is always a string, to simplify
|
| 448 |
+
C-level implementations.
|
| 449 |
+
|
| 450 |
+
.. versionadded:: 1.1.5
|
| 451 |
+
|
| 452 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 453 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 454 |
+
Requires libraqm.
|
| 455 |
+
|
| 456 |
+
.. versionadded:: 4.2.0
|
| 457 |
+
|
| 458 |
+
:param features: A list of OpenType font features to be used during text
|
| 459 |
+
layout. This is usually used to turn on optional
|
| 460 |
+
font features that are not enabled by default,
|
| 461 |
+
for example 'dlig' or 'ss01', but can be also
|
| 462 |
+
used to turn off default font features for
|
| 463 |
+
example '-liga' to disable ligatures or '-kern'
|
| 464 |
+
to disable kerning. To get all supported
|
| 465 |
+
features, see
|
| 466 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 467 |
+
Requires libraqm.
|
| 468 |
+
|
| 469 |
+
.. versionadded:: 4.2.0
|
| 470 |
+
|
| 471 |
+
:param language: Language of the text. Different languages may use
|
| 472 |
+
different glyph shapes or ligatures. This parameter tells
|
| 473 |
+
the font which language the text is in, and to apply the
|
| 474 |
+
correct substitutions as appropriate, if available.
|
| 475 |
+
It should be a `BCP 47 language code
|
| 476 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 477 |
+
Requires libraqm.
|
| 478 |
+
|
| 479 |
+
.. versionadded:: 6.0.0
|
| 480 |
+
|
| 481 |
+
:param stroke_width: The width of the text stroke.
|
| 482 |
+
|
| 483 |
+
.. versionadded:: 6.2.0
|
| 484 |
+
|
| 485 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 486 |
+
the anchor to the text. The default alignment is top left,
|
| 487 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 488 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 489 |
+
|
| 490 |
+
.. versionadded:: 8.0.0
|
| 491 |
+
|
| 492 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
| 493 |
+
|
| 494 |
+
.. versionadded:: 8.0.0
|
| 495 |
+
|
| 496 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
| 497 |
+
differently when starting at fractional coordinates.
|
| 498 |
+
|
| 499 |
+
.. versionadded:: 9.4.0
|
| 500 |
+
|
| 501 |
+
:return: An internal PIL storage memory instance as defined by the
|
| 502 |
+
:py:mod:`PIL.Image.core` interface module.
|
| 503 |
+
"""
|
| 504 |
+
return self.getmask2(
|
| 505 |
+
text,
|
| 506 |
+
mode,
|
| 507 |
+
direction=direction,
|
| 508 |
+
features=features,
|
| 509 |
+
language=language,
|
| 510 |
+
stroke_width=stroke_width,
|
| 511 |
+
anchor=anchor,
|
| 512 |
+
ink=ink,
|
| 513 |
+
start=start,
|
| 514 |
+
)[0]
|
| 515 |
+
|
| 516 |
+
def getmask2(
|
| 517 |
+
self,
|
| 518 |
+
text: str | bytes,
|
| 519 |
+
mode="",
|
| 520 |
+
direction=None,
|
| 521 |
+
features=None,
|
| 522 |
+
language=None,
|
| 523 |
+
stroke_width=0,
|
| 524 |
+
anchor=None,
|
| 525 |
+
ink=0,
|
| 526 |
+
start=None,
|
| 527 |
+
*args,
|
| 528 |
+
**kwargs,
|
| 529 |
+
):
|
| 530 |
+
"""
|
| 531 |
+
Create a bitmap for the text.
|
| 532 |
+
|
| 533 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 534 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
| 535 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
| 536 |
+
|
| 537 |
+
:param text: Text to render.
|
| 538 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 539 |
+
driver prefers; if empty, the renderer may return either
|
| 540 |
+
mode. Note that the mode is always a string, to simplify
|
| 541 |
+
C-level implementations.
|
| 542 |
+
|
| 543 |
+
.. versionadded:: 1.1.5
|
| 544 |
+
|
| 545 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 546 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 547 |
+
Requires libraqm.
|
| 548 |
+
|
| 549 |
+
.. versionadded:: 4.2.0
|
| 550 |
+
|
| 551 |
+
:param features: A list of OpenType font features to be used during text
|
| 552 |
+
layout. This is usually used to turn on optional
|
| 553 |
+
font features that are not enabled by default,
|
| 554 |
+
for example 'dlig' or 'ss01', but can be also
|
| 555 |
+
used to turn off default font features for
|
| 556 |
+
example '-liga' to disable ligatures or '-kern'
|
| 557 |
+
to disable kerning. To get all supported
|
| 558 |
+
features, see
|
| 559 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 560 |
+
Requires libraqm.
|
| 561 |
+
|
| 562 |
+
.. versionadded:: 4.2.0
|
| 563 |
+
|
| 564 |
+
:param language: Language of the text. Different languages may use
|
| 565 |
+
different glyph shapes or ligatures. This parameter tells
|
| 566 |
+
the font which language the text is in, and to apply the
|
| 567 |
+
correct substitutions as appropriate, if available.
|
| 568 |
+
It should be a `BCP 47 language code
|
| 569 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 570 |
+
Requires libraqm.
|
| 571 |
+
|
| 572 |
+
.. versionadded:: 6.0.0
|
| 573 |
+
|
| 574 |
+
:param stroke_width: The width of the text stroke.
|
| 575 |
+
|
| 576 |
+
.. versionadded:: 6.2.0
|
| 577 |
+
|
| 578 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 579 |
+
the anchor to the text. The default alignment is top left,
|
| 580 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 581 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 582 |
+
|
| 583 |
+
.. versionadded:: 8.0.0
|
| 584 |
+
|
| 585 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
| 586 |
+
|
| 587 |
+
.. versionadded:: 8.0.0
|
| 588 |
+
|
| 589 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
| 590 |
+
differently when starting at fractional coordinates.
|
| 591 |
+
|
| 592 |
+
.. versionadded:: 9.4.0
|
| 593 |
+
|
| 594 |
+
:return: A tuple of an internal PIL storage memory instance as defined by the
|
| 595 |
+
:py:mod:`PIL.Image.core` interface module, and the text offset, the
|
| 596 |
+
gap between the starting coordinate and the first marking
|
| 597 |
+
"""
|
| 598 |
+
_string_length_check(text)
|
| 599 |
+
if start is None:
|
| 600 |
+
start = (0, 0)
|
| 601 |
+
|
| 602 |
+
def fill(width, height):
|
| 603 |
+
size = (width, height)
|
| 604 |
+
Image._decompression_bomb_check(size)
|
| 605 |
+
return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
|
| 606 |
+
|
| 607 |
+
return self.font.render(
|
| 608 |
+
text,
|
| 609 |
+
fill,
|
| 610 |
+
mode,
|
| 611 |
+
direction,
|
| 612 |
+
features,
|
| 613 |
+
language,
|
| 614 |
+
stroke_width,
|
| 615 |
+
anchor,
|
| 616 |
+
ink,
|
| 617 |
+
start[0],
|
| 618 |
+
start[1],
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
def font_variant(
|
| 622 |
+
self, font=None, size=None, index=None, encoding=None, layout_engine=None
|
| 623 |
+
):
|
| 624 |
+
"""
|
| 625 |
+
Create a copy of this FreeTypeFont object,
|
| 626 |
+
using any specified arguments to override the settings.
|
| 627 |
+
|
| 628 |
+
Parameters are identical to the parameters used to initialize this
|
| 629 |
+
object.
|
| 630 |
+
|
| 631 |
+
:return: A FreeTypeFont object.
|
| 632 |
+
"""
|
| 633 |
+
if font is None:
|
| 634 |
+
try:
|
| 635 |
+
font = BytesIO(self.font_bytes)
|
| 636 |
+
except AttributeError:
|
| 637 |
+
font = self.path
|
| 638 |
+
return FreeTypeFont(
|
| 639 |
+
font=font,
|
| 640 |
+
size=self.size if size is None else size,
|
| 641 |
+
index=self.index if index is None else index,
|
| 642 |
+
encoding=self.encoding if encoding is None else encoding,
|
| 643 |
+
layout_engine=layout_engine or self.layout_engine,
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
def get_variation_names(self) -> list[bytes]:
|
| 647 |
+
"""
|
| 648 |
+
:returns: A list of the named styles in a variation font.
|
| 649 |
+
:exception OSError: If the font is not a variation font.
|
| 650 |
+
"""
|
| 651 |
+
try:
|
| 652 |
+
names = self.font.getvarnames()
|
| 653 |
+
except AttributeError as e:
|
| 654 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 655 |
+
raise NotImplementedError(msg) from e
|
| 656 |
+
return [name.replace(b"\x00", b"") for name in names]
|
| 657 |
+
|
| 658 |
+
def set_variation_by_name(self, name):
|
| 659 |
+
"""
|
| 660 |
+
:param name: The name of the style.
|
| 661 |
+
:exception OSError: If the font is not a variation font.
|
| 662 |
+
"""
|
| 663 |
+
names = self.get_variation_names()
|
| 664 |
+
if not isinstance(name, bytes):
|
| 665 |
+
name = name.encode()
|
| 666 |
+
index = names.index(name) + 1
|
| 667 |
+
|
| 668 |
+
if index == getattr(self, "_last_variation_index", None):
|
| 669 |
+
# When the same name is set twice in a row,
|
| 670 |
+
# there is an 'unknown freetype error'
|
| 671 |
+
# https://savannah.nongnu.org/bugs/?56186
|
| 672 |
+
return
|
| 673 |
+
self._last_variation_index = index
|
| 674 |
+
|
| 675 |
+
self.font.setvarname(index)
|
| 676 |
+
|
| 677 |
+
def get_variation_axes(self):
|
| 678 |
+
"""
|
| 679 |
+
:returns: A list of the axes in a variation font.
|
| 680 |
+
:exception OSError: If the font is not a variation font.
|
| 681 |
+
"""
|
| 682 |
+
try:
|
| 683 |
+
axes = self.font.getvaraxes()
|
| 684 |
+
except AttributeError as e:
|
| 685 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 686 |
+
raise NotImplementedError(msg) from e
|
| 687 |
+
for axis in axes:
|
| 688 |
+
if axis["name"]:
|
| 689 |
+
axis["name"] = axis["name"].replace(b"\x00", b"")
|
| 690 |
+
return axes
|
| 691 |
+
|
| 692 |
+
def set_variation_by_axes(self, axes: list[float]) -> None:
|
| 693 |
+
"""
|
| 694 |
+
:param axes: A list of values for each axis.
|
| 695 |
+
:exception OSError: If the font is not a variation font.
|
| 696 |
+
"""
|
| 697 |
+
try:
|
| 698 |
+
self.font.setvaraxes(axes)
|
| 699 |
+
except AttributeError as e:
|
| 700 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 701 |
+
raise NotImplementedError(msg) from e
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class TransposedFont:
|
| 705 |
+
"""Wrapper for writing rotated or mirrored text"""
|
| 706 |
+
|
| 707 |
+
def __init__(self, font, orientation=None):
|
| 708 |
+
"""
|
| 709 |
+
Wrapper that creates a transposed font from any existing font
|
| 710 |
+
object.
|
| 711 |
+
|
| 712 |
+
:param font: A font object.
|
| 713 |
+
:param orientation: An optional orientation. If given, this should
|
| 714 |
+
be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
|
| 715 |
+
Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
|
| 716 |
+
Image.Transpose.ROTATE_270.
|
| 717 |
+
"""
|
| 718 |
+
self.font = font
|
| 719 |
+
self.orientation = orientation # any 'transpose' argument, or None
|
| 720 |
+
|
| 721 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
| 722 |
+
im = self.font.getmask(text, mode, *args, **kwargs)
|
| 723 |
+
if self.orientation is not None:
|
| 724 |
+
return im.transpose(self.orientation)
|
| 725 |
+
return im
|
| 726 |
+
|
| 727 |
+
def getbbox(self, text, *args, **kwargs):
|
| 728 |
+
# TransposedFont doesn't support getmask2, move top-left point to (0, 0)
|
| 729 |
+
# this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
|
| 730 |
+
left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
|
| 731 |
+
width = right - left
|
| 732 |
+
height = bottom - top
|
| 733 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
| 734 |
+
return 0, 0, height, width
|
| 735 |
+
return 0, 0, width, height
|
| 736 |
+
|
| 737 |
+
def getlength(self, text: str | bytes, *args, **kwargs) -> float:
|
| 738 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
| 739 |
+
msg = "text length is undefined for text rotated by 90 or 270 degrees"
|
| 740 |
+
raise ValueError(msg)
|
| 741 |
+
return self.font.getlength(text, *args, **kwargs)
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def load(filename: str) -> ImageFont:
|
| 745 |
+
"""
|
| 746 |
+
Load a font file. This function loads a font object from the given
|
| 747 |
+
bitmap font file, and returns the corresponding font object.
|
| 748 |
+
|
| 749 |
+
:param filename: Name of font file.
|
| 750 |
+
:return: A font object.
|
| 751 |
+
:exception OSError: If the file could not be read.
|
| 752 |
+
"""
|
| 753 |
+
f = ImageFont()
|
| 754 |
+
f._load_pilfont(filename)
|
| 755 |
+
return f
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def truetype(
|
| 759 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
| 760 |
+
size: float = 10,
|
| 761 |
+
index: int = 0,
|
| 762 |
+
encoding: str = "",
|
| 763 |
+
layout_engine: Layout | None = None,
|
| 764 |
+
) -> FreeTypeFont:
|
| 765 |
+
"""
|
| 766 |
+
Load a TrueType or OpenType font from a file or file-like object,
|
| 767 |
+
and create a font object.
|
| 768 |
+
This function loads a font object from the given file or file-like
|
| 769 |
+
object, and creates a font object for a font of the given size.
|
| 770 |
+
|
| 771 |
+
Pillow uses FreeType to open font files. On Windows, be aware that FreeType
|
| 772 |
+
will keep the file open as long as the FreeTypeFont object exists. Windows
|
| 773 |
+
limits the number of files that can be open in C at once to 512, so if many
|
| 774 |
+
fonts are opened simultaneously and that limit is approached, an
|
| 775 |
+
``OSError`` may be thrown, reporting that FreeType "cannot open resource".
|
| 776 |
+
A workaround would be to copy the file(s) into memory, and open that instead.
|
| 777 |
+
|
| 778 |
+
This function requires the _imagingft service.
|
| 779 |
+
|
| 780 |
+
:param font: A filename or file-like object containing a TrueType font.
|
| 781 |
+
If the file is not found in this filename, the loader may also
|
| 782 |
+
search in other directories, such as:
|
| 783 |
+
|
| 784 |
+
* The :file:`fonts/` directory on Windows,
|
| 785 |
+
* :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
|
| 786 |
+
and :file:`~/Library/Fonts/` on macOS.
|
| 787 |
+
* :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
|
| 788 |
+
and :file:`/usr/share/fonts` on Linux; or those specified by
|
| 789 |
+
the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
|
| 790 |
+
for user-installed and system-wide fonts, respectively.
|
| 791 |
+
|
| 792 |
+
:param size: The requested size, in pixels.
|
| 793 |
+
:param index: Which font face to load (default is first available face).
|
| 794 |
+
:param encoding: Which font encoding to use (default is Unicode). Possible
|
| 795 |
+
encodings include (see the FreeType documentation for more
|
| 796 |
+
information):
|
| 797 |
+
|
| 798 |
+
* "unic" (Unicode)
|
| 799 |
+
* "symb" (Microsoft Symbol)
|
| 800 |
+
* "ADOB" (Adobe Standard)
|
| 801 |
+
* "ADBE" (Adobe Expert)
|
| 802 |
+
* "ADBC" (Adobe Custom)
|
| 803 |
+
* "armn" (Apple Roman)
|
| 804 |
+
* "sjis" (Shift JIS)
|
| 805 |
+
* "gb " (PRC)
|
| 806 |
+
* "big5"
|
| 807 |
+
* "wans" (Extended Wansung)
|
| 808 |
+
* "joha" (Johab)
|
| 809 |
+
* "lat1" (Latin-1)
|
| 810 |
+
|
| 811 |
+
This specifies the character set to use. It does not alter the
|
| 812 |
+
encoding of any text provided in subsequent operations.
|
| 813 |
+
:param layout_engine: Which layout engine to use, if available:
|
| 814 |
+
:attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
|
| 815 |
+
If it is available, Raqm layout will be used by default.
|
| 816 |
+
Otherwise, basic layout will be used.
|
| 817 |
+
|
| 818 |
+
Raqm layout is recommended for all non-English text. If Raqm layout
|
| 819 |
+
is not required, basic layout will have better performance.
|
| 820 |
+
|
| 821 |
+
You can check support for Raqm layout using
|
| 822 |
+
:py:func:`PIL.features.check_feature` with ``feature="raqm"``.
|
| 823 |
+
|
| 824 |
+
.. versionadded:: 4.2.0
|
| 825 |
+
:return: A font object.
|
| 826 |
+
:exception OSError: If the file could not be read.
|
| 827 |
+
:exception ValueError: If the font size is not greater than zero.
|
| 828 |
+
"""
|
| 829 |
+
|
| 830 |
+
def freetype(font: StrOrBytesPath | BinaryIO | None) -> FreeTypeFont:
|
| 831 |
+
return FreeTypeFont(font, size, index, encoding, layout_engine)
|
| 832 |
+
|
| 833 |
+
try:
|
| 834 |
+
return freetype(font)
|
| 835 |
+
except OSError:
|
| 836 |
+
if not is_path(font):
|
| 837 |
+
raise
|
| 838 |
+
ttf_filename = os.path.basename(font)
|
| 839 |
+
|
| 840 |
+
dirs = []
|
| 841 |
+
if sys.platform == "win32":
|
| 842 |
+
# check the windows font repository
|
| 843 |
+
# NOTE: must use uppercase WINDIR, to work around bugs in
|
| 844 |
+
# 1.5.2's os.environ.get()
|
| 845 |
+
windir = os.environ.get("WINDIR")
|
| 846 |
+
if windir:
|
| 847 |
+
dirs.append(os.path.join(windir, "fonts"))
|
| 848 |
+
elif sys.platform in ("linux", "linux2"):
|
| 849 |
+
data_home = os.environ.get("XDG_DATA_HOME")
|
| 850 |
+
if not data_home:
|
| 851 |
+
# The freedesktop spec defines the following default directory for
|
| 852 |
+
# when XDG_DATA_HOME is unset or empty. This user-level directory
|
| 853 |
+
# takes precedence over system-level directories.
|
| 854 |
+
data_home = os.path.expanduser("~/.local/share")
|
| 855 |
+
xdg_dirs = [data_home]
|
| 856 |
+
|
| 857 |
+
data_dirs = os.environ.get("XDG_DATA_DIRS")
|
| 858 |
+
if not data_dirs:
|
| 859 |
+
# Similarly, defaults are defined for the system-level directories
|
| 860 |
+
data_dirs = "/usr/local/share:/usr/share"
|
| 861 |
+
xdg_dirs += data_dirs.split(":")
|
| 862 |
+
|
| 863 |
+
dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
|
| 864 |
+
elif sys.platform == "darwin":
|
| 865 |
+
dirs += [
|
| 866 |
+
"/Library/Fonts",
|
| 867 |
+
"/System/Library/Fonts",
|
| 868 |
+
os.path.expanduser("~/Library/Fonts"),
|
| 869 |
+
]
|
| 870 |
+
|
| 871 |
+
ext = os.path.splitext(ttf_filename)[1]
|
| 872 |
+
first_font_with_a_different_extension = None
|
| 873 |
+
for directory in dirs:
|
| 874 |
+
for walkroot, walkdir, walkfilenames in os.walk(directory):
|
| 875 |
+
for walkfilename in walkfilenames:
|
| 876 |
+
if ext and walkfilename == ttf_filename:
|
| 877 |
+
return freetype(os.path.join(walkroot, walkfilename))
|
| 878 |
+
elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
|
| 879 |
+
fontpath = os.path.join(walkroot, walkfilename)
|
| 880 |
+
if os.path.splitext(fontpath)[1] == ".ttf":
|
| 881 |
+
return freetype(fontpath)
|
| 882 |
+
if not ext and first_font_with_a_different_extension is None:
|
| 883 |
+
first_font_with_a_different_extension = fontpath
|
| 884 |
+
if first_font_with_a_different_extension:
|
| 885 |
+
return freetype(first_font_with_a_different_extension)
|
| 886 |
+
raise
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def load_path(filename: str | bytes) -> ImageFont:
|
| 890 |
+
"""
|
| 891 |
+
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
|
| 892 |
+
bitmap font along the Python path.
|
| 893 |
+
|
| 894 |
+
:param filename: Name of font file.
|
| 895 |
+
:return: A font object.
|
| 896 |
+
:exception OSError: If the file could not be read.
|
| 897 |
+
"""
|
| 898 |
+
if not isinstance(filename, str):
|
| 899 |
+
filename = filename.decode("utf-8")
|
| 900 |
+
for directory in sys.path:
|
| 901 |
+
try:
|
| 902 |
+
return load(os.path.join(directory, filename))
|
| 903 |
+
except OSError:
|
| 904 |
+
pass
|
| 905 |
+
msg = "cannot find font file"
|
| 906 |
+
raise OSError(msg)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def load_default_imagefont() -> ImageFont:
|
| 910 |
+
f = ImageFont()
|
| 911 |
+
f._load_pilfont_data(
|
| 912 |
+
# courB08
|
| 913 |
+
BytesIO(
|
| 914 |
+
base64.b64decode(
|
| 915 |
+
b"""
|
| 916 |
+
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 917 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 918 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 919 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 920 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 921 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 922 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 923 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 924 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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
+
AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
|
| 938 |
+
/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
|
| 939 |
+
AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
|
| 940 |
+
AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
|
| 941 |
+
AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
|
| 942 |
+
BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
|
| 943 |
+
AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
|
| 944 |
+
2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
|
| 945 |
+
AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
|
| 946 |
+
+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
|
| 947 |
+
////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
|
| 948 |
+
BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
|
| 949 |
+
AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
|
| 950 |
+
AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
|
| 951 |
+
AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
|
| 952 |
+
BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
|
| 953 |
+
//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
|
| 954 |
+
AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
|
| 955 |
+
AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
|
| 956 |
+
mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
|
| 957 |
+
AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
|
| 958 |
+
AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
|
| 959 |
+
AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
|
| 960 |
+
Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
|
| 961 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 962 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|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AAACAAAJ
|
| 975 |
+
AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
|
| 976 |
+
DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
|
| 977 |
+
AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
|
| 978 |
+
+wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
|
| 979 |
+
AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
|
| 980 |
+
///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
|
| 981 |
+
AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
|
| 982 |
+
BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
|
| 983 |
+
Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
|
| 984 |
+
eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
|
| 985 |
+
AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
|
| 986 |
+
+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
|
| 987 |
+
////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
|
| 988 |
+
BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
|
| 989 |
+
AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
|
| 990 |
+
AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
|
| 991 |
+
Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
|
| 992 |
+
Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
|
| 993 |
+
//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
|
| 994 |
+
AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
|
| 995 |
+
AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
|
| 996 |
+
LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
|
| 997 |
+
AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
|
| 998 |
+
AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
|
| 999 |
+
AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
|
| 1000 |
+
AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
|
| 1001 |
+
AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
|
| 1002 |
+
EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
|
| 1003 |
+
AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
|
| 1004 |
+
pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
|
| 1005 |
+
AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
|
| 1006 |
+
+QAGAAIAzgAKANUAEw==
|
| 1007 |
+
"""
|
| 1008 |
+
)
|
| 1009 |
+
),
|
| 1010 |
+
Image.open(
|
| 1011 |
+
BytesIO(
|
| 1012 |
+
base64.b64decode(
|
| 1013 |
+
b"""
|
| 1014 |
+
iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
|
| 1015 |
+
Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
|
| 1016 |
+
M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
|
| 1017 |
+
LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
|
| 1018 |
+
IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
|
| 1019 |
+
Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
|
| 1020 |
+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npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
|
| 1033 |
+
evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
|
| 1034 |
+
AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
|
| 1035 |
+
Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
|
| 1036 |
+
w7IkEbzhVQAAAABJRU5ErkJggg==
|
| 1037 |
+
"""
|
| 1038 |
+
)
|
| 1039 |
+
)
|
| 1040 |
+
),
|
| 1041 |
+
)
|
| 1042 |
+
return f
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
|
| 1046 |
+
"""If FreeType support is available, load a version of Aileron Regular,
|
| 1047 |
+
https://dotcolon.net/font/aileron, with a more limited character set.
|
| 1048 |
+
|
| 1049 |
+
Otherwise, load a "better than nothing" font.
|
| 1050 |
+
|
| 1051 |
+
.. versionadded:: 1.1.4
|
| 1052 |
+
|
| 1053 |
+
:param size: The font size of Aileron Regular.
|
| 1054 |
+
|
| 1055 |
+
.. versionadded:: 10.1.0
|
| 1056 |
+
|
| 1057 |
+
:return: A font object.
|
| 1058 |
+
"""
|
| 1059 |
+
if isinstance(core, ModuleType) or size is not None:
|
| 1060 |
+
return truetype(
|
| 1061 |
+
BytesIO(
|
| 1062 |
+
base64.b64decode(
|
| 1063 |
+
b"""
|
| 1064 |
+
AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
|
| 1065 |
+
AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
|
| 1066 |
+
MAACjo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ACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
|
| 1283 |
+
AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
|
| 1284 |
+
"""
|
| 1285 |
+
)
|
| 1286 |
+
),
|
| 1287 |
+
10 if size is None else size,
|
| 1288 |
+
layout_engine=Layout.BASIC,
|
| 1289 |
+
)
|
| 1290 |
+
return load_default_imagefont()
|
valley/lib/python3.10/site-packages/PIL/ImageGrab.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# screen grabber
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2001-04-26 fl created
|
| 9 |
+
# 2001-09-17 fl use builtin driver, if present
|
| 10 |
+
# 2002-11-19 fl added grabclipboard support
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 2001-2002 by Secret Labs AB
|
| 13 |
+
# Copyright (c) 2001-2002 by Fredrik Lundh
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import io
|
| 20 |
+
import os
|
| 21 |
+
import shutil
|
| 22 |
+
import subprocess
|
| 23 |
+
import sys
|
| 24 |
+
import tempfile
|
| 25 |
+
|
| 26 |
+
from . import Image
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def grab(
|
| 30 |
+
bbox: tuple[int, int, int, int] | None = None,
|
| 31 |
+
include_layered_windows: bool = False,
|
| 32 |
+
all_screens: bool = False,
|
| 33 |
+
xdisplay: str | None = None,
|
| 34 |
+
) -> Image.Image:
|
| 35 |
+
im: Image.Image
|
| 36 |
+
if xdisplay is None:
|
| 37 |
+
if sys.platform == "darwin":
|
| 38 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 39 |
+
os.close(fh)
|
| 40 |
+
args = ["screencapture"]
|
| 41 |
+
if bbox:
|
| 42 |
+
left, top, right, bottom = bbox
|
| 43 |
+
args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
|
| 44 |
+
subprocess.call(args + ["-x", filepath])
|
| 45 |
+
im = Image.open(filepath)
|
| 46 |
+
im.load()
|
| 47 |
+
os.unlink(filepath)
|
| 48 |
+
if bbox:
|
| 49 |
+
im_resized = im.resize((right - left, bottom - top))
|
| 50 |
+
im.close()
|
| 51 |
+
return im_resized
|
| 52 |
+
return im
|
| 53 |
+
elif sys.platform == "win32":
|
| 54 |
+
offset, size, data = Image.core.grabscreen_win32(
|
| 55 |
+
include_layered_windows, all_screens
|
| 56 |
+
)
|
| 57 |
+
im = Image.frombytes(
|
| 58 |
+
"RGB",
|
| 59 |
+
size,
|
| 60 |
+
data,
|
| 61 |
+
# RGB, 32-bit line padding, origin lower left corner
|
| 62 |
+
"raw",
|
| 63 |
+
"BGR",
|
| 64 |
+
(size[0] * 3 + 3) & -4,
|
| 65 |
+
-1,
|
| 66 |
+
)
|
| 67 |
+
if bbox:
|
| 68 |
+
x0, y0 = offset
|
| 69 |
+
left, top, right, bottom = bbox
|
| 70 |
+
im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
|
| 71 |
+
return im
|
| 72 |
+
# Cast to Optional[str] needed for Windows and macOS.
|
| 73 |
+
display_name: str | None = xdisplay
|
| 74 |
+
try:
|
| 75 |
+
if not Image.core.HAVE_XCB:
|
| 76 |
+
msg = "Pillow was built without XCB support"
|
| 77 |
+
raise OSError(msg)
|
| 78 |
+
size, data = Image.core.grabscreen_x11(display_name)
|
| 79 |
+
except OSError:
|
| 80 |
+
if (
|
| 81 |
+
display_name is None
|
| 82 |
+
and sys.platform not in ("darwin", "win32")
|
| 83 |
+
and shutil.which("gnome-screenshot")
|
| 84 |
+
):
|
| 85 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 86 |
+
os.close(fh)
|
| 87 |
+
subprocess.call(["gnome-screenshot", "-f", filepath])
|
| 88 |
+
im = Image.open(filepath)
|
| 89 |
+
im.load()
|
| 90 |
+
os.unlink(filepath)
|
| 91 |
+
if bbox:
|
| 92 |
+
im_cropped = im.crop(bbox)
|
| 93 |
+
im.close()
|
| 94 |
+
return im_cropped
|
| 95 |
+
return im
|
| 96 |
+
else:
|
| 97 |
+
raise
|
| 98 |
+
else:
|
| 99 |
+
im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
|
| 100 |
+
if bbox:
|
| 101 |
+
im = im.crop(bbox)
|
| 102 |
+
return im
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def grabclipboard() -> Image.Image | list[str] | None:
|
| 106 |
+
if sys.platform == "darwin":
|
| 107 |
+
fh, filepath = tempfile.mkstemp(".png")
|
| 108 |
+
os.close(fh)
|
| 109 |
+
commands = [
|
| 110 |
+
'set theFile to (open for access POSIX file "'
|
| 111 |
+
+ filepath
|
| 112 |
+
+ '" with write permission)',
|
| 113 |
+
"try",
|
| 114 |
+
" write (the clipboard as «class PNGf») to theFile",
|
| 115 |
+
"end try",
|
| 116 |
+
"close access theFile",
|
| 117 |
+
]
|
| 118 |
+
script = ["osascript"]
|
| 119 |
+
for command in commands:
|
| 120 |
+
script += ["-e", command]
|
| 121 |
+
subprocess.call(script)
|
| 122 |
+
|
| 123 |
+
im = None
|
| 124 |
+
if os.stat(filepath).st_size != 0:
|
| 125 |
+
im = Image.open(filepath)
|
| 126 |
+
im.load()
|
| 127 |
+
os.unlink(filepath)
|
| 128 |
+
return im
|
| 129 |
+
elif sys.platform == "win32":
|
| 130 |
+
fmt, data = Image.core.grabclipboard_win32()
|
| 131 |
+
if fmt == "file": # CF_HDROP
|
| 132 |
+
import struct
|
| 133 |
+
|
| 134 |
+
o = struct.unpack_from("I", data)[0]
|
| 135 |
+
if data[16] != 0:
|
| 136 |
+
files = data[o:].decode("utf-16le").split("\0")
|
| 137 |
+
else:
|
| 138 |
+
files = data[o:].decode("mbcs").split("\0")
|
| 139 |
+
return files[: files.index("")]
|
| 140 |
+
if isinstance(data, bytes):
|
| 141 |
+
data = io.BytesIO(data)
|
| 142 |
+
if fmt == "png":
|
| 143 |
+
from . import PngImagePlugin
|
| 144 |
+
|
| 145 |
+
return PngImagePlugin.PngImageFile(data)
|
| 146 |
+
elif fmt == "DIB":
|
| 147 |
+
from . import BmpImagePlugin
|
| 148 |
+
|
| 149 |
+
return BmpImagePlugin.DibImageFile(data)
|
| 150 |
+
return None
|
| 151 |
+
else:
|
| 152 |
+
if os.getenv("WAYLAND_DISPLAY"):
|
| 153 |
+
session_type = "wayland"
|
| 154 |
+
elif os.getenv("DISPLAY"):
|
| 155 |
+
session_type = "x11"
|
| 156 |
+
else: # Session type check failed
|
| 157 |
+
session_type = None
|
| 158 |
+
|
| 159 |
+
if shutil.which("wl-paste") and session_type in ("wayland", None):
|
| 160 |
+
args = ["wl-paste", "-t", "image"]
|
| 161 |
+
elif shutil.which("xclip") and session_type in ("x11", None):
|
| 162 |
+
args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
|
| 163 |
+
else:
|
| 164 |
+
msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
|
| 165 |
+
raise NotImplementedError(msg)
|
| 166 |
+
|
| 167 |
+
p = subprocess.run(args, capture_output=True)
|
| 168 |
+
if p.returncode != 0:
|
| 169 |
+
err = p.stderr
|
| 170 |
+
for silent_error in [
|
| 171 |
+
# wl-paste, when the clipboard is empty
|
| 172 |
+
b"Nothing is copied",
|
| 173 |
+
# Ubuntu/Debian wl-paste, when the clipboard is empty
|
| 174 |
+
b"No selection",
|
| 175 |
+
# Ubuntu/Debian wl-paste, when an image isn't available
|
| 176 |
+
b"No suitable type of content copied",
|
| 177 |
+
# wl-paste or Ubuntu/Debian xclip, when an image isn't available
|
| 178 |
+
b" not available",
|
| 179 |
+
# xclip, when an image isn't available
|
| 180 |
+
b"cannot convert ",
|
| 181 |
+
# xclip, when the clipboard isn't initialized
|
| 182 |
+
b"xclip: Error: There is no owner for the ",
|
| 183 |
+
]:
|
| 184 |
+
if silent_error in err:
|
| 185 |
+
return None
|
| 186 |
+
msg = f"{args[0]} error"
|
| 187 |
+
if err:
|
| 188 |
+
msg += f": {err.strip().decode()}"
|
| 189 |
+
raise ChildProcessError(msg)
|
| 190 |
+
|
| 191 |
+
data = io.BytesIO(p.stdout)
|
| 192 |
+
im = Image.open(data)
|
| 193 |
+
im.load()
|
| 194 |
+
return im
|
valley/lib/python3.10/site-packages/PIL/ImagePalette.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# image palette object
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-03-11 fl Rewritten.
|
| 9 |
+
# 1997-01-03 fl Up and running.
|
| 10 |
+
# 1997-08-23 fl Added load hack
|
| 11 |
+
# 2001-04-16 fl Fixed randint shadow bug in random()
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import array
|
| 21 |
+
from typing import IO, TYPE_CHECKING, Sequence
|
| 22 |
+
|
| 23 |
+
from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from . import Image
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ImagePalette:
|
| 30 |
+
"""
|
| 31 |
+
Color palette for palette mapped images
|
| 32 |
+
|
| 33 |
+
:param mode: The mode to use for the palette. See:
|
| 34 |
+
:ref:`concept-modes`. Defaults to "RGB"
|
| 35 |
+
:param palette: An optional palette. If given, it must be a bytearray,
|
| 36 |
+
an array or a list of ints between 0-255. The list must consist of
|
| 37 |
+
all channels for one color followed by the next color (e.g. RGBRGBRGB).
|
| 38 |
+
Defaults to an empty palette.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
mode: str = "RGB",
|
| 44 |
+
palette: Sequence[int] | bytes | bytearray | None = None,
|
| 45 |
+
) -> None:
|
| 46 |
+
self.mode = mode
|
| 47 |
+
self.rawmode: str | None = None # if set, palette contains raw data
|
| 48 |
+
self.palette = palette or bytearray()
|
| 49 |
+
self.dirty: int | None = None
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def palette(self) -> Sequence[int] | bytes | bytearray:
|
| 53 |
+
return self._palette
|
| 54 |
+
|
| 55 |
+
@palette.setter
|
| 56 |
+
def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
|
| 57 |
+
self._colors: dict[tuple[int, ...], int] | None = None
|
| 58 |
+
self._palette = palette
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def colors(self) -> dict[tuple[int, ...], int]:
|
| 62 |
+
if self._colors is None:
|
| 63 |
+
mode_len = len(self.mode)
|
| 64 |
+
self._colors = {}
|
| 65 |
+
for i in range(0, len(self.palette), mode_len):
|
| 66 |
+
color = tuple(self.palette[i : i + mode_len])
|
| 67 |
+
if color in self._colors:
|
| 68 |
+
continue
|
| 69 |
+
self._colors[color] = i // mode_len
|
| 70 |
+
return self._colors
|
| 71 |
+
|
| 72 |
+
@colors.setter
|
| 73 |
+
def colors(self, colors: dict[tuple[int, ...], int]) -> None:
|
| 74 |
+
self._colors = colors
|
| 75 |
+
|
| 76 |
+
def copy(self) -> ImagePalette:
|
| 77 |
+
new = ImagePalette()
|
| 78 |
+
|
| 79 |
+
new.mode = self.mode
|
| 80 |
+
new.rawmode = self.rawmode
|
| 81 |
+
if self.palette is not None:
|
| 82 |
+
new.palette = self.palette[:]
|
| 83 |
+
new.dirty = self.dirty
|
| 84 |
+
|
| 85 |
+
return new
|
| 86 |
+
|
| 87 |
+
def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
|
| 88 |
+
"""
|
| 89 |
+
Get palette contents in format suitable for the low-level
|
| 90 |
+
``im.putpalette`` primitive.
|
| 91 |
+
|
| 92 |
+
.. warning:: This method is experimental.
|
| 93 |
+
"""
|
| 94 |
+
if self.rawmode:
|
| 95 |
+
return self.rawmode, self.palette
|
| 96 |
+
return self.mode, self.tobytes()
|
| 97 |
+
|
| 98 |
+
def tobytes(self) -> bytes:
|
| 99 |
+
"""Convert palette to bytes.
|
| 100 |
+
|
| 101 |
+
.. warning:: This method is experimental.
|
| 102 |
+
"""
|
| 103 |
+
if self.rawmode:
|
| 104 |
+
msg = "palette contains raw palette data"
|
| 105 |
+
raise ValueError(msg)
|
| 106 |
+
if isinstance(self.palette, bytes):
|
| 107 |
+
return self.palette
|
| 108 |
+
arr = array.array("B", self.palette)
|
| 109 |
+
return arr.tobytes()
|
| 110 |
+
|
| 111 |
+
# Declare tostring as an alias for tobytes
|
| 112 |
+
tostring = tobytes
|
| 113 |
+
|
| 114 |
+
def _new_color_index(
|
| 115 |
+
self, image: Image.Image | None = None, e: Exception | None = None
|
| 116 |
+
) -> int:
|
| 117 |
+
if not isinstance(self.palette, bytearray):
|
| 118 |
+
self._palette = bytearray(self.palette)
|
| 119 |
+
index = len(self.palette) // 3
|
| 120 |
+
special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
|
| 121 |
+
if image:
|
| 122 |
+
special_colors = (
|
| 123 |
+
image.info.get("background"),
|
| 124 |
+
image.info.get("transparency"),
|
| 125 |
+
)
|
| 126 |
+
while index in special_colors:
|
| 127 |
+
index += 1
|
| 128 |
+
if index >= 256:
|
| 129 |
+
if image:
|
| 130 |
+
# Search for an unused index
|
| 131 |
+
for i, count in reversed(list(enumerate(image.histogram()))):
|
| 132 |
+
if count == 0 and i not in special_colors:
|
| 133 |
+
index = i
|
| 134 |
+
break
|
| 135 |
+
if index >= 256:
|
| 136 |
+
msg = "cannot allocate more than 256 colors"
|
| 137 |
+
raise ValueError(msg) from e
|
| 138 |
+
return index
|
| 139 |
+
|
| 140 |
+
def getcolor(
|
| 141 |
+
self,
|
| 142 |
+
color: tuple[int, ...],
|
| 143 |
+
image: Image.Image | None = None,
|
| 144 |
+
) -> int:
|
| 145 |
+
"""Given an rgb tuple, allocate palette entry.
|
| 146 |
+
|
| 147 |
+
.. warning:: This method is experimental.
|
| 148 |
+
"""
|
| 149 |
+
if self.rawmode:
|
| 150 |
+
msg = "palette contains raw palette data"
|
| 151 |
+
raise ValueError(msg)
|
| 152 |
+
if isinstance(color, tuple):
|
| 153 |
+
if self.mode == "RGB":
|
| 154 |
+
if len(color) == 4:
|
| 155 |
+
if color[3] != 255:
|
| 156 |
+
msg = "cannot add non-opaque RGBA color to RGB palette"
|
| 157 |
+
raise ValueError(msg)
|
| 158 |
+
color = color[:3]
|
| 159 |
+
elif self.mode == "RGBA":
|
| 160 |
+
if len(color) == 3:
|
| 161 |
+
color += (255,)
|
| 162 |
+
try:
|
| 163 |
+
return self.colors[color]
|
| 164 |
+
except KeyError as e:
|
| 165 |
+
# allocate new color slot
|
| 166 |
+
index = self._new_color_index(image, e)
|
| 167 |
+
assert isinstance(self._palette, bytearray)
|
| 168 |
+
self.colors[color] = index
|
| 169 |
+
if index * 3 < len(self.palette):
|
| 170 |
+
self._palette = (
|
| 171 |
+
self._palette[: index * 3]
|
| 172 |
+
+ bytes(color)
|
| 173 |
+
+ self._palette[index * 3 + 3 :]
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
self._palette += bytes(color)
|
| 177 |
+
self.dirty = 1
|
| 178 |
+
return index
|
| 179 |
+
else:
|
| 180 |
+
msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
|
| 181 |
+
raise ValueError(msg)
|
| 182 |
+
|
| 183 |
+
def save(self, fp: str | IO[str]) -> None:
|
| 184 |
+
"""Save palette to text file.
|
| 185 |
+
|
| 186 |
+
.. warning:: This method is experimental.
|
| 187 |
+
"""
|
| 188 |
+
if self.rawmode:
|
| 189 |
+
msg = "palette contains raw palette data"
|
| 190 |
+
raise ValueError(msg)
|
| 191 |
+
if isinstance(fp, str):
|
| 192 |
+
fp = open(fp, "w")
|
| 193 |
+
fp.write("# Palette\n")
|
| 194 |
+
fp.write(f"# Mode: {self.mode}\n")
|
| 195 |
+
for i in range(256):
|
| 196 |
+
fp.write(f"{i}")
|
| 197 |
+
for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
|
| 198 |
+
try:
|
| 199 |
+
fp.write(f" {self.palette[j]}")
|
| 200 |
+
except IndexError:
|
| 201 |
+
fp.write(" 0")
|
| 202 |
+
fp.write("\n")
|
| 203 |
+
fp.close()
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# --------------------------------------------------------------------
|
| 207 |
+
# Internal
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def raw(rawmode, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
|
| 211 |
+
palette = ImagePalette()
|
| 212 |
+
palette.rawmode = rawmode
|
| 213 |
+
palette.palette = data
|
| 214 |
+
palette.dirty = 1
|
| 215 |
+
return palette
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# --------------------------------------------------------------------
|
| 219 |
+
# Factories
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def make_linear_lut(black: int, white: float) -> list[int]:
|
| 223 |
+
if black == 0:
|
| 224 |
+
return [int(white * i // 255) for i in range(256)]
|
| 225 |
+
|
| 226 |
+
msg = "unavailable when black is non-zero"
|
| 227 |
+
raise NotImplementedError(msg) # FIXME
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def make_gamma_lut(exp: float) -> list[int]:
|
| 231 |
+
return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def negative(mode: str = "RGB") -> ImagePalette:
|
| 235 |
+
palette = list(range(256 * len(mode)))
|
| 236 |
+
palette.reverse()
|
| 237 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def random(mode: str = "RGB") -> ImagePalette:
|
| 241 |
+
from random import randint
|
| 242 |
+
|
| 243 |
+
palette = [randint(0, 255) for _ in range(256 * len(mode))]
|
| 244 |
+
return ImagePalette(mode, palette)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def sepia(white: str = "#fff0c0") -> ImagePalette:
|
| 248 |
+
bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
|
| 249 |
+
return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def wedge(mode: str = "RGB") -> ImagePalette:
|
| 253 |
+
palette = list(range(256 * len(mode)))
|
| 254 |
+
return ImagePalette(mode, [i // len(mode) for i in palette])
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def load(filename: str) -> tuple[bytes, str]:
|
| 258 |
+
# FIXME: supports GIMP gradients only
|
| 259 |
+
|
| 260 |
+
with open(filename, "rb") as fp:
|
| 261 |
+
paletteHandlers: list[
|
| 262 |
+
type[
|
| 263 |
+
GimpPaletteFile.GimpPaletteFile
|
| 264 |
+
| GimpGradientFile.GimpGradientFile
|
| 265 |
+
| PaletteFile.PaletteFile
|
| 266 |
+
]
|
| 267 |
+
] = [
|
| 268 |
+
GimpPaletteFile.GimpPaletteFile,
|
| 269 |
+
GimpGradientFile.GimpGradientFile,
|
| 270 |
+
PaletteFile.PaletteFile,
|
| 271 |
+
]
|
| 272 |
+
for paletteHandler in paletteHandlers:
|
| 273 |
+
try:
|
| 274 |
+
fp.seek(0)
|
| 275 |
+
lut = paletteHandler(fp).getpalette()
|
| 276 |
+
if lut:
|
| 277 |
+
break
|
| 278 |
+
except (SyntaxError, ValueError):
|
| 279 |
+
pass
|
| 280 |
+
else:
|
| 281 |
+
msg = "cannot load palette"
|
| 282 |
+
raise OSError(msg)
|
| 283 |
+
|
| 284 |
+
return lut # data, rawmode
|
valley/lib/python3.10/site-packages/PIL/ImageQt.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a simple Qt image interface.
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 2006-06-03 fl: created
|
| 9 |
+
# 2006-06-04 fl: inherit from QImage instead of wrapping it
|
| 10 |
+
# 2006-06-05 fl: removed toimage helper; move string support to ImageQt
|
| 11 |
+
# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 2006 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 2006 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import sys
|
| 21 |
+
from io import BytesIO
|
| 22 |
+
from typing import Callable
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
from ._util import is_path
|
| 26 |
+
|
| 27 |
+
qt_version: str | None
|
| 28 |
+
qt_versions = [
|
| 29 |
+
["6", "PyQt6"],
|
| 30 |
+
["side6", "PySide6"],
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
# If a version has already been imported, attempt it first
|
| 34 |
+
qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
|
| 35 |
+
for version, qt_module in qt_versions:
|
| 36 |
+
try:
|
| 37 |
+
QBuffer: type
|
| 38 |
+
QIODevice: type
|
| 39 |
+
QImage: type
|
| 40 |
+
QPixmap: type
|
| 41 |
+
qRgba: Callable[[int, int, int, int], int]
|
| 42 |
+
if qt_module == "PyQt6":
|
| 43 |
+
from PyQt6.QtCore import QBuffer, QIODevice
|
| 44 |
+
from PyQt6.QtGui import QImage, QPixmap, qRgba
|
| 45 |
+
elif qt_module == "PySide6":
|
| 46 |
+
from PySide6.QtCore import QBuffer, QIODevice
|
| 47 |
+
from PySide6.QtGui import QImage, QPixmap, qRgba
|
| 48 |
+
except (ImportError, RuntimeError):
|
| 49 |
+
continue
|
| 50 |
+
qt_is_installed = True
|
| 51 |
+
qt_version = version
|
| 52 |
+
break
|
| 53 |
+
else:
|
| 54 |
+
qt_is_installed = False
|
| 55 |
+
qt_version = None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def rgb(r, g, b, a=255):
|
| 59 |
+
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
|
| 60 |
+
# use qRgb to pack the colors, and then turn the resulting long
|
| 61 |
+
# into a negative integer with the same bitpattern.
|
| 62 |
+
return qRgba(r, g, b, a) & 0xFFFFFFFF
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def fromqimage(im):
|
| 66 |
+
"""
|
| 67 |
+
:param im: QImage or PIL ImageQt object
|
| 68 |
+
"""
|
| 69 |
+
buffer = QBuffer()
|
| 70 |
+
if qt_version == "6":
|
| 71 |
+
try:
|
| 72 |
+
qt_openmode = QIODevice.OpenModeFlag
|
| 73 |
+
except AttributeError:
|
| 74 |
+
qt_openmode = QIODevice.OpenMode
|
| 75 |
+
else:
|
| 76 |
+
qt_openmode = QIODevice
|
| 77 |
+
buffer.open(qt_openmode.ReadWrite)
|
| 78 |
+
# preserve alpha channel with png
|
| 79 |
+
# otherwise ppm is more friendly with Image.open
|
| 80 |
+
if im.hasAlphaChannel():
|
| 81 |
+
im.save(buffer, "png")
|
| 82 |
+
else:
|
| 83 |
+
im.save(buffer, "ppm")
|
| 84 |
+
|
| 85 |
+
b = BytesIO()
|
| 86 |
+
b.write(buffer.data())
|
| 87 |
+
buffer.close()
|
| 88 |
+
b.seek(0)
|
| 89 |
+
|
| 90 |
+
return Image.open(b)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def fromqpixmap(im):
|
| 94 |
+
return fromqimage(im)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def align8to32(bytes, width, mode):
|
| 98 |
+
"""
|
| 99 |
+
converts each scanline of data from 8 bit to 32 bit aligned
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
|
| 103 |
+
|
| 104 |
+
# calculate bytes per line and the extra padding if needed
|
| 105 |
+
bits_per_line = bits_per_pixel * width
|
| 106 |
+
full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
|
| 107 |
+
bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
|
| 108 |
+
|
| 109 |
+
extra_padding = -bytes_per_line % 4
|
| 110 |
+
|
| 111 |
+
# already 32 bit aligned by luck
|
| 112 |
+
if not extra_padding:
|
| 113 |
+
return bytes
|
| 114 |
+
|
| 115 |
+
new_data = [
|
| 116 |
+
bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
|
| 117 |
+
for i in range(len(bytes) // bytes_per_line)
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
return b"".join(new_data)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _toqclass_helper(im):
|
| 124 |
+
data = None
|
| 125 |
+
colortable = None
|
| 126 |
+
exclusive_fp = False
|
| 127 |
+
|
| 128 |
+
# handle filename, if given instead of image name
|
| 129 |
+
if hasattr(im, "toUtf8"):
|
| 130 |
+
# FIXME - is this really the best way to do this?
|
| 131 |
+
im = str(im.toUtf8(), "utf-8")
|
| 132 |
+
if is_path(im):
|
| 133 |
+
im = Image.open(im)
|
| 134 |
+
exclusive_fp = True
|
| 135 |
+
|
| 136 |
+
qt_format = QImage.Format if qt_version == "6" else QImage
|
| 137 |
+
if im.mode == "1":
|
| 138 |
+
format = qt_format.Format_Mono
|
| 139 |
+
elif im.mode == "L":
|
| 140 |
+
format = qt_format.Format_Indexed8
|
| 141 |
+
colortable = [rgb(i, i, i) for i in range(256)]
|
| 142 |
+
elif im.mode == "P":
|
| 143 |
+
format = qt_format.Format_Indexed8
|
| 144 |
+
palette = im.getpalette()
|
| 145 |
+
colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
|
| 146 |
+
elif im.mode == "RGB":
|
| 147 |
+
# Populate the 4th channel with 255
|
| 148 |
+
im = im.convert("RGBA")
|
| 149 |
+
|
| 150 |
+
data = im.tobytes("raw", "BGRA")
|
| 151 |
+
format = qt_format.Format_RGB32
|
| 152 |
+
elif im.mode == "RGBA":
|
| 153 |
+
data = im.tobytes("raw", "BGRA")
|
| 154 |
+
format = qt_format.Format_ARGB32
|
| 155 |
+
elif im.mode == "I;16":
|
| 156 |
+
im = im.point(lambda i: i * 256)
|
| 157 |
+
|
| 158 |
+
format = qt_format.Format_Grayscale16
|
| 159 |
+
else:
|
| 160 |
+
if exclusive_fp:
|
| 161 |
+
im.close()
|
| 162 |
+
msg = f"unsupported image mode {repr(im.mode)}"
|
| 163 |
+
raise ValueError(msg)
|
| 164 |
+
|
| 165 |
+
size = im.size
|
| 166 |
+
__data = data or align8to32(im.tobytes(), size[0], im.mode)
|
| 167 |
+
if exclusive_fp:
|
| 168 |
+
im.close()
|
| 169 |
+
return {"data": __data, "size": size, "format": format, "colortable": colortable}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if qt_is_installed:
|
| 173 |
+
|
| 174 |
+
class ImageQt(QImage):
|
| 175 |
+
def __init__(self, im):
|
| 176 |
+
"""
|
| 177 |
+
An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
|
| 178 |
+
class.
|
| 179 |
+
|
| 180 |
+
:param im: A PIL Image object, or a file name (given either as
|
| 181 |
+
Python string or a PyQt string object).
|
| 182 |
+
"""
|
| 183 |
+
im_data = _toqclass_helper(im)
|
| 184 |
+
# must keep a reference, or Qt will crash!
|
| 185 |
+
# All QImage constructors that take data operate on an existing
|
| 186 |
+
# buffer, so this buffer has to hang on for the life of the image.
|
| 187 |
+
# Fixes https://github.com/python-pillow/Pillow/issues/1370
|
| 188 |
+
self.__data = im_data["data"]
|
| 189 |
+
super().__init__(
|
| 190 |
+
self.__data,
|
| 191 |
+
im_data["size"][0],
|
| 192 |
+
im_data["size"][1],
|
| 193 |
+
im_data["format"],
|
| 194 |
+
)
|
| 195 |
+
if im_data["colortable"]:
|
| 196 |
+
self.setColorTable(im_data["colortable"])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def toqimage(im) -> ImageQt:
|
| 200 |
+
return ImageQt(im)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def toqpixmap(im):
|
| 204 |
+
qimage = toqimage(im)
|
| 205 |
+
return QPixmap.fromImage(qimage)
|
valley/lib/python3.10/site-packages/PIL/ImageSequence.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# sequence support classes
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1997-02-20 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 11 |
+
# Copyright (c) 1997 by Fredrik Lundh.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
##
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from typing import Callable
|
| 20 |
+
|
| 21 |
+
from . import Image
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Iterator:
|
| 25 |
+
"""
|
| 26 |
+
This class implements an iterator object that can be used to loop
|
| 27 |
+
over an image sequence.
|
| 28 |
+
|
| 29 |
+
You can use the ``[]`` operator to access elements by index. This operator
|
| 30 |
+
will raise an :py:exc:`IndexError` if you try to access a nonexistent
|
| 31 |
+
frame.
|
| 32 |
+
|
| 33 |
+
:param im: An image object.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, im: Image.Image):
|
| 37 |
+
if not hasattr(im, "seek"):
|
| 38 |
+
msg = "im must have seek method"
|
| 39 |
+
raise AttributeError(msg)
|
| 40 |
+
self.im = im
|
| 41 |
+
self.position = getattr(self.im, "_min_frame", 0)
|
| 42 |
+
|
| 43 |
+
def __getitem__(self, ix: int) -> Image.Image:
|
| 44 |
+
try:
|
| 45 |
+
self.im.seek(ix)
|
| 46 |
+
return self.im
|
| 47 |
+
except EOFError as e:
|
| 48 |
+
msg = "end of sequence"
|
| 49 |
+
raise IndexError(msg) from e
|
| 50 |
+
|
| 51 |
+
def __iter__(self) -> Iterator:
|
| 52 |
+
return self
|
| 53 |
+
|
| 54 |
+
def __next__(self) -> Image.Image:
|
| 55 |
+
try:
|
| 56 |
+
self.im.seek(self.position)
|
| 57 |
+
self.position += 1
|
| 58 |
+
return self.im
|
| 59 |
+
except EOFError as e:
|
| 60 |
+
msg = "end of sequence"
|
| 61 |
+
raise StopIteration(msg) from e
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def all_frames(
|
| 65 |
+
im: Image.Image | list[Image.Image],
|
| 66 |
+
func: Callable[[Image.Image], Image.Image] | None = None,
|
| 67 |
+
) -> list[Image.Image]:
|
| 68 |
+
"""
|
| 69 |
+
Applies a given function to all frames in an image or a list of images.
|
| 70 |
+
The frames are returned as a list of separate images.
|
| 71 |
+
|
| 72 |
+
:param im: An image, or a list of images.
|
| 73 |
+
:param func: The function to apply to all of the image frames.
|
| 74 |
+
:returns: A list of images.
|
| 75 |
+
"""
|
| 76 |
+
if not isinstance(im, list):
|
| 77 |
+
im = [im]
|
| 78 |
+
|
| 79 |
+
ims = []
|
| 80 |
+
for imSequence in im:
|
| 81 |
+
current = imSequence.tell()
|
| 82 |
+
|
| 83 |
+
ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
|
| 84 |
+
|
| 85 |
+
imSequence.seek(current)
|
| 86 |
+
return [func(im) for im in ims] if func else ims
|
valley/lib/python3.10/site-packages/PIL/ImageShow.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# im.show() drivers
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2008-04-06 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 2008.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import abc
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
from shlex import quote
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
|
| 26 |
+
_viewers = []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def register(viewer, order: int = 1) -> None:
|
| 30 |
+
"""
|
| 31 |
+
The :py:func:`register` function is used to register additional viewers::
|
| 32 |
+
|
| 33 |
+
from PIL import ImageShow
|
| 34 |
+
ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
|
| 35 |
+
ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
|
| 36 |
+
ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
|
| 37 |
+
|
| 38 |
+
:param viewer: The viewer to be registered.
|
| 39 |
+
:param order:
|
| 40 |
+
Zero or a negative integer to prepend this viewer to the list,
|
| 41 |
+
a positive integer to append it.
|
| 42 |
+
"""
|
| 43 |
+
try:
|
| 44 |
+
if issubclass(viewer, Viewer):
|
| 45 |
+
viewer = viewer()
|
| 46 |
+
except TypeError:
|
| 47 |
+
pass # raised if viewer wasn't a class
|
| 48 |
+
if order > 0:
|
| 49 |
+
_viewers.append(viewer)
|
| 50 |
+
else:
|
| 51 |
+
_viewers.insert(0, viewer)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
|
| 55 |
+
r"""
|
| 56 |
+
Display a given image.
|
| 57 |
+
|
| 58 |
+
:param image: An image object.
|
| 59 |
+
:param title: Optional title. Not all viewers can display the title.
|
| 60 |
+
:param \**options: Additional viewer options.
|
| 61 |
+
:returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
|
| 62 |
+
"""
|
| 63 |
+
for viewer in _viewers:
|
| 64 |
+
if viewer.show(image, title=title, **options):
|
| 65 |
+
return True
|
| 66 |
+
return False
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Viewer:
|
| 70 |
+
"""Base class for viewers."""
|
| 71 |
+
|
| 72 |
+
# main api
|
| 73 |
+
|
| 74 |
+
def show(self, image: Image.Image, **options: Any) -> int:
|
| 75 |
+
"""
|
| 76 |
+
The main function for displaying an image.
|
| 77 |
+
Converts the given image to the target format and displays it.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
if not (
|
| 81 |
+
image.mode in ("1", "RGBA")
|
| 82 |
+
or (self.format == "PNG" and image.mode in ("I;16", "LA"))
|
| 83 |
+
):
|
| 84 |
+
base = Image.getmodebase(image.mode)
|
| 85 |
+
if image.mode != base:
|
| 86 |
+
image = image.convert(base)
|
| 87 |
+
|
| 88 |
+
return self.show_image(image, **options)
|
| 89 |
+
|
| 90 |
+
# hook methods
|
| 91 |
+
|
| 92 |
+
format: str | None = None
|
| 93 |
+
"""The format to convert the image into."""
|
| 94 |
+
options: dict[str, Any] = {}
|
| 95 |
+
"""Additional options used to convert the image."""
|
| 96 |
+
|
| 97 |
+
def get_format(self, image: Image.Image) -> str | None:
|
| 98 |
+
"""Return format name, or ``None`` to save as PGM/PPM."""
|
| 99 |
+
return self.format
|
| 100 |
+
|
| 101 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 102 |
+
"""
|
| 103 |
+
Returns the command used to display the file.
|
| 104 |
+
Not implemented in the base class.
|
| 105 |
+
"""
|
| 106 |
+
msg = "unavailable in base viewer"
|
| 107 |
+
raise NotImplementedError(msg)
|
| 108 |
+
|
| 109 |
+
def save_image(self, image: Image.Image) -> str:
|
| 110 |
+
"""Save to temporary file and return filename."""
|
| 111 |
+
return image._dump(format=self.get_format(image), **self.options)
|
| 112 |
+
|
| 113 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
| 114 |
+
"""Display the given image."""
|
| 115 |
+
return self.show_file(self.save_image(image), **options)
|
| 116 |
+
|
| 117 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 118 |
+
"""
|
| 119 |
+
Display given file.
|
| 120 |
+
"""
|
| 121 |
+
if not os.path.exists(path):
|
| 122 |
+
raise FileNotFoundError
|
| 123 |
+
os.system(self.get_command(path, **options)) # nosec
|
| 124 |
+
return 1
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# --------------------------------------------------------------------
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class WindowsViewer(Viewer):
|
| 131 |
+
"""The default viewer on Windows is the default system application for PNG files."""
|
| 132 |
+
|
| 133 |
+
format = "PNG"
|
| 134 |
+
options = {"compress_level": 1, "save_all": True}
|
| 135 |
+
|
| 136 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 137 |
+
return (
|
| 138 |
+
f'start "Pillow" /WAIT "{file}" '
|
| 139 |
+
"&& ping -n 4 127.0.0.1 >NUL "
|
| 140 |
+
f'&& del /f "{file}"'
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 144 |
+
"""
|
| 145 |
+
Display given file.
|
| 146 |
+
"""
|
| 147 |
+
if not os.path.exists(path):
|
| 148 |
+
raise FileNotFoundError
|
| 149 |
+
subprocess.Popen(
|
| 150 |
+
self.get_command(path, **options),
|
| 151 |
+
shell=True,
|
| 152 |
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
|
| 153 |
+
) # nosec
|
| 154 |
+
return 1
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if sys.platform == "win32":
|
| 158 |
+
register(WindowsViewer)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class MacViewer(Viewer):
|
| 162 |
+
"""The default viewer on macOS using ``Preview.app``."""
|
| 163 |
+
|
| 164 |
+
format = "PNG"
|
| 165 |
+
options = {"compress_level": 1, "save_all": True}
|
| 166 |
+
|
| 167 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 168 |
+
# on darwin open returns immediately resulting in the temp
|
| 169 |
+
# file removal while app is opening
|
| 170 |
+
command = "open -a Preview.app"
|
| 171 |
+
command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
|
| 172 |
+
return command
|
| 173 |
+
|
| 174 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 175 |
+
"""
|
| 176 |
+
Display given file.
|
| 177 |
+
"""
|
| 178 |
+
if not os.path.exists(path):
|
| 179 |
+
raise FileNotFoundError
|
| 180 |
+
subprocess.call(["open", "-a", "Preview.app", path])
|
| 181 |
+
executable = sys.executable or shutil.which("python3")
|
| 182 |
+
if executable:
|
| 183 |
+
subprocess.Popen(
|
| 184 |
+
[
|
| 185 |
+
executable,
|
| 186 |
+
"-c",
|
| 187 |
+
"import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
|
| 188 |
+
path,
|
| 189 |
+
]
|
| 190 |
+
)
|
| 191 |
+
return 1
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if sys.platform == "darwin":
|
| 195 |
+
register(MacViewer)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class UnixViewer(Viewer):
|
| 199 |
+
format = "PNG"
|
| 200 |
+
options = {"compress_level": 1, "save_all": True}
|
| 201 |
+
|
| 202 |
+
@abc.abstractmethod
|
| 203 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 204 |
+
pass
|
| 205 |
+
|
| 206 |
+
def get_command(self, file: str, **options: Any) -> str:
|
| 207 |
+
command = self.get_command_ex(file, **options)[0]
|
| 208 |
+
return f"{command} {quote(file)}"
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class XDGViewer(UnixViewer):
|
| 212 |
+
"""
|
| 213 |
+
The freedesktop.org ``xdg-open`` command.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 217 |
+
command = executable = "xdg-open"
|
| 218 |
+
return command, executable
|
| 219 |
+
|
| 220 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 221 |
+
"""
|
| 222 |
+
Display given file.
|
| 223 |
+
"""
|
| 224 |
+
if not os.path.exists(path):
|
| 225 |
+
raise FileNotFoundError
|
| 226 |
+
subprocess.Popen(["xdg-open", path])
|
| 227 |
+
return 1
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class DisplayViewer(UnixViewer):
|
| 231 |
+
"""
|
| 232 |
+
The ImageMagick ``display`` command.
|
| 233 |
+
This viewer supports the ``title`` parameter.
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
def get_command_ex(
|
| 237 |
+
self, file: str, title: str | None = None, **options: Any
|
| 238 |
+
) -> tuple[str, str]:
|
| 239 |
+
command = executable = "display"
|
| 240 |
+
if title:
|
| 241 |
+
command += f" -title {quote(title)}"
|
| 242 |
+
return command, executable
|
| 243 |
+
|
| 244 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 245 |
+
"""
|
| 246 |
+
Display given file.
|
| 247 |
+
"""
|
| 248 |
+
if not os.path.exists(path):
|
| 249 |
+
raise FileNotFoundError
|
| 250 |
+
args = ["display"]
|
| 251 |
+
title = options.get("title")
|
| 252 |
+
if title:
|
| 253 |
+
args += ["-title", title]
|
| 254 |
+
args.append(path)
|
| 255 |
+
|
| 256 |
+
subprocess.Popen(args)
|
| 257 |
+
return 1
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class GmDisplayViewer(UnixViewer):
|
| 261 |
+
"""The GraphicsMagick ``gm display`` command."""
|
| 262 |
+
|
| 263 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 264 |
+
executable = "gm"
|
| 265 |
+
command = "gm display"
|
| 266 |
+
return command, executable
|
| 267 |
+
|
| 268 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 269 |
+
"""
|
| 270 |
+
Display given file.
|
| 271 |
+
"""
|
| 272 |
+
if not os.path.exists(path):
|
| 273 |
+
raise FileNotFoundError
|
| 274 |
+
subprocess.Popen(["gm", "display", path])
|
| 275 |
+
return 1
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class EogViewer(UnixViewer):
|
| 279 |
+
"""The GNOME Image Viewer ``eog`` command."""
|
| 280 |
+
|
| 281 |
+
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
|
| 282 |
+
executable = "eog"
|
| 283 |
+
command = "eog -n"
|
| 284 |
+
return command, executable
|
| 285 |
+
|
| 286 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 287 |
+
"""
|
| 288 |
+
Display given file.
|
| 289 |
+
"""
|
| 290 |
+
if not os.path.exists(path):
|
| 291 |
+
raise FileNotFoundError
|
| 292 |
+
subprocess.Popen(["eog", "-n", path])
|
| 293 |
+
return 1
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class XVViewer(UnixViewer):
|
| 297 |
+
"""
|
| 298 |
+
The X Viewer ``xv`` command.
|
| 299 |
+
This viewer supports the ``title`` parameter.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def get_command_ex(
|
| 303 |
+
self, file: str, title: str | None = None, **options: Any
|
| 304 |
+
) -> tuple[str, str]:
|
| 305 |
+
# note: xv is pretty outdated. most modern systems have
|
| 306 |
+
# imagemagick's display command instead.
|
| 307 |
+
command = executable = "xv"
|
| 308 |
+
if title:
|
| 309 |
+
command += f" -name {quote(title)}"
|
| 310 |
+
return command, executable
|
| 311 |
+
|
| 312 |
+
def show_file(self, path: str, **options: Any) -> int:
|
| 313 |
+
"""
|
| 314 |
+
Display given file.
|
| 315 |
+
"""
|
| 316 |
+
if not os.path.exists(path):
|
| 317 |
+
raise FileNotFoundError
|
| 318 |
+
args = ["xv"]
|
| 319 |
+
title = options.get("title")
|
| 320 |
+
if title:
|
| 321 |
+
args += ["-name", title]
|
| 322 |
+
args.append(path)
|
| 323 |
+
|
| 324 |
+
subprocess.Popen(args)
|
| 325 |
+
return 1
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
if sys.platform not in ("win32", "darwin"): # unixoids
|
| 329 |
+
if shutil.which("xdg-open"):
|
| 330 |
+
register(XDGViewer)
|
| 331 |
+
if shutil.which("display"):
|
| 332 |
+
register(DisplayViewer)
|
| 333 |
+
if shutil.which("gm"):
|
| 334 |
+
register(GmDisplayViewer)
|
| 335 |
+
if shutil.which("eog"):
|
| 336 |
+
register(EogViewer)
|
| 337 |
+
if shutil.which("xv"):
|
| 338 |
+
register(XVViewer)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class IPythonViewer(Viewer):
|
| 342 |
+
"""The viewer for IPython frontends."""
|
| 343 |
+
|
| 344 |
+
def show_image(self, image: Image.Image, **options: Any) -> int:
|
| 345 |
+
ipython_display(image)
|
| 346 |
+
return 1
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
try:
|
| 350 |
+
from IPython.display import display as ipython_display
|
| 351 |
+
except ImportError:
|
| 352 |
+
pass
|
| 353 |
+
else:
|
| 354 |
+
register(IPythonViewer)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
if __name__ == "__main__":
|
| 358 |
+
if len(sys.argv) < 2:
|
| 359 |
+
print("Syntax: python3 ImageShow.py imagefile [title]")
|
| 360 |
+
sys.exit()
|
| 361 |
+
|
| 362 |
+
with Image.open(sys.argv[1]) as im:
|
| 363 |
+
print(show(im, *sys.argv[2:]))
|
valley/lib/python3.10/site-packages/PIL/ImageStat.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# global image statistics
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-05 fl Created
|
| 9 |
+
# 1997-05-21 fl Added mask; added rms, var, stddev attributes
|
| 10 |
+
# 1997-08-05 fl Added median
|
| 11 |
+
# 1998-07-05 hk Fixed integer overflow error
|
| 12 |
+
#
|
| 13 |
+
# Notes:
|
| 14 |
+
# This class shows how to implement delayed evaluation of attributes.
|
| 15 |
+
# To get a certain value, simply access the corresponding attribute.
|
| 16 |
+
# The __getattr__ dispatcher takes care of the rest.
|
| 17 |
+
#
|
| 18 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 19 |
+
# Copyright (c) Fredrik Lundh 1996-97.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import math
|
| 26 |
+
from functools import cached_property
|
| 27 |
+
|
| 28 |
+
from . import Image
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Stat:
|
| 32 |
+
def __init__(
|
| 33 |
+
self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
|
| 34 |
+
) -> None:
|
| 35 |
+
"""
|
| 36 |
+
Calculate statistics for the given image. If a mask is included,
|
| 37 |
+
only the regions covered by that mask are included in the
|
| 38 |
+
statistics. You can also pass in a previously calculated histogram.
|
| 39 |
+
|
| 40 |
+
:param image: A PIL image, or a precalculated histogram.
|
| 41 |
+
|
| 42 |
+
.. note::
|
| 43 |
+
|
| 44 |
+
For a PIL image, calculations rely on the
|
| 45 |
+
:py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
|
| 46 |
+
grouped into 256 bins, even if the image has more than 8 bits per
|
| 47 |
+
channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
|
| 48 |
+
``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
|
| 49 |
+
of more than 255.
|
| 50 |
+
|
| 51 |
+
:param mask: An optional mask.
|
| 52 |
+
"""
|
| 53 |
+
if isinstance(image_or_list, Image.Image):
|
| 54 |
+
self.h = image_or_list.histogram(mask)
|
| 55 |
+
elif isinstance(image_or_list, list):
|
| 56 |
+
self.h = image_or_list
|
| 57 |
+
else:
|
| 58 |
+
msg = "first argument must be image or list" # type: ignore[unreachable]
|
| 59 |
+
raise TypeError(msg)
|
| 60 |
+
self.bands = list(range(len(self.h) // 256))
|
| 61 |
+
|
| 62 |
+
@cached_property
|
| 63 |
+
def extrema(self) -> list[tuple[int, int]]:
|
| 64 |
+
"""
|
| 65 |
+
Min/max values for each band in the image.
|
| 66 |
+
|
| 67 |
+
.. note::
|
| 68 |
+
This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
|
| 69 |
+
simply returns the low and high bins used. This is correct for
|
| 70 |
+
images with 8 bits per channel, but fails for other modes such as
|
| 71 |
+
``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
|
| 72 |
+
return per-band extrema for the image. This is more correct and
|
| 73 |
+
efficient because, for non-8-bit modes, the histogram method uses
|
| 74 |
+
:py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def minmax(histogram: list[int]) -> tuple[int, int]:
|
| 78 |
+
res_min, res_max = 255, 0
|
| 79 |
+
for i in range(256):
|
| 80 |
+
if histogram[i]:
|
| 81 |
+
res_min = i
|
| 82 |
+
break
|
| 83 |
+
for i in range(255, -1, -1):
|
| 84 |
+
if histogram[i]:
|
| 85 |
+
res_max = i
|
| 86 |
+
break
|
| 87 |
+
return res_min, res_max
|
| 88 |
+
|
| 89 |
+
return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
|
| 90 |
+
|
| 91 |
+
@cached_property
|
| 92 |
+
def count(self) -> list[int]:
|
| 93 |
+
"""Total number of pixels for each band in the image."""
|
| 94 |
+
return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
|
| 95 |
+
|
| 96 |
+
@cached_property
|
| 97 |
+
def sum(self) -> list[float]:
|
| 98 |
+
"""Sum of all pixels for each band in the image."""
|
| 99 |
+
|
| 100 |
+
v = []
|
| 101 |
+
for i in range(0, len(self.h), 256):
|
| 102 |
+
layer_sum = 0.0
|
| 103 |
+
for j in range(256):
|
| 104 |
+
layer_sum += j * self.h[i + j]
|
| 105 |
+
v.append(layer_sum)
|
| 106 |
+
return v
|
| 107 |
+
|
| 108 |
+
@cached_property
|
| 109 |
+
def sum2(self) -> list[float]:
|
| 110 |
+
"""Squared sum of all pixels for each band in the image."""
|
| 111 |
+
|
| 112 |
+
v = []
|
| 113 |
+
for i in range(0, len(self.h), 256):
|
| 114 |
+
sum2 = 0.0
|
| 115 |
+
for j in range(256):
|
| 116 |
+
sum2 += (j**2) * float(self.h[i + j])
|
| 117 |
+
v.append(sum2)
|
| 118 |
+
return v
|
| 119 |
+
|
| 120 |
+
@cached_property
|
| 121 |
+
def mean(self) -> list[float]:
|
| 122 |
+
"""Average (arithmetic mean) pixel level for each band in the image."""
|
| 123 |
+
return [self.sum[i] / self.count[i] for i in self.bands]
|
| 124 |
+
|
| 125 |
+
@cached_property
|
| 126 |
+
def median(self) -> list[int]:
|
| 127 |
+
"""Median pixel level for each band in the image."""
|
| 128 |
+
|
| 129 |
+
v = []
|
| 130 |
+
for i in self.bands:
|
| 131 |
+
s = 0
|
| 132 |
+
half = self.count[i] // 2
|
| 133 |
+
b = i * 256
|
| 134 |
+
for j in range(256):
|
| 135 |
+
s = s + self.h[b + j]
|
| 136 |
+
if s > half:
|
| 137 |
+
break
|
| 138 |
+
v.append(j)
|
| 139 |
+
return v
|
| 140 |
+
|
| 141 |
+
@cached_property
|
| 142 |
+
def rms(self) -> list[float]:
|
| 143 |
+
"""RMS (root-mean-square) for each band in the image."""
|
| 144 |
+
return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands]
|
| 145 |
+
|
| 146 |
+
@cached_property
|
| 147 |
+
def var(self) -> list[float]:
|
| 148 |
+
"""Variance for each band in the image."""
|
| 149 |
+
return [
|
| 150 |
+
(self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
|
| 151 |
+
for i in self.bands
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
@cached_property
|
| 155 |
+
def stddev(self) -> list[float]:
|
| 156 |
+
"""Standard deviation for each band in the image."""
|
| 157 |
+
return [math.sqrt(self.var[i]) for i in self.bands]
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
Global = Stat # compatibility
|
valley/lib/python3.10/site-packages/PIL/ImageTk.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a Tk display interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-04-08 fl Created
|
| 9 |
+
# 96-09-06 fl Added getimage method
|
| 10 |
+
# 96-11-01 fl Rewritten, removed image attribute and crop method
|
| 11 |
+
# 97-05-09 fl Use PyImagingPaste method instead of image type
|
| 12 |
+
# 97-05-12 fl Minor tweaks to match the IFUNC95 interface
|
| 13 |
+
# 97-05-17 fl Support the "pilbitmap" booster patch
|
| 14 |
+
# 97-06-05 fl Added file= and data= argument to image constructors
|
| 15 |
+
# 98-03-09 fl Added width and height methods to Image classes
|
| 16 |
+
# 98-07-02 fl Use default mode for "P" images without palette attribute
|
| 17 |
+
# 98-07-02 fl Explicitly destroy Tkinter image objects
|
| 18 |
+
# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
|
| 19 |
+
# 99-07-26 fl Automatically hook into Tkinter (if possible)
|
| 20 |
+
# 99-08-15 fl Hook uses _imagingtk instead of _imaging
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-1999 by Secret Labs AB
|
| 23 |
+
# Copyright (c) 1996-1997 by Fredrik Lundh
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import tkinter
|
| 30 |
+
from io import BytesIO
|
| 31 |
+
|
| 32 |
+
from . import Image
|
| 33 |
+
|
| 34 |
+
# --------------------------------------------------------------------
|
| 35 |
+
# Check for Tkinter interface hooks
|
| 36 |
+
|
| 37 |
+
_pilbitmap_ok = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _pilbitmap_check() -> int:
|
| 41 |
+
global _pilbitmap_ok
|
| 42 |
+
if _pilbitmap_ok is None:
|
| 43 |
+
try:
|
| 44 |
+
im = Image.new("1", (1, 1))
|
| 45 |
+
tkinter.BitmapImage(data=f"PIL:{im.im.id}")
|
| 46 |
+
_pilbitmap_ok = 1
|
| 47 |
+
except tkinter.TclError:
|
| 48 |
+
_pilbitmap_ok = 0
|
| 49 |
+
return _pilbitmap_ok
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _get_image_from_kw(kw):
|
| 53 |
+
source = None
|
| 54 |
+
if "file" in kw:
|
| 55 |
+
source = kw.pop("file")
|
| 56 |
+
elif "data" in kw:
|
| 57 |
+
source = BytesIO(kw.pop("data"))
|
| 58 |
+
if source:
|
| 59 |
+
return Image.open(source)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _pyimagingtkcall(command, photo, id):
|
| 63 |
+
tk = photo.tk
|
| 64 |
+
try:
|
| 65 |
+
tk.call(command, photo, id)
|
| 66 |
+
except tkinter.TclError:
|
| 67 |
+
# activate Tkinter hook
|
| 68 |
+
# may raise an error if it cannot attach to Tkinter
|
| 69 |
+
from . import _imagingtk
|
| 70 |
+
|
| 71 |
+
_imagingtk.tkinit(tk.interpaddr())
|
| 72 |
+
tk.call(command, photo, id)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# --------------------------------------------------------------------
|
| 76 |
+
# PhotoImage
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class PhotoImage:
|
| 80 |
+
"""
|
| 81 |
+
A Tkinter-compatible photo image. This can be used
|
| 82 |
+
everywhere Tkinter expects an image object. If the image is an RGBA
|
| 83 |
+
image, pixels having alpha 0 are treated as transparent.
|
| 84 |
+
|
| 85 |
+
The constructor takes either a PIL image, or a mode and a size.
|
| 86 |
+
Alternatively, you can use the ``file`` or ``data`` options to initialize
|
| 87 |
+
the photo image object.
|
| 88 |
+
|
| 89 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
| 90 |
+
used, a size must also be given.
|
| 91 |
+
:param size: If the first argument is a mode string, this defines the size
|
| 92 |
+
of the image.
|
| 93 |
+
:keyword file: A filename to load the image from (using
|
| 94 |
+
``Image.open(file)``).
|
| 95 |
+
:keyword data: An 8-bit string containing image data (as loaded from an
|
| 96 |
+
image file).
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self, image=None, size=None, **kw):
|
| 100 |
+
# Tk compatibility: file or data
|
| 101 |
+
if image is None:
|
| 102 |
+
image = _get_image_from_kw(kw)
|
| 103 |
+
|
| 104 |
+
if hasattr(image, "mode") and hasattr(image, "size"):
|
| 105 |
+
# got an image instead of a mode
|
| 106 |
+
mode = image.mode
|
| 107 |
+
if mode == "P":
|
| 108 |
+
# palette mapped data
|
| 109 |
+
image.apply_transparency()
|
| 110 |
+
image.load()
|
| 111 |
+
try:
|
| 112 |
+
mode = image.palette.mode
|
| 113 |
+
except AttributeError:
|
| 114 |
+
mode = "RGB" # default
|
| 115 |
+
size = image.size
|
| 116 |
+
kw["width"], kw["height"] = size
|
| 117 |
+
else:
|
| 118 |
+
mode = image
|
| 119 |
+
image = None
|
| 120 |
+
|
| 121 |
+
if mode not in ["1", "L", "RGB", "RGBA"]:
|
| 122 |
+
mode = Image.getmodebase(mode)
|
| 123 |
+
|
| 124 |
+
self.__mode = mode
|
| 125 |
+
self.__size = size
|
| 126 |
+
self.__photo = tkinter.PhotoImage(**kw)
|
| 127 |
+
self.tk = self.__photo.tk
|
| 128 |
+
if image:
|
| 129 |
+
self.paste(image)
|
| 130 |
+
|
| 131 |
+
def __del__(self) -> None:
|
| 132 |
+
name = self.__photo.name
|
| 133 |
+
self.__photo.name = None
|
| 134 |
+
try:
|
| 135 |
+
self.__photo.tk.call("image", "delete", name)
|
| 136 |
+
except Exception:
|
| 137 |
+
pass # ignore internal errors
|
| 138 |
+
|
| 139 |
+
def __str__(self) -> str:
|
| 140 |
+
"""
|
| 141 |
+
Get the Tkinter photo image identifier. This method is automatically
|
| 142 |
+
called by Tkinter whenever a PhotoImage object is passed to a Tkinter
|
| 143 |
+
method.
|
| 144 |
+
|
| 145 |
+
:return: A Tkinter photo image identifier (a string).
|
| 146 |
+
"""
|
| 147 |
+
return str(self.__photo)
|
| 148 |
+
|
| 149 |
+
def width(self) -> int:
|
| 150 |
+
"""
|
| 151 |
+
Get the width of the image.
|
| 152 |
+
|
| 153 |
+
:return: The width, in pixels.
|
| 154 |
+
"""
|
| 155 |
+
return self.__size[0]
|
| 156 |
+
|
| 157 |
+
def height(self) -> int:
|
| 158 |
+
"""
|
| 159 |
+
Get the height of the image.
|
| 160 |
+
|
| 161 |
+
:return: The height, in pixels.
|
| 162 |
+
"""
|
| 163 |
+
return self.__size[1]
|
| 164 |
+
|
| 165 |
+
def paste(self, im: Image.Image) -> None:
|
| 166 |
+
"""
|
| 167 |
+
Paste a PIL image into the photo image. Note that this can
|
| 168 |
+
be very slow if the photo image is displayed.
|
| 169 |
+
|
| 170 |
+
:param im: A PIL image. The size must match the target region. If the
|
| 171 |
+
mode does not match, the image is converted to the mode of
|
| 172 |
+
the bitmap image.
|
| 173 |
+
"""
|
| 174 |
+
# convert to blittable
|
| 175 |
+
im.load()
|
| 176 |
+
image = im.im
|
| 177 |
+
if image.isblock() and im.mode == self.__mode:
|
| 178 |
+
block = image
|
| 179 |
+
else:
|
| 180 |
+
block = image.new_block(self.__mode, im.size)
|
| 181 |
+
image.convert2(block, image) # convert directly between buffers
|
| 182 |
+
|
| 183 |
+
_pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# --------------------------------------------------------------------
|
| 187 |
+
# BitmapImage
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class BitmapImage:
|
| 191 |
+
"""
|
| 192 |
+
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
|
| 193 |
+
expects an image object.
|
| 194 |
+
|
| 195 |
+
The given image must have mode "1". Pixels having value 0 are treated as
|
| 196 |
+
transparent. Options, if any, are passed on to Tkinter. The most commonly
|
| 197 |
+
used option is ``foreground``, which is used to specify the color for the
|
| 198 |
+
non-transparent parts. See the Tkinter documentation for information on
|
| 199 |
+
how to specify colours.
|
| 200 |
+
|
| 201 |
+
:param image: A PIL image.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
def __init__(self, image=None, **kw):
|
| 205 |
+
# Tk compatibility: file or data
|
| 206 |
+
if image is None:
|
| 207 |
+
image = _get_image_from_kw(kw)
|
| 208 |
+
|
| 209 |
+
self.__mode = image.mode
|
| 210 |
+
self.__size = image.size
|
| 211 |
+
|
| 212 |
+
if _pilbitmap_check():
|
| 213 |
+
# fast way (requires the pilbitmap booster patch)
|
| 214 |
+
image.load()
|
| 215 |
+
kw["data"] = f"PIL:{image.im.id}"
|
| 216 |
+
self.__im = image # must keep a reference
|
| 217 |
+
else:
|
| 218 |
+
# slow but safe way
|
| 219 |
+
kw["data"] = image.tobitmap()
|
| 220 |
+
self.__photo = tkinter.BitmapImage(**kw)
|
| 221 |
+
|
| 222 |
+
def __del__(self) -> None:
|
| 223 |
+
name = self.__photo.name
|
| 224 |
+
self.__photo.name = None
|
| 225 |
+
try:
|
| 226 |
+
self.__photo.tk.call("image", "delete", name)
|
| 227 |
+
except Exception:
|
| 228 |
+
pass # ignore internal errors
|
| 229 |
+
|
| 230 |
+
def width(self) -> int:
|
| 231 |
+
"""
|
| 232 |
+
Get the width of the image.
|
| 233 |
+
|
| 234 |
+
:return: The width, in pixels.
|
| 235 |
+
"""
|
| 236 |
+
return self.__size[0]
|
| 237 |
+
|
| 238 |
+
def height(self) -> int:
|
| 239 |
+
"""
|
| 240 |
+
Get the height of the image.
|
| 241 |
+
|
| 242 |
+
:return: The height, in pixels.
|
| 243 |
+
"""
|
| 244 |
+
return self.__size[1]
|
| 245 |
+
|
| 246 |
+
def __str__(self) -> str:
|
| 247 |
+
"""
|
| 248 |
+
Get the Tkinter bitmap image identifier. This method is automatically
|
| 249 |
+
called by Tkinter whenever a BitmapImage object is passed to a Tkinter
|
| 250 |
+
method.
|
| 251 |
+
|
| 252 |
+
:return: A Tkinter bitmap image identifier (a string).
|
| 253 |
+
"""
|
| 254 |
+
return str(self.__photo)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def getimage(photo: PhotoImage) -> Image.Image:
|
| 258 |
+
"""Copies the contents of a PhotoImage to a PIL image memory."""
|
| 259 |
+
im = Image.new("RGBA", (photo.width(), photo.height()))
|
| 260 |
+
block = im.im
|
| 261 |
+
|
| 262 |
+
_pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
|
| 263 |
+
|
| 264 |
+
return im
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _show(image, title):
|
| 268 |
+
"""Helper for the Image.show method."""
|
| 269 |
+
|
| 270 |
+
class UI(tkinter.Label):
|
| 271 |
+
def __init__(self, master, im):
|
| 272 |
+
if im.mode == "1":
|
| 273 |
+
self.image = BitmapImage(im, foreground="white", master=master)
|
| 274 |
+
else:
|
| 275 |
+
self.image = PhotoImage(im, master=master)
|
| 276 |
+
super().__init__(master, image=self.image, bg="black", bd=0)
|
| 277 |
+
|
| 278 |
+
if not tkinter._default_root:
|
| 279 |
+
msg = "tkinter not initialized"
|
| 280 |
+
raise OSError(msg)
|
| 281 |
+
top = tkinter.Toplevel()
|
| 282 |
+
if title:
|
| 283 |
+
top.title(title)
|
| 284 |
+
UI(top, image).pack()
|
valley/lib/python3.10/site-packages/PIL/ImageTransform.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# transform wrappers
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2002-04-08 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2002 by Secret Labs AB
|
| 11 |
+
# Copyright (c) 2002 by Fredrik Lundh
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import Any, Sequence
|
| 18 |
+
|
| 19 |
+
from . import Image
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Transform(Image.ImageTransformHandler):
|
| 23 |
+
"""Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
|
| 24 |
+
|
| 25 |
+
method: Image.Transform
|
| 26 |
+
|
| 27 |
+
def __init__(self, data: Sequence[Any]) -> None:
|
| 28 |
+
self.data = data
|
| 29 |
+
|
| 30 |
+
def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
|
| 31 |
+
return self.method, self.data
|
| 32 |
+
|
| 33 |
+
def transform(
|
| 34 |
+
self,
|
| 35 |
+
size: tuple[int, int],
|
| 36 |
+
image: Image.Image,
|
| 37 |
+
**options: Any,
|
| 38 |
+
) -> Image.Image:
|
| 39 |
+
"""Perform the transform. Called from :py:meth:`.Image.transform`."""
|
| 40 |
+
# can be overridden
|
| 41 |
+
method, data = self.getdata()
|
| 42 |
+
return image.transform(size, method, data, **options)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class AffineTransform(Transform):
|
| 46 |
+
"""
|
| 47 |
+
Define an affine image transform.
|
| 48 |
+
|
| 49 |
+
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
|
| 50 |
+
two rows from an affine transform matrix. For each pixel (x, y) in the
|
| 51 |
+
output image, the new value is taken from a position (a x + b y + c,
|
| 52 |
+
d x + e y + f) in the input image, rounded to nearest pixel.
|
| 53 |
+
|
| 54 |
+
This function can be used to scale, translate, rotate, and shear the
|
| 55 |
+
original image.
|
| 56 |
+
|
| 57 |
+
See :py:meth:`.Image.transform`
|
| 58 |
+
|
| 59 |
+
:param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
|
| 60 |
+
from an affine transform matrix.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
method = Image.Transform.AFFINE
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class PerspectiveTransform(Transform):
|
| 67 |
+
"""
|
| 68 |
+
Define a perspective image transform.
|
| 69 |
+
|
| 70 |
+
This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
|
| 71 |
+
(x, y) in the output image, the new value is taken from a position
|
| 72 |
+
((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
|
| 73 |
+
the input image, rounded to nearest pixel.
|
| 74 |
+
|
| 75 |
+
This function can be used to scale, translate, rotate, and shear the
|
| 76 |
+
original image.
|
| 77 |
+
|
| 78 |
+
See :py:meth:`.Image.transform`
|
| 79 |
+
|
| 80 |
+
:param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
method = Image.Transform.PERSPECTIVE
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ExtentTransform(Transform):
|
| 87 |
+
"""
|
| 88 |
+
Define a transform to extract a subregion from an image.
|
| 89 |
+
|
| 90 |
+
Maps a rectangle (defined by two corners) from the image to a rectangle of
|
| 91 |
+
the given size. The resulting image will contain data sampled from between
|
| 92 |
+
the corners, such that (x0, y0) in the input image will end up at (0,0) in
|
| 93 |
+
the output image, and (x1, y1) at size.
|
| 94 |
+
|
| 95 |
+
This method can be used to crop, stretch, shrink, or mirror an arbitrary
|
| 96 |
+
rectangle in the current image. It is slightly slower than crop, but about
|
| 97 |
+
as fast as a corresponding resize operation.
|
| 98 |
+
|
| 99 |
+
See :py:meth:`.Image.transform`
|
| 100 |
+
|
| 101 |
+
:param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
|
| 102 |
+
input image's coordinate system. See :ref:`coordinate-system`.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
method = Image.Transform.EXTENT
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class QuadTransform(Transform):
|
| 109 |
+
"""
|
| 110 |
+
Define a quad image transform.
|
| 111 |
+
|
| 112 |
+
Maps a quadrilateral (a region defined by four corners) from the image to a
|
| 113 |
+
rectangle of the given size.
|
| 114 |
+
|
| 115 |
+
See :py:meth:`.Image.transform`
|
| 116 |
+
|
| 117 |
+
:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
|
| 118 |
+
upper left, lower left, lower right, and upper right corner of the
|
| 119 |
+
source quadrilateral.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
method = Image.Transform.QUAD
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class MeshTransform(Transform):
|
| 126 |
+
"""
|
| 127 |
+
Define a mesh image transform. A mesh transform consists of one or more
|
| 128 |
+
individual quad transforms.
|
| 129 |
+
|
| 130 |
+
See :py:meth:`.Image.transform`
|
| 131 |
+
|
| 132 |
+
:param data: A list of (bbox, quad) tuples.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
method = Image.Transform.MESH
|
valley/lib/python3.10/site-packages/PIL/ImageWin.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a Windows DIB display interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-05-20 fl Created
|
| 9 |
+
# 1996-09-20 fl Fixed subregion exposure
|
| 10 |
+
# 1997-09-21 fl Added draw primitive (for tzPrint)
|
| 11 |
+
# 2003-05-21 fl Added experimental Window/ImageWindow classes
|
| 12 |
+
# 2003-09-05 fl Added fromstring/tostring methods
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) Secret Labs AB 1997-2003.
|
| 15 |
+
# Copyright (c) Fredrik Lundh 1996-2003.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from . import Image
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class HDC:
|
| 25 |
+
"""
|
| 26 |
+
Wraps an HDC integer. The resulting object can be passed to the
|
| 27 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
| 28 |
+
methods.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, dc: int) -> None:
|
| 32 |
+
self.dc = dc
|
| 33 |
+
|
| 34 |
+
def __int__(self) -> int:
|
| 35 |
+
return self.dc
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class HWND:
|
| 39 |
+
"""
|
| 40 |
+
Wraps an HWND integer. The resulting object can be passed to the
|
| 41 |
+
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
|
| 42 |
+
methods, instead of a DC.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, wnd: int) -> None:
|
| 46 |
+
self.wnd = wnd
|
| 47 |
+
|
| 48 |
+
def __int__(self) -> int:
|
| 49 |
+
return self.wnd
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Dib:
|
| 53 |
+
"""
|
| 54 |
+
A Windows bitmap with the given mode and size. The mode can be one of "1",
|
| 55 |
+
"L", "P", or "RGB".
|
| 56 |
+
|
| 57 |
+
If the display requires a palette, this constructor creates a suitable
|
| 58 |
+
palette and associates it with the image. For an "L" image, 128 graylevels
|
| 59 |
+
are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
|
| 60 |
+
with 20 graylevels.
|
| 61 |
+
|
| 62 |
+
To make sure that palettes work properly under Windows, you must call the
|
| 63 |
+
``palette`` method upon certain events from Windows.
|
| 64 |
+
|
| 65 |
+
:param image: Either a PIL image, or a mode string. If a mode string is
|
| 66 |
+
used, a size must also be given. The mode can be one of "1",
|
| 67 |
+
"L", "P", or "RGB".
|
| 68 |
+
:param size: If the first argument is a mode string, this
|
| 69 |
+
defines the size of the image.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self, image: Image.Image | str, size: tuple[int, int] | list[int] | None = None
|
| 74 |
+
) -> None:
|
| 75 |
+
if isinstance(image, str):
|
| 76 |
+
mode = image
|
| 77 |
+
image = ""
|
| 78 |
+
else:
|
| 79 |
+
mode = image.mode
|
| 80 |
+
size = image.size
|
| 81 |
+
if mode not in ["1", "L", "P", "RGB"]:
|
| 82 |
+
mode = Image.getmodebase(mode)
|
| 83 |
+
self.image = Image.core.display(mode, size)
|
| 84 |
+
self.mode = mode
|
| 85 |
+
self.size = size
|
| 86 |
+
if image:
|
| 87 |
+
assert not isinstance(image, str)
|
| 88 |
+
self.paste(image)
|
| 89 |
+
|
| 90 |
+
def expose(self, handle):
|
| 91 |
+
"""
|
| 92 |
+
Copy the bitmap contents to a device context.
|
| 93 |
+
|
| 94 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
| 95 |
+
HDC or HWND instance. In PythonWin, you can use
|
| 96 |
+
``CDC.GetHandleAttrib()`` to get a suitable handle.
|
| 97 |
+
"""
|
| 98 |
+
if isinstance(handle, HWND):
|
| 99 |
+
dc = self.image.getdc(handle)
|
| 100 |
+
try:
|
| 101 |
+
result = self.image.expose(dc)
|
| 102 |
+
finally:
|
| 103 |
+
self.image.releasedc(handle, dc)
|
| 104 |
+
else:
|
| 105 |
+
result = self.image.expose(handle)
|
| 106 |
+
return result
|
| 107 |
+
|
| 108 |
+
def draw(self, handle, dst, src=None):
|
| 109 |
+
"""
|
| 110 |
+
Same as expose, but allows you to specify where to draw the image, and
|
| 111 |
+
what part of it to draw.
|
| 112 |
+
|
| 113 |
+
The destination and source areas are given as 4-tuple rectangles. If
|
| 114 |
+
the source is omitted, the entire image is copied. If the source and
|
| 115 |
+
the destination have different sizes, the image is resized as
|
| 116 |
+
necessary.
|
| 117 |
+
"""
|
| 118 |
+
if not src:
|
| 119 |
+
src = (0, 0) + self.size
|
| 120 |
+
if isinstance(handle, HWND):
|
| 121 |
+
dc = self.image.getdc(handle)
|
| 122 |
+
try:
|
| 123 |
+
result = self.image.draw(dc, dst, src)
|
| 124 |
+
finally:
|
| 125 |
+
self.image.releasedc(handle, dc)
|
| 126 |
+
else:
|
| 127 |
+
result = self.image.draw(handle, dst, src)
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
def query_palette(self, handle):
|
| 131 |
+
"""
|
| 132 |
+
Installs the palette associated with the image in the given device
|
| 133 |
+
context.
|
| 134 |
+
|
| 135 |
+
This method should be called upon **QUERYNEWPALETTE** and
|
| 136 |
+
**PALETTECHANGED** events from Windows. If this method returns a
|
| 137 |
+
non-zero value, one or more display palette entries were changed, and
|
| 138 |
+
the image should be redrawn.
|
| 139 |
+
|
| 140 |
+
:param handle: Device context (HDC), cast to a Python integer, or an
|
| 141 |
+
HDC or HWND instance.
|
| 142 |
+
:return: A true value if one or more entries were changed (this
|
| 143 |
+
indicates that the image should be redrawn).
|
| 144 |
+
"""
|
| 145 |
+
if isinstance(handle, HWND):
|
| 146 |
+
handle = self.image.getdc(handle)
|
| 147 |
+
try:
|
| 148 |
+
result = self.image.query_palette(handle)
|
| 149 |
+
finally:
|
| 150 |
+
self.image.releasedc(handle, handle)
|
| 151 |
+
else:
|
| 152 |
+
result = self.image.query_palette(handle)
|
| 153 |
+
return result
|
| 154 |
+
|
| 155 |
+
def paste(
|
| 156 |
+
self, im: Image.Image, box: tuple[int, int, int, int] | None = None
|
| 157 |
+
) -> None:
|
| 158 |
+
"""
|
| 159 |
+
Paste a PIL image into the bitmap image.
|
| 160 |
+
|
| 161 |
+
:param im: A PIL image. The size must match the target region.
|
| 162 |
+
If the mode does not match, the image is converted to the
|
| 163 |
+
mode of the bitmap image.
|
| 164 |
+
:param box: A 4-tuple defining the left, upper, right, and
|
| 165 |
+
lower pixel coordinate. See :ref:`coordinate-system`. If
|
| 166 |
+
None is given instead of a tuple, all of the image is
|
| 167 |
+
assumed.
|
| 168 |
+
"""
|
| 169 |
+
im.load()
|
| 170 |
+
if self.mode != im.mode:
|
| 171 |
+
im = im.convert(self.mode)
|
| 172 |
+
if box:
|
| 173 |
+
self.image.paste(im.im, box)
|
| 174 |
+
else:
|
| 175 |
+
self.image.paste(im.im)
|
| 176 |
+
|
| 177 |
+
def frombytes(self, buffer: bytes) -> None:
|
| 178 |
+
"""
|
| 179 |
+
Load display memory contents from byte data.
|
| 180 |
+
|
| 181 |
+
:param buffer: A buffer containing display data (usually
|
| 182 |
+
data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
|
| 183 |
+
"""
|
| 184 |
+
self.image.frombytes(buffer)
|
| 185 |
+
|
| 186 |
+
def tobytes(self) -> bytes:
|
| 187 |
+
"""
|
| 188 |
+
Copy display memory contents to bytes object.
|
| 189 |
+
|
| 190 |
+
:return: A bytes object containing display data.
|
| 191 |
+
"""
|
| 192 |
+
return self.image.tobytes()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class Window:
|
| 196 |
+
"""Create a Window with the given title size."""
|
| 197 |
+
|
| 198 |
+
def __init__(
|
| 199 |
+
self, title: str = "PIL", width: int | None = None, height: int | None = None
|
| 200 |
+
) -> None:
|
| 201 |
+
self.hwnd = Image.core.createwindow(
|
| 202 |
+
title, self.__dispatcher, width or 0, height or 0
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
def __dispatcher(self, action, *args):
|
| 206 |
+
return getattr(self, f"ui_handle_{action}")(*args)
|
| 207 |
+
|
| 208 |
+
def ui_handle_clear(self, dc, x0, y0, x1, y1):
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
def ui_handle_damage(self, x0, y0, x1, y1):
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
def ui_handle_destroy(self) -> None:
|
| 215 |
+
pass
|
| 216 |
+
|
| 217 |
+
def ui_handle_repair(self, dc, x0, y0, x1, y1):
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
def ui_handle_resize(self, width, height):
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
def mainloop(self) -> None:
|
| 224 |
+
Image.core.eventloop()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class ImageWindow(Window):
|
| 228 |
+
"""Create an image window which displays the given image."""
|
| 229 |
+
|
| 230 |
+
def __init__(self, image, title="PIL"):
|
| 231 |
+
if not isinstance(image, Dib):
|
| 232 |
+
image = Dib(image)
|
| 233 |
+
self.image = image
|
| 234 |
+
width, height = image.size
|
| 235 |
+
super().__init__(title, width=width, height=height)
|
| 236 |
+
|
| 237 |
+
def ui_handle_repair(self, dc, x0, y0, x1, y1):
|
| 238 |
+
self.image.draw(dc, (x0, y0, x1, y1))
|
valley/lib/python3.10/site-packages/PIL/ImtImagePlugin.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# IM Tools support for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1996-05-27 fl Created (read 8-bit images only)
|
| 9 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997-2001.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996-2001.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
from . import Image, ImageFile
|
| 21 |
+
|
| 22 |
+
#
|
| 23 |
+
# --------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
##
|
| 29 |
+
# Image plugin for IM Tools images.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ImtImageFile(ImageFile.ImageFile):
|
| 33 |
+
format = "IMT"
|
| 34 |
+
format_description = "IM Tools"
|
| 35 |
+
|
| 36 |
+
def _open(self) -> None:
|
| 37 |
+
# Quick rejection: if there's not a LF among the first
|
| 38 |
+
# 100 bytes, this is (probably) not a text header.
|
| 39 |
+
|
| 40 |
+
assert self.fp is not None
|
| 41 |
+
|
| 42 |
+
buffer = self.fp.read(100)
|
| 43 |
+
if b"\n" not in buffer:
|
| 44 |
+
msg = "not an IM file"
|
| 45 |
+
raise SyntaxError(msg)
|
| 46 |
+
|
| 47 |
+
xsize = ysize = 0
|
| 48 |
+
|
| 49 |
+
while True:
|
| 50 |
+
if buffer:
|
| 51 |
+
s = buffer[:1]
|
| 52 |
+
buffer = buffer[1:]
|
| 53 |
+
else:
|
| 54 |
+
s = self.fp.read(1)
|
| 55 |
+
if not s:
|
| 56 |
+
break
|
| 57 |
+
|
| 58 |
+
if s == b"\x0C":
|
| 59 |
+
# image data begins
|
| 60 |
+
self.tile = [
|
| 61 |
+
(
|
| 62 |
+
"raw",
|
| 63 |
+
(0, 0) + self.size,
|
| 64 |
+
self.fp.tell() - len(buffer),
|
| 65 |
+
(self.mode, 0, 1),
|
| 66 |
+
)
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
break
|
| 70 |
+
|
| 71 |
+
else:
|
| 72 |
+
# read key/value pair
|
| 73 |
+
if b"\n" not in buffer:
|
| 74 |
+
buffer += self.fp.read(100)
|
| 75 |
+
lines = buffer.split(b"\n")
|
| 76 |
+
s += lines.pop(0)
|
| 77 |
+
buffer = b"\n".join(lines)
|
| 78 |
+
if len(s) == 1 or len(s) > 100:
|
| 79 |
+
break
|
| 80 |
+
if s[0] == ord(b"*"):
|
| 81 |
+
continue # comment
|
| 82 |
+
|
| 83 |
+
m = field.match(s)
|
| 84 |
+
if not m:
|
| 85 |
+
break
|
| 86 |
+
k, v = m.group(1, 2)
|
| 87 |
+
if k == b"width":
|
| 88 |
+
xsize = int(v)
|
| 89 |
+
self._size = xsize, ysize
|
| 90 |
+
elif k == b"height":
|
| 91 |
+
ysize = int(v)
|
| 92 |
+
self._size = xsize, ysize
|
| 93 |
+
elif k == b"pixel" and v == b"n8":
|
| 94 |
+
self._mode = "L"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
#
|
| 98 |
+
# --------------------------------------------------------------------
|
| 99 |
+
|
| 100 |
+
Image.register_open(ImtImageFile.format, ImtImageFile)
|
| 101 |
+
|
| 102 |
+
#
|
| 103 |
+
# no extension registered (".im" is simply too common)
|
valley/lib/python3.10/site-packages/PIL/IptcImagePlugin.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ned up and added to PIL
|
| 10 |
+
# 2002-06-18 fl Added getiptcinfo helper
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997-2002.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1995.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
from typing import Sequence
|
| 21 |
+
|
| 22 |
+
from . import Image, ImageFile
|
| 23 |
+
from ._binary import i16be as i16
|
| 24 |
+
from ._binary import i32be as i32
|
| 25 |
+
from ._deprecate import deprecate
|
| 26 |
+
|
| 27 |
+
COMPRESSION = {1: "raw", 5: "jpeg"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def __getattr__(name: str) -> bytes:
|
| 31 |
+
if name == "PAD":
|
| 32 |
+
deprecate("IptcImagePlugin.PAD", 12)
|
| 33 |
+
return b"\0\0\0\0"
|
| 34 |
+
msg = f"module '{__name__}' has no attribute '{name}'"
|
| 35 |
+
raise AttributeError(msg)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
#
|
| 39 |
+
# Helpers
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _i(c: bytes) -> int:
|
| 43 |
+
return i32((b"\0\0\0\0" + c)[-4:])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _i8(c: int | bytes) -> int:
|
| 47 |
+
return c if isinstance(c, int) else c[0]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def i(c: bytes) -> int:
|
| 51 |
+
""".. deprecated:: 10.2.0"""
|
| 52 |
+
deprecate("IptcImagePlugin.i", 12)
|
| 53 |
+
return _i(c)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def dump(c: Sequence[int | bytes]) -> None:
|
| 57 |
+
""".. deprecated:: 10.2.0"""
|
| 58 |
+
deprecate("IptcImagePlugin.dump", 12)
|
| 59 |
+
for i in c:
|
| 60 |
+
print(f"{_i8(i):02x}", end=" ")
|
| 61 |
+
print()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
##
|
| 65 |
+
# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
|
| 66 |
+
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class IptcImageFile(ImageFile.ImageFile):
|
| 70 |
+
format = "IPTC"
|
| 71 |
+
format_description = "IPTC/NAA"
|
| 72 |
+
|
| 73 |
+
def getint(self, key: tuple[int, int]) -> int:
|
| 74 |
+
return _i(self.info[key])
|
| 75 |
+
|
| 76 |
+
def field(self) -> tuple[tuple[int, int] | None, int]:
|
| 77 |
+
#
|
| 78 |
+
# get a IPTC field header
|
| 79 |
+
s = self.fp.read(5)
|
| 80 |
+
if not s.strip(b"\x00"):
|
| 81 |
+
return None, 0
|
| 82 |
+
|
| 83 |
+
tag = s[1], s[2]
|
| 84 |
+
|
| 85 |
+
# syntax
|
| 86 |
+
if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:
|
| 87 |
+
msg = "invalid IPTC/NAA file"
|
| 88 |
+
raise SyntaxError(msg)
|
| 89 |
+
|
| 90 |
+
# field size
|
| 91 |
+
size = s[3]
|
| 92 |
+
if size > 132:
|
| 93 |
+
msg = "illegal field length in IPTC/NAA file"
|
| 94 |
+
raise OSError(msg)
|
| 95 |
+
elif size == 128:
|
| 96 |
+
size = 0
|
| 97 |
+
elif size > 128:
|
| 98 |
+
size = _i(self.fp.read(size - 128))
|
| 99 |
+
else:
|
| 100 |
+
size = i16(s, 3)
|
| 101 |
+
|
| 102 |
+
return tag, size
|
| 103 |
+
|
| 104 |
+
def _open(self) -> None:
|
| 105 |
+
# load descriptive fields
|
| 106 |
+
while True:
|
| 107 |
+
offset = self.fp.tell()
|
| 108 |
+
tag, size = self.field()
|
| 109 |
+
if not tag or tag == (8, 10):
|
| 110 |
+
break
|
| 111 |
+
if size:
|
| 112 |
+
tagdata = self.fp.read(size)
|
| 113 |
+
else:
|
| 114 |
+
tagdata = None
|
| 115 |
+
if tag in self.info:
|
| 116 |
+
if isinstance(self.info[tag], list):
|
| 117 |
+
self.info[tag].append(tagdata)
|
| 118 |
+
else:
|
| 119 |
+
self.info[tag] = [self.info[tag], tagdata]
|
| 120 |
+
else:
|
| 121 |
+
self.info[tag] = tagdata
|
| 122 |
+
|
| 123 |
+
# mode
|
| 124 |
+
layers = self.info[(3, 60)][0]
|
| 125 |
+
component = self.info[(3, 60)][1]
|
| 126 |
+
if (3, 65) in self.info:
|
| 127 |
+
id = self.info[(3, 65)][0] - 1
|
| 128 |
+
else:
|
| 129 |
+
id = 0
|
| 130 |
+
if layers == 1 and not component:
|
| 131 |
+
self._mode = "L"
|
| 132 |
+
elif layers == 3 and component:
|
| 133 |
+
self._mode = "RGB"[id]
|
| 134 |
+
elif layers == 4 and component:
|
| 135 |
+
self._mode = "CMYK"[id]
|
| 136 |
+
|
| 137 |
+
# size
|
| 138 |
+
self._size = self.getint((3, 20)), self.getint((3, 30))
|
| 139 |
+
|
| 140 |
+
# compression
|
| 141 |
+
try:
|
| 142 |
+
compression = COMPRESSION[self.getint((3, 120))]
|
| 143 |
+
except KeyError as e:
|
| 144 |
+
msg = "Unknown IPTC image compression"
|
| 145 |
+
raise OSError(msg) from e
|
| 146 |
+
|
| 147 |
+
# tile
|
| 148 |
+
if tag == (8, 10):
|
| 149 |
+
self.tile = [("iptc", (0, 0) + self.size, offset, compression)]
|
| 150 |
+
|
| 151 |
+
def load(self):
|
| 152 |
+
if len(self.tile) != 1 or self.tile[0][0] != "iptc":
|
| 153 |
+
return ImageFile.ImageFile.load(self)
|
| 154 |
+
|
| 155 |
+
offset, compression = self.tile[0][2:]
|
| 156 |
+
|
| 157 |
+
self.fp.seek(offset)
|
| 158 |
+
|
| 159 |
+
# Copy image data to temporary file
|
| 160 |
+
o = BytesIO()
|
| 161 |
+
if compression == "raw":
|
| 162 |
+
# To simplify access to the extracted file,
|
| 163 |
+
# prepend a PPM header
|
| 164 |
+
o.write(b"P5\n%d %d\n255\n" % self.size)
|
| 165 |
+
while True:
|
| 166 |
+
type, size = self.field()
|
| 167 |
+
if type != (8, 10):
|
| 168 |
+
break
|
| 169 |
+
while size > 0:
|
| 170 |
+
s = self.fp.read(min(size, 8192))
|
| 171 |
+
if not s:
|
| 172 |
+
break
|
| 173 |
+
o.write(s)
|
| 174 |
+
size -= len(s)
|
| 175 |
+
|
| 176 |
+
with Image.open(o) as _im:
|
| 177 |
+
_im.load()
|
| 178 |
+
self.im = _im.im
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
Image.register_open(IptcImageFile.format, IptcImageFile)
|
| 182 |
+
|
| 183 |
+
Image.register_extension(IptcImageFile.format, ".iim")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def getiptcinfo(im):
|
| 187 |
+
"""
|
| 188 |
+
Get IPTC information from TIFF, JPEG, or IPTC file.
|
| 189 |
+
|
| 190 |
+
:param im: An image containing IPTC data.
|
| 191 |
+
:returns: A dictionary containing IPTC information, or None if
|
| 192 |
+
no IPTC information block was found.
|
| 193 |
+
"""
|
| 194 |
+
from . import JpegImagePlugin, TiffImagePlugin
|
| 195 |
+
|
| 196 |
+
data = None
|
| 197 |
+
|
| 198 |
+
if isinstance(im, IptcImageFile):
|
| 199 |
+
# return info dictionary right away
|
| 200 |
+
return im.info
|
| 201 |
+
|
| 202 |
+
elif isinstance(im, JpegImagePlugin.JpegImageFile):
|
| 203 |
+
# extract the IPTC/NAA resource
|
| 204 |
+
photoshop = im.info.get("photoshop")
|
| 205 |
+
if photoshop:
|
| 206 |
+
data = photoshop.get(0x0404)
|
| 207 |
+
|
| 208 |
+
elif isinstance(im, TiffImagePlugin.TiffImageFile):
|
| 209 |
+
# get raw data from the IPTC/NAA tag (PhotoShop tags the data
|
| 210 |
+
# as 4-byte integers, so we cannot use the get method...)
|
| 211 |
+
try:
|
| 212 |
+
data = im.tag.tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
|
| 213 |
+
except (AttributeError, KeyError):
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
if data is None:
|
| 217 |
+
return None # no properties
|
| 218 |
+
|
| 219 |
+
# create an IptcImagePlugin object without initializing it
|
| 220 |
+
class FakeImage:
|
| 221 |
+
pass
|
| 222 |
+
|
| 223 |
+
im = FakeImage()
|
| 224 |
+
im.__class__ = IptcImageFile
|
| 225 |
+
|
| 226 |
+
# parse the IPTC information chunk
|
| 227 |
+
im.info = {}
|
| 228 |
+
im.fp = BytesIO(data)
|
| 229 |
+
|
| 230 |
+
try:
|
| 231 |
+
im._open()
|
| 232 |
+
except (IndexError, KeyError):
|
| 233 |
+
pass # expected failure
|
| 234 |
+
|
| 235 |
+
return im.info
|
valley/lib/python3.10/site-packages/PIL/Jpeg2KImagePlugin.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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2021-06-30 rogermb Extract dpi information from the 'resc' header box
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2014 Coriolis Systems Limited
|
| 12 |
+
# Copyright (c) 2014 Alastair Houghton
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
import os
|
| 20 |
+
import struct
|
| 21 |
+
from typing import IO, Tuple, cast
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile, ImagePalette, _binary
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BoxReader:
|
| 27 |
+
"""
|
| 28 |
+
A small helper class to read fields stored in JPEG2000 header boxes
|
| 29 |
+
and to easily step into and read sub-boxes.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, fp, length=-1):
|
| 33 |
+
self.fp = fp
|
| 34 |
+
self.has_length = length >= 0
|
| 35 |
+
self.length = length
|
| 36 |
+
self.remaining_in_box = -1
|
| 37 |
+
|
| 38 |
+
def _can_read(self, num_bytes: int) -> bool:
|
| 39 |
+
if self.has_length and self.fp.tell() + num_bytes > self.length:
|
| 40 |
+
# Outside box: ensure we don't read past the known file length
|
| 41 |
+
return False
|
| 42 |
+
if self.remaining_in_box >= 0:
|
| 43 |
+
# Inside box contents: ensure read does not go past box boundaries
|
| 44 |
+
return num_bytes <= self.remaining_in_box
|
| 45 |
+
else:
|
| 46 |
+
return True # No length known, just read
|
| 47 |
+
|
| 48 |
+
def _read_bytes(self, num_bytes: int) -> bytes:
|
| 49 |
+
if not self._can_read(num_bytes):
|
| 50 |
+
msg = "Not enough data in header"
|
| 51 |
+
raise SyntaxError(msg)
|
| 52 |
+
|
| 53 |
+
data = self.fp.read(num_bytes)
|
| 54 |
+
if len(data) < num_bytes:
|
| 55 |
+
msg = f"Expected to read {num_bytes} bytes but only got {len(data)}."
|
| 56 |
+
raise OSError(msg)
|
| 57 |
+
|
| 58 |
+
if self.remaining_in_box > 0:
|
| 59 |
+
self.remaining_in_box -= num_bytes
|
| 60 |
+
return data
|
| 61 |
+
|
| 62 |
+
def read_fields(self, field_format: str) -> tuple[int | bytes, ...]:
|
| 63 |
+
size = struct.calcsize(field_format)
|
| 64 |
+
data = self._read_bytes(size)
|
| 65 |
+
return struct.unpack(field_format, data)
|
| 66 |
+
|
| 67 |
+
def read_boxes(self) -> BoxReader:
|
| 68 |
+
size = self.remaining_in_box
|
| 69 |
+
data = self._read_bytes(size)
|
| 70 |
+
return BoxReader(io.BytesIO(data), size)
|
| 71 |
+
|
| 72 |
+
def has_next_box(self) -> bool:
|
| 73 |
+
if self.has_length:
|
| 74 |
+
return self.fp.tell() + self.remaining_in_box < self.length
|
| 75 |
+
else:
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
def next_box_type(self) -> bytes:
|
| 79 |
+
# Skip the rest of the box if it has not been read
|
| 80 |
+
if self.remaining_in_box > 0:
|
| 81 |
+
self.fp.seek(self.remaining_in_box, os.SEEK_CUR)
|
| 82 |
+
self.remaining_in_box = -1
|
| 83 |
+
|
| 84 |
+
# Read the length and type of the next box
|
| 85 |
+
lbox, tbox = cast(Tuple[int, bytes], self.read_fields(">I4s"))
|
| 86 |
+
if lbox == 1:
|
| 87 |
+
lbox = cast(int, self.read_fields(">Q")[0])
|
| 88 |
+
hlen = 16
|
| 89 |
+
else:
|
| 90 |
+
hlen = 8
|
| 91 |
+
|
| 92 |
+
if lbox < hlen or not self._can_read(lbox - hlen):
|
| 93 |
+
msg = "Invalid header length"
|
| 94 |
+
raise SyntaxError(msg)
|
| 95 |
+
|
| 96 |
+
self.remaining_in_box = lbox - hlen
|
| 97 |
+
return tbox
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _parse_codestream(fp) -> tuple[tuple[int, int], str]:
|
| 101 |
+
"""Parse the JPEG 2000 codestream to extract the size and component
|
| 102 |
+
count from the SIZ marker segment, returning a PIL (size, mode) tuple."""
|
| 103 |
+
|
| 104 |
+
hdr = fp.read(2)
|
| 105 |
+
lsiz = _binary.i16be(hdr)
|
| 106 |
+
siz = hdr + fp.read(lsiz - 2)
|
| 107 |
+
lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(
|
| 108 |
+
">HHIIIIIIIIH", siz
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
size = (xsiz - xosiz, ysiz - yosiz)
|
| 112 |
+
if csiz == 1:
|
| 113 |
+
ssiz = struct.unpack_from(">B", siz, 38)
|
| 114 |
+
if (ssiz[0] & 0x7F) + 1 > 8:
|
| 115 |
+
mode = "I;16"
|
| 116 |
+
else:
|
| 117 |
+
mode = "L"
|
| 118 |
+
elif csiz == 2:
|
| 119 |
+
mode = "LA"
|
| 120 |
+
elif csiz == 3:
|
| 121 |
+
mode = "RGB"
|
| 122 |
+
elif csiz == 4:
|
| 123 |
+
mode = "RGBA"
|
| 124 |
+
else:
|
| 125 |
+
msg = "unable to determine J2K image mode"
|
| 126 |
+
raise SyntaxError(msg)
|
| 127 |
+
|
| 128 |
+
return size, mode
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _res_to_dpi(num: int, denom: int, exp: int) -> float | None:
|
| 132 |
+
"""Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution,
|
| 133 |
+
calculated as (num / denom) * 10^exp and stored in dots per meter,
|
| 134 |
+
to floating-point dots per inch."""
|
| 135 |
+
if denom == 0:
|
| 136 |
+
return None
|
| 137 |
+
return (254 * num * (10**exp)) / (10000 * denom)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _parse_jp2_header(fp):
|
| 141 |
+
"""Parse the JP2 header box to extract size, component count,
|
| 142 |
+
color space information, and optionally DPI information,
|
| 143 |
+
returning a (size, mode, mimetype, dpi) tuple."""
|
| 144 |
+
|
| 145 |
+
# Find the JP2 header box
|
| 146 |
+
reader = BoxReader(fp)
|
| 147 |
+
header = None
|
| 148 |
+
mimetype = None
|
| 149 |
+
while reader.has_next_box():
|
| 150 |
+
tbox = reader.next_box_type()
|
| 151 |
+
|
| 152 |
+
if tbox == b"jp2h":
|
| 153 |
+
header = reader.read_boxes()
|
| 154 |
+
break
|
| 155 |
+
elif tbox == b"ftyp":
|
| 156 |
+
if reader.read_fields(">4s")[0] == b"jpx ":
|
| 157 |
+
mimetype = "image/jpx"
|
| 158 |
+
|
| 159 |
+
size = None
|
| 160 |
+
mode = None
|
| 161 |
+
bpc = None
|
| 162 |
+
nc = None
|
| 163 |
+
dpi = None # 2-tuple of DPI info, or None
|
| 164 |
+
palette = None
|
| 165 |
+
|
| 166 |
+
while header.has_next_box():
|
| 167 |
+
tbox = header.next_box_type()
|
| 168 |
+
|
| 169 |
+
if tbox == b"ihdr":
|
| 170 |
+
height, width, nc, bpc = header.read_fields(">IIHB")
|
| 171 |
+
size = (width, height)
|
| 172 |
+
if nc == 1 and (bpc & 0x7F) > 8:
|
| 173 |
+
mode = "I;16"
|
| 174 |
+
elif nc == 1:
|
| 175 |
+
mode = "L"
|
| 176 |
+
elif nc == 2:
|
| 177 |
+
mode = "LA"
|
| 178 |
+
elif nc == 3:
|
| 179 |
+
mode = "RGB"
|
| 180 |
+
elif nc == 4:
|
| 181 |
+
mode = "RGBA"
|
| 182 |
+
elif tbox == b"colr" and nc == 4:
|
| 183 |
+
meth, _, _, enumcs = header.read_fields(">BBBI")
|
| 184 |
+
if meth == 1 and enumcs == 12:
|
| 185 |
+
mode = "CMYK"
|
| 186 |
+
elif tbox == b"pclr" and mode in ("L", "LA"):
|
| 187 |
+
ne, npc = header.read_fields(">HB")
|
| 188 |
+
bitdepths = header.read_fields(">" + ("B" * npc))
|
| 189 |
+
if max(bitdepths) <= 8:
|
| 190 |
+
palette = ImagePalette.ImagePalette()
|
| 191 |
+
for i in range(ne):
|
| 192 |
+
palette.getcolor(header.read_fields(">" + ("B" * npc)))
|
| 193 |
+
mode = "P" if mode == "L" else "PA"
|
| 194 |
+
elif tbox == b"res ":
|
| 195 |
+
res = header.read_boxes()
|
| 196 |
+
while res.has_next_box():
|
| 197 |
+
tres = res.next_box_type()
|
| 198 |
+
if tres == b"resc":
|
| 199 |
+
vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
|
| 200 |
+
hres = _res_to_dpi(hrcn, hrcd, hrce)
|
| 201 |
+
vres = _res_to_dpi(vrcn, vrcd, vrce)
|
| 202 |
+
if hres is not None and vres is not None:
|
| 203 |
+
dpi = (hres, vres)
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
if size is None or mode is None:
|
| 207 |
+
msg = "Malformed JP2 header"
|
| 208 |
+
raise SyntaxError(msg)
|
| 209 |
+
|
| 210 |
+
return size, mode, mimetype, dpi, palette
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
##
|
| 214 |
+
# Image plugin for JPEG2000 images.
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class Jpeg2KImageFile(ImageFile.ImageFile):
|
| 218 |
+
format = "JPEG2000"
|
| 219 |
+
format_description = "JPEG 2000 (ISO 15444)"
|
| 220 |
+
|
| 221 |
+
def _open(self) -> None:
|
| 222 |
+
sig = self.fp.read(4)
|
| 223 |
+
if sig == b"\xff\x4f\xff\x51":
|
| 224 |
+
self.codec = "j2k"
|
| 225 |
+
self._size, self._mode = _parse_codestream(self.fp)
|
| 226 |
+
else:
|
| 227 |
+
sig = sig + self.fp.read(8)
|
| 228 |
+
|
| 229 |
+
if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":
|
| 230 |
+
self.codec = "jp2"
|
| 231 |
+
header = _parse_jp2_header(self.fp)
|
| 232 |
+
self._size, self._mode, self.custom_mimetype, dpi, self.palette = header
|
| 233 |
+
if dpi is not None:
|
| 234 |
+
self.info["dpi"] = dpi
|
| 235 |
+
if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
|
| 236 |
+
self._parse_comment()
|
| 237 |
+
else:
|
| 238 |
+
msg = "not a JPEG 2000 file"
|
| 239 |
+
raise SyntaxError(msg)
|
| 240 |
+
|
| 241 |
+
self._reduce = 0
|
| 242 |
+
self.layers = 0
|
| 243 |
+
|
| 244 |
+
fd = -1
|
| 245 |
+
length = -1
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
fd = self.fp.fileno()
|
| 249 |
+
length = os.fstat(fd).st_size
|
| 250 |
+
except Exception:
|
| 251 |
+
fd = -1
|
| 252 |
+
try:
|
| 253 |
+
pos = self.fp.tell()
|
| 254 |
+
self.fp.seek(0, io.SEEK_END)
|
| 255 |
+
length = self.fp.tell()
|
| 256 |
+
self.fp.seek(pos)
|
| 257 |
+
except Exception:
|
| 258 |
+
length = -1
|
| 259 |
+
|
| 260 |
+
self.tile = [
|
| 261 |
+
(
|
| 262 |
+
"jpeg2k",
|
| 263 |
+
(0, 0) + self.size,
|
| 264 |
+
0,
|
| 265 |
+
(self.codec, self._reduce, self.layers, fd, length),
|
| 266 |
+
)
|
| 267 |
+
]
|
| 268 |
+
|
| 269 |
+
def _parse_comment(self) -> None:
|
| 270 |
+
hdr = self.fp.read(2)
|
| 271 |
+
length = _binary.i16be(hdr)
|
| 272 |
+
self.fp.seek(length - 2, os.SEEK_CUR)
|
| 273 |
+
|
| 274 |
+
while True:
|
| 275 |
+
marker = self.fp.read(2)
|
| 276 |
+
if not marker:
|
| 277 |
+
break
|
| 278 |
+
typ = marker[1]
|
| 279 |
+
if typ in (0x90, 0xD9):
|
| 280 |
+
# Start of tile or end of codestream
|
| 281 |
+
break
|
| 282 |
+
hdr = self.fp.read(2)
|
| 283 |
+
length = _binary.i16be(hdr)
|
| 284 |
+
if typ == 0x64:
|
| 285 |
+
# Comment
|
| 286 |
+
self.info["comment"] = self.fp.read(length - 2)[2:]
|
| 287 |
+
break
|
| 288 |
+
else:
|
| 289 |
+
self.fp.seek(length - 2, os.SEEK_CUR)
|
| 290 |
+
|
| 291 |
+
@property
|
| 292 |
+
def reduce(self):
|
| 293 |
+
# https://github.com/python-pillow/Pillow/issues/4343 found that the
|
| 294 |
+
# new Image 'reduce' method was shadowed by this plugin's 'reduce'
|
| 295 |
+
# property. This attempts to allow for both scenarios
|
| 296 |
+
return self._reduce or super().reduce
|
| 297 |
+
|
| 298 |
+
@reduce.setter
|
| 299 |
+
def reduce(self, value):
|
| 300 |
+
self._reduce = value
|
| 301 |
+
|
| 302 |
+
def load(self):
|
| 303 |
+
if self.tile and self._reduce:
|
| 304 |
+
power = 1 << self._reduce
|
| 305 |
+
adjust = power >> 1
|
| 306 |
+
self._size = (
|
| 307 |
+
int((self.size[0] + adjust) / power),
|
| 308 |
+
int((self.size[1] + adjust) / power),
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# Update the reduce and layers settings
|
| 312 |
+
t = self.tile[0]
|
| 313 |
+
t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
|
| 314 |
+
self.tile = [(t[0], (0, 0) + self.size, t[2], t3)]
|
| 315 |
+
|
| 316 |
+
return ImageFile.ImageFile.load(self)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _accept(prefix: bytes) -> bool:
|
| 320 |
+
return (
|
| 321 |
+
prefix[:4] == b"\xff\x4f\xff\x51"
|
| 322 |
+
or prefix[:12] == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ------------------------------------------------------------
|
| 327 |
+
# Save support
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 331 |
+
# Get the keyword arguments
|
| 332 |
+
info = im.encoderinfo
|
| 333 |
+
|
| 334 |
+
if isinstance(filename, str):
|
| 335 |
+
filename = filename.encode()
|
| 336 |
+
if filename.endswith(b".j2k") or info.get("no_jp2", False):
|
| 337 |
+
kind = "j2k"
|
| 338 |
+
else:
|
| 339 |
+
kind = "jp2"
|
| 340 |
+
|
| 341 |
+
offset = info.get("offset", None)
|
| 342 |
+
tile_offset = info.get("tile_offset", None)
|
| 343 |
+
tile_size = info.get("tile_size", None)
|
| 344 |
+
quality_mode = info.get("quality_mode", "rates")
|
| 345 |
+
quality_layers = info.get("quality_layers", None)
|
| 346 |
+
if quality_layers is not None and not (
|
| 347 |
+
isinstance(quality_layers, (list, tuple))
|
| 348 |
+
and all(
|
| 349 |
+
isinstance(quality_layer, (int, float)) for quality_layer in quality_layers
|
| 350 |
+
)
|
| 351 |
+
):
|
| 352 |
+
msg = "quality_layers must be a sequence of numbers"
|
| 353 |
+
raise ValueError(msg)
|
| 354 |
+
|
| 355 |
+
num_resolutions = info.get("num_resolutions", 0)
|
| 356 |
+
cblk_size = info.get("codeblock_size", None)
|
| 357 |
+
precinct_size = info.get("precinct_size", None)
|
| 358 |
+
irreversible = info.get("irreversible", False)
|
| 359 |
+
progression = info.get("progression", "LRCP")
|
| 360 |
+
cinema_mode = info.get("cinema_mode", "no")
|
| 361 |
+
mct = info.get("mct", 0)
|
| 362 |
+
signed = info.get("signed", False)
|
| 363 |
+
comment = info.get("comment")
|
| 364 |
+
if isinstance(comment, str):
|
| 365 |
+
comment = comment.encode()
|
| 366 |
+
plt = info.get("plt", False)
|
| 367 |
+
|
| 368 |
+
fd = -1
|
| 369 |
+
if hasattr(fp, "fileno"):
|
| 370 |
+
try:
|
| 371 |
+
fd = fp.fileno()
|
| 372 |
+
except Exception:
|
| 373 |
+
fd = -1
|
| 374 |
+
|
| 375 |
+
im.encoderconfig = (
|
| 376 |
+
offset,
|
| 377 |
+
tile_offset,
|
| 378 |
+
tile_size,
|
| 379 |
+
quality_mode,
|
| 380 |
+
quality_layers,
|
| 381 |
+
num_resolutions,
|
| 382 |
+
cblk_size,
|
| 383 |
+
precinct_size,
|
| 384 |
+
irreversible,
|
| 385 |
+
progression,
|
| 386 |
+
cinema_mode,
|
| 387 |
+
mct,
|
| 388 |
+
signed,
|
| 389 |
+
fd,
|
| 390 |
+
comment,
|
| 391 |
+
plt,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
ImageFile._save(im, fp, [("jpeg2k", (0, 0) + im.size, 0, kind)])
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
# ------------------------------------------------------------
|
| 398 |
+
# Registry stuff
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept)
|
| 402 |
+
Image.register_save(Jpeg2KImageFile.format, _save)
|
| 403 |
+
|
| 404 |
+
Image.register_extensions(
|
| 405 |
+
Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"]
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
Image.register_mime(Jpeg2KImageFile.format, "image/jp2")
|
valley/lib/python3.10/site-packages/PIL/JpegImagePlugin.py
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# JPEG (JFIF) file handling
|
| 6 |
+
#
|
| 7 |
+
# See "Digital Compression and Coding of Continuous-Tone Still Images,
|
| 8 |
+
# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
|
| 9 |
+
#
|
| 10 |
+
# History:
|
| 11 |
+
# 1995-09-09 fl Created
|
| 12 |
+
# 1995-09-13 fl Added full parser
|
| 13 |
+
# 1996-03-25 fl Added hack to use the IJG command line utilities
|
| 14 |
+
# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
|
| 15 |
+
# 1996-05-28 fl Added draft support, JFIF version (0.1)
|
| 16 |
+
# 1996-12-30 fl Added encoder options, added progression property (0.2)
|
| 17 |
+
# 1997-08-27 fl Save mode 1 images as BW (0.3)
|
| 18 |
+
# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
|
| 19 |
+
# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
|
| 20 |
+
# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
|
| 21 |
+
# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
|
| 22 |
+
# 2003-04-25 fl Added experimental EXIF decoder (0.5)
|
| 23 |
+
# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
|
| 24 |
+
# 2003-09-13 fl Extract COM markers
|
| 25 |
+
# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
|
| 26 |
+
# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
|
| 27 |
+
# 2009-03-08 fl Added subsampling support (from Justin Huff).
|
| 28 |
+
#
|
| 29 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 30 |
+
# Copyright (c) 1995-1996 by Fredrik Lundh.
|
| 31 |
+
#
|
| 32 |
+
# See the README file for information on usage and redistribution.
|
| 33 |
+
#
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import array
|
| 37 |
+
import io
|
| 38 |
+
import math
|
| 39 |
+
import os
|
| 40 |
+
import struct
|
| 41 |
+
import subprocess
|
| 42 |
+
import sys
|
| 43 |
+
import tempfile
|
| 44 |
+
import warnings
|
| 45 |
+
from typing import IO, Any
|
| 46 |
+
|
| 47 |
+
from . import Image, ImageFile
|
| 48 |
+
from ._binary import i16be as i16
|
| 49 |
+
from ._binary import i32be as i32
|
| 50 |
+
from ._binary import o8
|
| 51 |
+
from ._binary import o16be as o16
|
| 52 |
+
from .JpegPresets import presets
|
| 53 |
+
|
| 54 |
+
#
|
| 55 |
+
# Parser
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def Skip(self: JpegImageFile, marker: int) -> None:
|
| 59 |
+
n = i16(self.fp.read(2)) - 2
|
| 60 |
+
ImageFile._safe_read(self.fp, n)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def APP(self, marker):
|
| 64 |
+
#
|
| 65 |
+
# Application marker. Store these in the APP dictionary.
|
| 66 |
+
# Also look for well-known application markers.
|
| 67 |
+
|
| 68 |
+
n = i16(self.fp.read(2)) - 2
|
| 69 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 70 |
+
|
| 71 |
+
app = "APP%d" % (marker & 15)
|
| 72 |
+
|
| 73 |
+
self.app[app] = s # compatibility
|
| 74 |
+
self.applist.append((app, s))
|
| 75 |
+
|
| 76 |
+
if marker == 0xFFE0 and s[:4] == b"JFIF":
|
| 77 |
+
# extract JFIF information
|
| 78 |
+
self.info["jfif"] = version = i16(s, 5) # version
|
| 79 |
+
self.info["jfif_version"] = divmod(version, 256)
|
| 80 |
+
# extract JFIF properties
|
| 81 |
+
try:
|
| 82 |
+
jfif_unit = s[7]
|
| 83 |
+
jfif_density = i16(s, 8), i16(s, 10)
|
| 84 |
+
except Exception:
|
| 85 |
+
pass
|
| 86 |
+
else:
|
| 87 |
+
if jfif_unit == 1:
|
| 88 |
+
self.info["dpi"] = jfif_density
|
| 89 |
+
self.info["jfif_unit"] = jfif_unit
|
| 90 |
+
self.info["jfif_density"] = jfif_density
|
| 91 |
+
elif marker == 0xFFE1 and s[:6] == b"Exif\0\0":
|
| 92 |
+
# extract EXIF information
|
| 93 |
+
if "exif" in self.info:
|
| 94 |
+
self.info["exif"] += s[6:]
|
| 95 |
+
else:
|
| 96 |
+
self.info["exif"] = s
|
| 97 |
+
self._exif_offset = self.fp.tell() - n + 6
|
| 98 |
+
elif marker == 0xFFE1 and s[:29] == b"http://ns.adobe.com/xap/1.0/\x00":
|
| 99 |
+
self.info["xmp"] = s.split(b"\x00", 1)[1]
|
| 100 |
+
elif marker == 0xFFE2 and s[:5] == b"FPXR\0":
|
| 101 |
+
# extract FlashPix information (incomplete)
|
| 102 |
+
self.info["flashpix"] = s # FIXME: value will change
|
| 103 |
+
elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0":
|
| 104 |
+
# Since an ICC profile can be larger than the maximum size of
|
| 105 |
+
# a JPEG marker (64K), we need provisions to split it into
|
| 106 |
+
# multiple markers. The format defined by the ICC specifies
|
| 107 |
+
# one or more APP2 markers containing the following data:
|
| 108 |
+
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
|
| 109 |
+
# Marker sequence number 1, 2, etc (1 byte)
|
| 110 |
+
# Number of markers Total of APP2's used (1 byte)
|
| 111 |
+
# Profile data (remainder of APP2 data)
|
| 112 |
+
# Decoders should use the marker sequence numbers to
|
| 113 |
+
# reassemble the profile, rather than assuming that the APP2
|
| 114 |
+
# markers appear in the correct sequence.
|
| 115 |
+
self.icclist.append(s)
|
| 116 |
+
elif marker == 0xFFED and s[:14] == b"Photoshop 3.0\x00":
|
| 117 |
+
# parse the image resource block
|
| 118 |
+
offset = 14
|
| 119 |
+
photoshop = self.info.setdefault("photoshop", {})
|
| 120 |
+
while s[offset : offset + 4] == b"8BIM":
|
| 121 |
+
try:
|
| 122 |
+
offset += 4
|
| 123 |
+
# resource code
|
| 124 |
+
code = i16(s, offset)
|
| 125 |
+
offset += 2
|
| 126 |
+
# resource name (usually empty)
|
| 127 |
+
name_len = s[offset]
|
| 128 |
+
# name = s[offset+1:offset+1+name_len]
|
| 129 |
+
offset += 1 + name_len
|
| 130 |
+
offset += offset & 1 # align
|
| 131 |
+
# resource data block
|
| 132 |
+
size = i32(s, offset)
|
| 133 |
+
offset += 4
|
| 134 |
+
data = s[offset : offset + size]
|
| 135 |
+
if code == 0x03ED: # ResolutionInfo
|
| 136 |
+
data = {
|
| 137 |
+
"XResolution": i32(data, 0) / 65536,
|
| 138 |
+
"DisplayedUnitsX": i16(data, 4),
|
| 139 |
+
"YResolution": i32(data, 8) / 65536,
|
| 140 |
+
"DisplayedUnitsY": i16(data, 12),
|
| 141 |
+
}
|
| 142 |
+
photoshop[code] = data
|
| 143 |
+
offset += size
|
| 144 |
+
offset += offset & 1 # align
|
| 145 |
+
except struct.error:
|
| 146 |
+
break # insufficient data
|
| 147 |
+
|
| 148 |
+
elif marker == 0xFFEE and s[:5] == b"Adobe":
|
| 149 |
+
self.info["adobe"] = i16(s, 5)
|
| 150 |
+
# extract Adobe custom properties
|
| 151 |
+
try:
|
| 152 |
+
adobe_transform = s[11]
|
| 153 |
+
except IndexError:
|
| 154 |
+
pass
|
| 155 |
+
else:
|
| 156 |
+
self.info["adobe_transform"] = adobe_transform
|
| 157 |
+
elif marker == 0xFFE2 and s[:4] == b"MPF\0":
|
| 158 |
+
# extract MPO information
|
| 159 |
+
self.info["mp"] = s[4:]
|
| 160 |
+
# offset is current location minus buffer size
|
| 161 |
+
# plus constant header size
|
| 162 |
+
self.info["mpoffset"] = self.fp.tell() - n + 4
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def COM(self: JpegImageFile, marker: int) -> None:
|
| 166 |
+
#
|
| 167 |
+
# Comment marker. Store these in the APP dictionary.
|
| 168 |
+
n = i16(self.fp.read(2)) - 2
|
| 169 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 170 |
+
|
| 171 |
+
self.info["comment"] = s
|
| 172 |
+
self.app["COM"] = s # compatibility
|
| 173 |
+
self.applist.append(("COM", s))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def SOF(self: JpegImageFile, marker: int) -> None:
|
| 177 |
+
#
|
| 178 |
+
# Start of frame marker. Defines the size and mode of the
|
| 179 |
+
# image. JPEG is colour blind, so we use some simple
|
| 180 |
+
# heuristics to map the number of layers to an appropriate
|
| 181 |
+
# mode. Note that this could be made a bit brighter, by
|
| 182 |
+
# looking for JFIF and Adobe APP markers.
|
| 183 |
+
|
| 184 |
+
n = i16(self.fp.read(2)) - 2
|
| 185 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 186 |
+
self._size = i16(s, 3), i16(s, 1)
|
| 187 |
+
|
| 188 |
+
self.bits = s[0]
|
| 189 |
+
if self.bits != 8:
|
| 190 |
+
msg = f"cannot handle {self.bits}-bit layers"
|
| 191 |
+
raise SyntaxError(msg)
|
| 192 |
+
|
| 193 |
+
self.layers = s[5]
|
| 194 |
+
if self.layers == 1:
|
| 195 |
+
self._mode = "L"
|
| 196 |
+
elif self.layers == 3:
|
| 197 |
+
self._mode = "RGB"
|
| 198 |
+
elif self.layers == 4:
|
| 199 |
+
self._mode = "CMYK"
|
| 200 |
+
else:
|
| 201 |
+
msg = f"cannot handle {self.layers}-layer images"
|
| 202 |
+
raise SyntaxError(msg)
|
| 203 |
+
|
| 204 |
+
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
|
| 205 |
+
self.info["progressive"] = self.info["progression"] = 1
|
| 206 |
+
|
| 207 |
+
if self.icclist:
|
| 208 |
+
# fixup icc profile
|
| 209 |
+
self.icclist.sort() # sort by sequence number
|
| 210 |
+
if self.icclist[0][13] == len(self.icclist):
|
| 211 |
+
profile = [p[14:] for p in self.icclist]
|
| 212 |
+
icc_profile = b"".join(profile)
|
| 213 |
+
else:
|
| 214 |
+
icc_profile = None # wrong number of fragments
|
| 215 |
+
self.info["icc_profile"] = icc_profile
|
| 216 |
+
self.icclist = []
|
| 217 |
+
|
| 218 |
+
for i in range(6, len(s), 3):
|
| 219 |
+
t = s[i : i + 3]
|
| 220 |
+
# 4-tuples: id, vsamp, hsamp, qtable
|
| 221 |
+
self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def DQT(self: JpegImageFile, marker: int) -> None:
|
| 225 |
+
#
|
| 226 |
+
# Define quantization table. Note that there might be more
|
| 227 |
+
# than one table in each marker.
|
| 228 |
+
|
| 229 |
+
# FIXME: The quantization tables can be used to estimate the
|
| 230 |
+
# compression quality.
|
| 231 |
+
|
| 232 |
+
n = i16(self.fp.read(2)) - 2
|
| 233 |
+
s = ImageFile._safe_read(self.fp, n)
|
| 234 |
+
while len(s):
|
| 235 |
+
v = s[0]
|
| 236 |
+
precision = 1 if (v // 16 == 0) else 2 # in bytes
|
| 237 |
+
qt_length = 1 + precision * 64
|
| 238 |
+
if len(s) < qt_length:
|
| 239 |
+
msg = "bad quantization table marker"
|
| 240 |
+
raise SyntaxError(msg)
|
| 241 |
+
data = array.array("B" if precision == 1 else "H", s[1:qt_length])
|
| 242 |
+
if sys.byteorder == "little" and precision > 1:
|
| 243 |
+
data.byteswap() # the values are always big-endian
|
| 244 |
+
self.quantization[v & 15] = [data[i] for i in zigzag_index]
|
| 245 |
+
s = s[qt_length:]
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
#
|
| 249 |
+
# JPEG marker table
|
| 250 |
+
|
| 251 |
+
MARKER = {
|
| 252 |
+
0xFFC0: ("SOF0", "Baseline DCT", SOF),
|
| 253 |
+
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
|
| 254 |
+
0xFFC2: ("SOF2", "Progressive DCT", SOF),
|
| 255 |
+
0xFFC3: ("SOF3", "Spatial lossless", SOF),
|
| 256 |
+
0xFFC4: ("DHT", "Define Huffman table", Skip),
|
| 257 |
+
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
|
| 258 |
+
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
|
| 259 |
+
0xFFC7: ("SOF7", "Differential spatial", SOF),
|
| 260 |
+
0xFFC8: ("JPG", "Extension", None),
|
| 261 |
+
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
|
| 262 |
+
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
|
| 263 |
+
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
|
| 264 |
+
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
|
| 265 |
+
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
|
| 266 |
+
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
|
| 267 |
+
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
|
| 268 |
+
0xFFD0: ("RST0", "Restart 0", None),
|
| 269 |
+
0xFFD1: ("RST1", "Restart 1", None),
|
| 270 |
+
0xFFD2: ("RST2", "Restart 2", None),
|
| 271 |
+
0xFFD3: ("RST3", "Restart 3", None),
|
| 272 |
+
0xFFD4: ("RST4", "Restart 4", None),
|
| 273 |
+
0xFFD5: ("RST5", "Restart 5", None),
|
| 274 |
+
0xFFD6: ("RST6", "Restart 6", None),
|
| 275 |
+
0xFFD7: ("RST7", "Restart 7", None),
|
| 276 |
+
0xFFD8: ("SOI", "Start of image", None),
|
| 277 |
+
0xFFD9: ("EOI", "End of image", None),
|
| 278 |
+
0xFFDA: ("SOS", "Start of scan", Skip),
|
| 279 |
+
0xFFDB: ("DQT", "Define quantization table", DQT),
|
| 280 |
+
0xFFDC: ("DNL", "Define number of lines", Skip),
|
| 281 |
+
0xFFDD: ("DRI", "Define restart interval", Skip),
|
| 282 |
+
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
|
| 283 |
+
0xFFDF: ("EXP", "Expand reference component", Skip),
|
| 284 |
+
0xFFE0: ("APP0", "Application segment 0", APP),
|
| 285 |
+
0xFFE1: ("APP1", "Application segment 1", APP),
|
| 286 |
+
0xFFE2: ("APP2", "Application segment 2", APP),
|
| 287 |
+
0xFFE3: ("APP3", "Application segment 3", APP),
|
| 288 |
+
0xFFE4: ("APP4", "Application segment 4", APP),
|
| 289 |
+
0xFFE5: ("APP5", "Application segment 5", APP),
|
| 290 |
+
0xFFE6: ("APP6", "Application segment 6", APP),
|
| 291 |
+
0xFFE7: ("APP7", "Application segment 7", APP),
|
| 292 |
+
0xFFE8: ("APP8", "Application segment 8", APP),
|
| 293 |
+
0xFFE9: ("APP9", "Application segment 9", APP),
|
| 294 |
+
0xFFEA: ("APP10", "Application segment 10", APP),
|
| 295 |
+
0xFFEB: ("APP11", "Application segment 11", APP),
|
| 296 |
+
0xFFEC: ("APP12", "Application segment 12", APP),
|
| 297 |
+
0xFFED: ("APP13", "Application segment 13", APP),
|
| 298 |
+
0xFFEE: ("APP14", "Application segment 14", APP),
|
| 299 |
+
0xFFEF: ("APP15", "Application segment 15", APP),
|
| 300 |
+
0xFFF0: ("JPG0", "Extension 0", None),
|
| 301 |
+
0xFFF1: ("JPG1", "Extension 1", None),
|
| 302 |
+
0xFFF2: ("JPG2", "Extension 2", None),
|
| 303 |
+
0xFFF3: ("JPG3", "Extension 3", None),
|
| 304 |
+
0xFFF4: ("JPG4", "Extension 4", None),
|
| 305 |
+
0xFFF5: ("JPG5", "Extension 5", None),
|
| 306 |
+
0xFFF6: ("JPG6", "Extension 6", None),
|
| 307 |
+
0xFFF7: ("JPG7", "Extension 7", None),
|
| 308 |
+
0xFFF8: ("JPG8", "Extension 8", None),
|
| 309 |
+
0xFFF9: ("JPG9", "Extension 9", None),
|
| 310 |
+
0xFFFA: ("JPG10", "Extension 10", None),
|
| 311 |
+
0xFFFB: ("JPG11", "Extension 11", None),
|
| 312 |
+
0xFFFC: ("JPG12", "Extension 12", None),
|
| 313 |
+
0xFFFD: ("JPG13", "Extension 13", None),
|
| 314 |
+
0xFFFE: ("COM", "Comment", COM),
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _accept(prefix: bytes) -> bool:
|
| 319 |
+
# Magic number was taken from https://en.wikipedia.org/wiki/JPEG
|
| 320 |
+
return prefix[:3] == b"\xFF\xD8\xFF"
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
##
|
| 324 |
+
# Image plugin for JPEG and JFIF images.
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class JpegImageFile(ImageFile.ImageFile):
|
| 328 |
+
format = "JPEG"
|
| 329 |
+
format_description = "JPEG (ISO 10918)"
|
| 330 |
+
|
| 331 |
+
def _open(self):
|
| 332 |
+
s = self.fp.read(3)
|
| 333 |
+
|
| 334 |
+
if not _accept(s):
|
| 335 |
+
msg = "not a JPEG file"
|
| 336 |
+
raise SyntaxError(msg)
|
| 337 |
+
s = b"\xFF"
|
| 338 |
+
|
| 339 |
+
# Create attributes
|
| 340 |
+
self.bits = self.layers = 0
|
| 341 |
+
|
| 342 |
+
# JPEG specifics (internal)
|
| 343 |
+
self.layer = []
|
| 344 |
+
self.huffman_dc = {}
|
| 345 |
+
self.huffman_ac = {}
|
| 346 |
+
self.quantization = {}
|
| 347 |
+
self.app = {} # compatibility
|
| 348 |
+
self.applist = []
|
| 349 |
+
self.icclist = []
|
| 350 |
+
|
| 351 |
+
while True:
|
| 352 |
+
i = s[0]
|
| 353 |
+
if i == 0xFF:
|
| 354 |
+
s = s + self.fp.read(1)
|
| 355 |
+
i = i16(s)
|
| 356 |
+
else:
|
| 357 |
+
# Skip non-0xFF junk
|
| 358 |
+
s = self.fp.read(1)
|
| 359 |
+
continue
|
| 360 |
+
|
| 361 |
+
if i in MARKER:
|
| 362 |
+
name, description, handler = MARKER[i]
|
| 363 |
+
if handler is not None:
|
| 364 |
+
handler(self, i)
|
| 365 |
+
if i == 0xFFDA: # start of scan
|
| 366 |
+
rawmode = self.mode
|
| 367 |
+
if self.mode == "CMYK":
|
| 368 |
+
rawmode = "CMYK;I" # assume adobe conventions
|
| 369 |
+
self.tile = [("jpeg", (0, 0) + self.size, 0, (rawmode, ""))]
|
| 370 |
+
# self.__offset = self.fp.tell()
|
| 371 |
+
break
|
| 372 |
+
s = self.fp.read(1)
|
| 373 |
+
elif i in {0, 0xFFFF}:
|
| 374 |
+
# padded marker or junk; move on
|
| 375 |
+
s = b"\xff"
|
| 376 |
+
elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
|
| 377 |
+
s = self.fp.read(1)
|
| 378 |
+
else:
|
| 379 |
+
msg = "no marker found"
|
| 380 |
+
raise SyntaxError(msg)
|
| 381 |
+
|
| 382 |
+
self._read_dpi_from_exif()
|
| 383 |
+
|
| 384 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 385 |
+
"""
|
| 386 |
+
internal: read more image data
|
| 387 |
+
For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
|
| 388 |
+
so libjpeg can finish decoding
|
| 389 |
+
"""
|
| 390 |
+
s = self.fp.read(read_bytes)
|
| 391 |
+
|
| 392 |
+
if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
|
| 393 |
+
# Premature EOF.
|
| 394 |
+
# Pretend file is finished adding EOI marker
|
| 395 |
+
self._ended = True
|
| 396 |
+
return b"\xFF\xD9"
|
| 397 |
+
|
| 398 |
+
return s
|
| 399 |
+
|
| 400 |
+
def draft(
|
| 401 |
+
self, mode: str | None, size: tuple[int, int] | None
|
| 402 |
+
) -> tuple[str, tuple[int, int, float, float]] | None:
|
| 403 |
+
if len(self.tile) != 1:
|
| 404 |
+
return None
|
| 405 |
+
|
| 406 |
+
# Protect from second call
|
| 407 |
+
if self.decoderconfig:
|
| 408 |
+
return None
|
| 409 |
+
|
| 410 |
+
d, e, o, a = self.tile[0]
|
| 411 |
+
scale = 1
|
| 412 |
+
original_size = self.size
|
| 413 |
+
|
| 414 |
+
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
|
| 415 |
+
self._mode = mode
|
| 416 |
+
a = mode, ""
|
| 417 |
+
|
| 418 |
+
if size:
|
| 419 |
+
scale = min(self.size[0] // size[0], self.size[1] // size[1])
|
| 420 |
+
for s in [8, 4, 2, 1]:
|
| 421 |
+
if scale >= s:
|
| 422 |
+
break
|
| 423 |
+
e = (
|
| 424 |
+
e[0],
|
| 425 |
+
e[1],
|
| 426 |
+
(e[2] - e[0] + s - 1) // s + e[0],
|
| 427 |
+
(e[3] - e[1] + s - 1) // s + e[1],
|
| 428 |
+
)
|
| 429 |
+
self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
|
| 430 |
+
scale = s
|
| 431 |
+
|
| 432 |
+
self.tile = [(d, e, o, a)]
|
| 433 |
+
self.decoderconfig = (scale, 0)
|
| 434 |
+
|
| 435 |
+
box = (0, 0, original_size[0] / scale, original_size[1] / scale)
|
| 436 |
+
return self.mode, box
|
| 437 |
+
|
| 438 |
+
def load_djpeg(self) -> None:
|
| 439 |
+
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
|
| 440 |
+
|
| 441 |
+
f, path = tempfile.mkstemp()
|
| 442 |
+
os.close(f)
|
| 443 |
+
if os.path.exists(self.filename):
|
| 444 |
+
subprocess.check_call(["djpeg", "-outfile", path, self.filename])
|
| 445 |
+
else:
|
| 446 |
+
try:
|
| 447 |
+
os.unlink(path)
|
| 448 |
+
except OSError:
|
| 449 |
+
pass
|
| 450 |
+
|
| 451 |
+
msg = "Invalid Filename"
|
| 452 |
+
raise ValueError(msg)
|
| 453 |
+
|
| 454 |
+
try:
|
| 455 |
+
with Image.open(path) as _im:
|
| 456 |
+
_im.load()
|
| 457 |
+
self.im = _im.im
|
| 458 |
+
finally:
|
| 459 |
+
try:
|
| 460 |
+
os.unlink(path)
|
| 461 |
+
except OSError:
|
| 462 |
+
pass
|
| 463 |
+
|
| 464 |
+
self._mode = self.im.mode
|
| 465 |
+
self._size = self.im.size
|
| 466 |
+
|
| 467 |
+
self.tile = []
|
| 468 |
+
|
| 469 |
+
def _getexif(self) -> dict[str, Any] | None:
|
| 470 |
+
return _getexif(self)
|
| 471 |
+
|
| 472 |
+
def _read_dpi_from_exif(self) -> None:
|
| 473 |
+
# If DPI isn't in JPEG header, fetch from EXIF
|
| 474 |
+
if "dpi" in self.info or "exif" not in self.info:
|
| 475 |
+
return
|
| 476 |
+
try:
|
| 477 |
+
exif = self.getexif()
|
| 478 |
+
resolution_unit = exif[0x0128]
|
| 479 |
+
x_resolution = exif[0x011A]
|
| 480 |
+
try:
|
| 481 |
+
dpi = float(x_resolution[0]) / x_resolution[1]
|
| 482 |
+
except TypeError:
|
| 483 |
+
dpi = x_resolution
|
| 484 |
+
if math.isnan(dpi):
|
| 485 |
+
msg = "DPI is not a number"
|
| 486 |
+
raise ValueError(msg)
|
| 487 |
+
if resolution_unit == 3: # cm
|
| 488 |
+
# 1 dpcm = 2.54 dpi
|
| 489 |
+
dpi *= 2.54
|
| 490 |
+
self.info["dpi"] = dpi, dpi
|
| 491 |
+
except (
|
| 492 |
+
struct.error, # truncated EXIF
|
| 493 |
+
KeyError, # dpi not included
|
| 494 |
+
SyntaxError, # invalid/unreadable EXIF
|
| 495 |
+
TypeError, # dpi is an invalid float
|
| 496 |
+
ValueError, # dpi is an invalid float
|
| 497 |
+
ZeroDivisionError, # invalid dpi rational value
|
| 498 |
+
):
|
| 499 |
+
self.info["dpi"] = 72, 72
|
| 500 |
+
|
| 501 |
+
def _getmp(self):
|
| 502 |
+
return _getmp(self)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _getexif(self) -> dict[str, Any] | None:
|
| 506 |
+
if "exif" not in self.info:
|
| 507 |
+
return None
|
| 508 |
+
return self.getexif()._get_merged_dict()
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _getmp(self):
|
| 512 |
+
# Extract MP information. This method was inspired by the "highly
|
| 513 |
+
# experimental" _getexif version that's been in use for years now,
|
| 514 |
+
# itself based on the ImageFileDirectory class in the TIFF plugin.
|
| 515 |
+
|
| 516 |
+
# The MP record essentially consists of a TIFF file embedded in a JPEG
|
| 517 |
+
# application marker.
|
| 518 |
+
try:
|
| 519 |
+
data = self.info["mp"]
|
| 520 |
+
except KeyError:
|
| 521 |
+
return None
|
| 522 |
+
file_contents = io.BytesIO(data)
|
| 523 |
+
head = file_contents.read(8)
|
| 524 |
+
endianness = ">" if head[:4] == b"\x4d\x4d\x00\x2a" else "<"
|
| 525 |
+
# process dictionary
|
| 526 |
+
from . import TiffImagePlugin
|
| 527 |
+
|
| 528 |
+
try:
|
| 529 |
+
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
| 530 |
+
file_contents.seek(info.next)
|
| 531 |
+
info.load(file_contents)
|
| 532 |
+
mp = dict(info)
|
| 533 |
+
except Exception as e:
|
| 534 |
+
msg = "malformed MP Index (unreadable directory)"
|
| 535 |
+
raise SyntaxError(msg) from e
|
| 536 |
+
# it's an error not to have a number of images
|
| 537 |
+
try:
|
| 538 |
+
quant = mp[0xB001]
|
| 539 |
+
except KeyError as e:
|
| 540 |
+
msg = "malformed MP Index (no number of images)"
|
| 541 |
+
raise SyntaxError(msg) from e
|
| 542 |
+
# get MP entries
|
| 543 |
+
mpentries = []
|
| 544 |
+
try:
|
| 545 |
+
rawmpentries = mp[0xB002]
|
| 546 |
+
for entrynum in range(0, quant):
|
| 547 |
+
unpackedentry = struct.unpack_from(
|
| 548 |
+
f"{endianness}LLLHH", rawmpentries, entrynum * 16
|
| 549 |
+
)
|
| 550 |
+
labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")
|
| 551 |
+
mpentry = dict(zip(labels, unpackedentry))
|
| 552 |
+
mpentryattr = {
|
| 553 |
+
"DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),
|
| 554 |
+
"DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),
|
| 555 |
+
"RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),
|
| 556 |
+
"Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,
|
| 557 |
+
"ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,
|
| 558 |
+
"MPType": mpentry["Attribute"] & 0x00FFFFFF,
|
| 559 |
+
}
|
| 560 |
+
if mpentryattr["ImageDataFormat"] == 0:
|
| 561 |
+
mpentryattr["ImageDataFormat"] = "JPEG"
|
| 562 |
+
else:
|
| 563 |
+
msg = "unsupported picture format in MPO"
|
| 564 |
+
raise SyntaxError(msg)
|
| 565 |
+
mptypemap = {
|
| 566 |
+
0x000000: "Undefined",
|
| 567 |
+
0x010001: "Large Thumbnail (VGA Equivalent)",
|
| 568 |
+
0x010002: "Large Thumbnail (Full HD Equivalent)",
|
| 569 |
+
0x020001: "Multi-Frame Image (Panorama)",
|
| 570 |
+
0x020002: "Multi-Frame Image: (Disparity)",
|
| 571 |
+
0x020003: "Multi-Frame Image: (Multi-Angle)",
|
| 572 |
+
0x030000: "Baseline MP Primary Image",
|
| 573 |
+
}
|
| 574 |
+
mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")
|
| 575 |
+
mpentry["Attribute"] = mpentryattr
|
| 576 |
+
mpentries.append(mpentry)
|
| 577 |
+
mp[0xB002] = mpentries
|
| 578 |
+
except KeyError as e:
|
| 579 |
+
msg = "malformed MP Index (bad MP Entry)"
|
| 580 |
+
raise SyntaxError(msg) from e
|
| 581 |
+
# Next we should try and parse the individual image unique ID list;
|
| 582 |
+
# we don't because I've never seen this actually used in a real MPO
|
| 583 |
+
# file and so can't test it.
|
| 584 |
+
return mp
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# --------------------------------------------------------------------
|
| 588 |
+
# stuff to save JPEG files
|
| 589 |
+
|
| 590 |
+
RAWMODE = {
|
| 591 |
+
"1": "L",
|
| 592 |
+
"L": "L",
|
| 593 |
+
"RGB": "RGB",
|
| 594 |
+
"RGBX": "RGB",
|
| 595 |
+
"CMYK": "CMYK;I", # assume adobe conventions
|
| 596 |
+
"YCbCr": "YCbCr",
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
# fmt: off
|
| 600 |
+
zigzag_index = (
|
| 601 |
+
0, 1, 5, 6, 14, 15, 27, 28,
|
| 602 |
+
2, 4, 7, 13, 16, 26, 29, 42,
|
| 603 |
+
3, 8, 12, 17, 25, 30, 41, 43,
|
| 604 |
+
9, 11, 18, 24, 31, 40, 44, 53,
|
| 605 |
+
10, 19, 23, 32, 39, 45, 52, 54,
|
| 606 |
+
20, 22, 33, 38, 46, 51, 55, 60,
|
| 607 |
+
21, 34, 37, 47, 50, 56, 59, 61,
|
| 608 |
+
35, 36, 48, 49, 57, 58, 62, 63,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
samplings = {
|
| 612 |
+
(1, 1, 1, 1, 1, 1): 0,
|
| 613 |
+
(2, 1, 1, 1, 1, 1): 1,
|
| 614 |
+
(2, 2, 1, 1, 1, 1): 2,
|
| 615 |
+
}
|
| 616 |
+
# fmt: on
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def get_sampling(im):
|
| 620 |
+
# There's no subsampling when images have only 1 layer
|
| 621 |
+
# (grayscale images) or when they are CMYK (4 layers),
|
| 622 |
+
# so set subsampling to the default value.
|
| 623 |
+
#
|
| 624 |
+
# NOTE: currently Pillow can't encode JPEG to YCCK format.
|
| 625 |
+
# If YCCK support is added in the future, subsampling code will have
|
| 626 |
+
# to be updated (here and in JpegEncode.c) to deal with 4 layers.
|
| 627 |
+
if not hasattr(im, "layers") or im.layers in (1, 4):
|
| 628 |
+
return -1
|
| 629 |
+
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
|
| 630 |
+
return samplings.get(sampling, -1)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 634 |
+
if im.width == 0 or im.height == 0:
|
| 635 |
+
msg = "cannot write empty image as JPEG"
|
| 636 |
+
raise ValueError(msg)
|
| 637 |
+
|
| 638 |
+
try:
|
| 639 |
+
rawmode = RAWMODE[im.mode]
|
| 640 |
+
except KeyError as e:
|
| 641 |
+
msg = f"cannot write mode {im.mode} as JPEG"
|
| 642 |
+
raise OSError(msg) from e
|
| 643 |
+
|
| 644 |
+
info = im.encoderinfo
|
| 645 |
+
|
| 646 |
+
dpi = [round(x) for x in info.get("dpi", (0, 0))]
|
| 647 |
+
|
| 648 |
+
quality = info.get("quality", -1)
|
| 649 |
+
subsampling = info.get("subsampling", -1)
|
| 650 |
+
qtables = info.get("qtables")
|
| 651 |
+
|
| 652 |
+
if quality == "keep":
|
| 653 |
+
quality = -1
|
| 654 |
+
subsampling = "keep"
|
| 655 |
+
qtables = "keep"
|
| 656 |
+
elif quality in presets:
|
| 657 |
+
preset = presets[quality]
|
| 658 |
+
quality = -1
|
| 659 |
+
subsampling = preset.get("subsampling", -1)
|
| 660 |
+
qtables = preset.get("quantization")
|
| 661 |
+
elif not isinstance(quality, int):
|
| 662 |
+
msg = "Invalid quality setting"
|
| 663 |
+
raise ValueError(msg)
|
| 664 |
+
else:
|
| 665 |
+
if subsampling in presets:
|
| 666 |
+
subsampling = presets[subsampling].get("subsampling", -1)
|
| 667 |
+
if isinstance(qtables, str) and qtables in presets:
|
| 668 |
+
qtables = presets[qtables].get("quantization")
|
| 669 |
+
|
| 670 |
+
if subsampling == "4:4:4":
|
| 671 |
+
subsampling = 0
|
| 672 |
+
elif subsampling == "4:2:2":
|
| 673 |
+
subsampling = 1
|
| 674 |
+
elif subsampling == "4:2:0":
|
| 675 |
+
subsampling = 2
|
| 676 |
+
elif subsampling == "4:1:1":
|
| 677 |
+
# For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.
|
| 678 |
+
# Set 4:2:0 if someone is still using that value.
|
| 679 |
+
subsampling = 2
|
| 680 |
+
elif subsampling == "keep":
|
| 681 |
+
if im.format != "JPEG":
|
| 682 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 683 |
+
raise ValueError(msg)
|
| 684 |
+
subsampling = get_sampling(im)
|
| 685 |
+
|
| 686 |
+
def validate_qtables(qtables):
|
| 687 |
+
if qtables is None:
|
| 688 |
+
return qtables
|
| 689 |
+
if isinstance(qtables, str):
|
| 690 |
+
try:
|
| 691 |
+
lines = [
|
| 692 |
+
int(num)
|
| 693 |
+
for line in qtables.splitlines()
|
| 694 |
+
for num in line.split("#", 1)[0].split()
|
| 695 |
+
]
|
| 696 |
+
except ValueError as e:
|
| 697 |
+
msg = "Invalid quantization table"
|
| 698 |
+
raise ValueError(msg) from e
|
| 699 |
+
else:
|
| 700 |
+
qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]
|
| 701 |
+
if isinstance(qtables, (tuple, list, dict)):
|
| 702 |
+
if isinstance(qtables, dict):
|
| 703 |
+
qtables = [
|
| 704 |
+
qtables[key] for key in range(len(qtables)) if key in qtables
|
| 705 |
+
]
|
| 706 |
+
elif isinstance(qtables, tuple):
|
| 707 |
+
qtables = list(qtables)
|
| 708 |
+
if not (0 < len(qtables) < 5):
|
| 709 |
+
msg = "None or too many quantization tables"
|
| 710 |
+
raise ValueError(msg)
|
| 711 |
+
for idx, table in enumerate(qtables):
|
| 712 |
+
try:
|
| 713 |
+
if len(table) != 64:
|
| 714 |
+
msg = "Invalid quantization table"
|
| 715 |
+
raise TypeError(msg)
|
| 716 |
+
table = array.array("H", table)
|
| 717 |
+
except TypeError as e:
|
| 718 |
+
msg = "Invalid quantization table"
|
| 719 |
+
raise ValueError(msg) from e
|
| 720 |
+
else:
|
| 721 |
+
qtables[idx] = list(table)
|
| 722 |
+
return qtables
|
| 723 |
+
|
| 724 |
+
if qtables == "keep":
|
| 725 |
+
if im.format != "JPEG":
|
| 726 |
+
msg = "Cannot use 'keep' when original image is not a JPEG"
|
| 727 |
+
raise ValueError(msg)
|
| 728 |
+
qtables = getattr(im, "quantization", None)
|
| 729 |
+
qtables = validate_qtables(qtables)
|
| 730 |
+
|
| 731 |
+
extra = info.get("extra", b"")
|
| 732 |
+
|
| 733 |
+
MAX_BYTES_IN_MARKER = 65533
|
| 734 |
+
icc_profile = info.get("icc_profile")
|
| 735 |
+
if icc_profile:
|
| 736 |
+
ICC_OVERHEAD_LEN = 14
|
| 737 |
+
MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
|
| 738 |
+
markers = []
|
| 739 |
+
while icc_profile:
|
| 740 |
+
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
|
| 741 |
+
icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
|
| 742 |
+
i = 1
|
| 743 |
+
for marker in markers:
|
| 744 |
+
size = o16(2 + ICC_OVERHEAD_LEN + len(marker))
|
| 745 |
+
extra += (
|
| 746 |
+
b"\xFF\xE2"
|
| 747 |
+
+ size
|
| 748 |
+
+ b"ICC_PROFILE\0"
|
| 749 |
+
+ o8(i)
|
| 750 |
+
+ o8(len(markers))
|
| 751 |
+
+ marker
|
| 752 |
+
)
|
| 753 |
+
i += 1
|
| 754 |
+
|
| 755 |
+
comment = info.get("comment", im.info.get("comment"))
|
| 756 |
+
|
| 757 |
+
# "progressive" is the official name, but older documentation
|
| 758 |
+
# says "progression"
|
| 759 |
+
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
|
| 760 |
+
progressive = info.get("progressive", False) or info.get("progression", False)
|
| 761 |
+
|
| 762 |
+
optimize = info.get("optimize", False)
|
| 763 |
+
|
| 764 |
+
exif = info.get("exif", b"")
|
| 765 |
+
if isinstance(exif, Image.Exif):
|
| 766 |
+
exif = exif.tobytes()
|
| 767 |
+
if len(exif) > MAX_BYTES_IN_MARKER:
|
| 768 |
+
msg = "EXIF data is too long"
|
| 769 |
+
raise ValueError(msg)
|
| 770 |
+
|
| 771 |
+
# get keyword arguments
|
| 772 |
+
im.encoderconfig = (
|
| 773 |
+
quality,
|
| 774 |
+
progressive,
|
| 775 |
+
info.get("smooth", 0),
|
| 776 |
+
optimize,
|
| 777 |
+
info.get("keep_rgb", False),
|
| 778 |
+
info.get("streamtype", 0),
|
| 779 |
+
dpi[0],
|
| 780 |
+
dpi[1],
|
| 781 |
+
subsampling,
|
| 782 |
+
info.get("restart_marker_blocks", 0),
|
| 783 |
+
info.get("restart_marker_rows", 0),
|
| 784 |
+
qtables,
|
| 785 |
+
comment,
|
| 786 |
+
extra,
|
| 787 |
+
exif,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
# if we optimize, libjpeg needs a buffer big enough to hold the whole image
|
| 791 |
+
# in a shot. Guessing on the size, at im.size bytes. (raw pixel size is
|
| 792 |
+
# channels*size, this is a value that's been used in a django patch.
|
| 793 |
+
# https://github.com/matthewwithanm/django-imagekit/issues/50
|
| 794 |
+
bufsize = 0
|
| 795 |
+
if optimize or progressive:
|
| 796 |
+
# CMYK can be bigger
|
| 797 |
+
if im.mode == "CMYK":
|
| 798 |
+
bufsize = 4 * im.size[0] * im.size[1]
|
| 799 |
+
# keep sets quality to -1, but the actual value may be high.
|
| 800 |
+
elif quality >= 95 or quality == -1:
|
| 801 |
+
bufsize = 2 * im.size[0] * im.size[1]
|
| 802 |
+
else:
|
| 803 |
+
bufsize = im.size[0] * im.size[1]
|
| 804 |
+
if exif:
|
| 805 |
+
bufsize += len(exif) + 5
|
| 806 |
+
if extra:
|
| 807 |
+
bufsize += len(extra) + 1
|
| 808 |
+
else:
|
| 809 |
+
# The EXIF info needs to be written as one block, + APP1, + one spare byte.
|
| 810 |
+
# Ensure that our buffer is big enough. Same with the icc_profile block.
|
| 811 |
+
bufsize = max(bufsize, len(exif) + 5, len(extra) + 1)
|
| 812 |
+
|
| 813 |
+
ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize)
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def _save_cjpeg(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 817 |
+
# ALTERNATIVE: handle JPEGs via the IJG command line utilities.
|
| 818 |
+
tempfile = im._dump()
|
| 819 |
+
subprocess.check_call(["cjpeg", "-outfile", filename, tempfile])
|
| 820 |
+
try:
|
| 821 |
+
os.unlink(tempfile)
|
| 822 |
+
except OSError:
|
| 823 |
+
pass
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
##
|
| 827 |
+
# Factory for making JPEG and MPO instances
|
| 828 |
+
def jpeg_factory(fp=None, filename=None):
|
| 829 |
+
im = JpegImageFile(fp, filename)
|
| 830 |
+
try:
|
| 831 |
+
mpheader = im._getmp()
|
| 832 |
+
if mpheader[45057] > 1:
|
| 833 |
+
for segment, content in im.applist:
|
| 834 |
+
if segment == "APP1" and b' hdrgm:Version="' in content:
|
| 835 |
+
# Ultra HDR images are not yet supported
|
| 836 |
+
return im
|
| 837 |
+
# It's actually an MPO
|
| 838 |
+
from .MpoImagePlugin import MpoImageFile
|
| 839 |
+
|
| 840 |
+
# Don't reload everything, just convert it.
|
| 841 |
+
im = MpoImageFile.adopt(im, mpheader)
|
| 842 |
+
except (TypeError, IndexError):
|
| 843 |
+
# It is really a JPEG
|
| 844 |
+
pass
|
| 845 |
+
except SyntaxError:
|
| 846 |
+
warnings.warn(
|
| 847 |
+
"Image appears to be a malformed MPO file, it will be "
|
| 848 |
+
"interpreted as a base JPEG file"
|
| 849 |
+
)
|
| 850 |
+
return im
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
# ---------------------------------------------------------------------
|
| 854 |
+
# Registry stuff
|
| 855 |
+
|
| 856 |
+
Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
|
| 857 |
+
Image.register_save(JpegImageFile.format, _save)
|
| 858 |
+
|
| 859 |
+
Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])
|
| 860 |
+
|
| 861 |
+
Image.register_mime(JpegImageFile.format, "image/jpeg")
|
valley/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):
|
| 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")
|
valley/lib/python3.10/site-packages/PIL/MpegImagePlugin.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# MPEG file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-09-09 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1995.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from . import Image, ImageFile
|
| 18 |
+
from ._binary import i8
|
| 19 |
+
from ._typing import SupportsRead
|
| 20 |
+
|
| 21 |
+
#
|
| 22 |
+
# Bitstream parser
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BitStream:
|
| 26 |
+
def __init__(self, fp: SupportsRead[bytes]) -> None:
|
| 27 |
+
self.fp = fp
|
| 28 |
+
self.bits = 0
|
| 29 |
+
self.bitbuffer = 0
|
| 30 |
+
|
| 31 |
+
def next(self) -> int:
|
| 32 |
+
return i8(self.fp.read(1))
|
| 33 |
+
|
| 34 |
+
def peek(self, bits: int) -> int:
|
| 35 |
+
while self.bits < bits:
|
| 36 |
+
c = self.next()
|
| 37 |
+
if c < 0:
|
| 38 |
+
self.bits = 0
|
| 39 |
+
continue
|
| 40 |
+
self.bitbuffer = (self.bitbuffer << 8) + c
|
| 41 |
+
self.bits += 8
|
| 42 |
+
return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1
|
| 43 |
+
|
| 44 |
+
def skip(self, bits: int) -> None:
|
| 45 |
+
while self.bits < bits:
|
| 46 |
+
self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1))
|
| 47 |
+
self.bits += 8
|
| 48 |
+
self.bits = self.bits - bits
|
| 49 |
+
|
| 50 |
+
def read(self, bits: int) -> int:
|
| 51 |
+
v = self.peek(bits)
|
| 52 |
+
self.bits = self.bits - bits
|
| 53 |
+
return v
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _accept(prefix: bytes) -> bool:
|
| 57 |
+
return prefix[:4] == b"\x00\x00\x01\xb3"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
##
|
| 61 |
+
# Image plugin for MPEG streams. This plugin can identify a stream,
|
| 62 |
+
# but it cannot read it.
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MpegImageFile(ImageFile.ImageFile):
|
| 66 |
+
format = "MPEG"
|
| 67 |
+
format_description = "MPEG"
|
| 68 |
+
|
| 69 |
+
def _open(self) -> None:
|
| 70 |
+
assert self.fp is not None
|
| 71 |
+
|
| 72 |
+
s = BitStream(self.fp)
|
| 73 |
+
if s.read(32) != 0x1B3:
|
| 74 |
+
msg = "not an MPEG file"
|
| 75 |
+
raise SyntaxError(msg)
|
| 76 |
+
|
| 77 |
+
self._mode = "RGB"
|
| 78 |
+
self._size = s.read(12), s.read(12)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# --------------------------------------------------------------------
|
| 82 |
+
# Registry stuff
|
| 83 |
+
|
| 84 |
+
Image.register_open(MpegImageFile.format, MpegImageFile, _accept)
|
| 85 |
+
|
| 86 |
+
Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
|
| 87 |
+
|
| 88 |
+
Image.register_mime(MpegImageFile.format, "video/mpeg")
|
valley/lib/python3.10/site-packages/PIL/MpoImagePlugin.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 26 |
+
|
| 27 |
+
from . import (
|
| 28 |
+
Image,
|
| 29 |
+
ImageSequence,
|
| 30 |
+
JpegImagePlugin,
|
| 31 |
+
TiffImagePlugin,
|
| 32 |
+
)
|
| 33 |
+
from ._binary import o32le
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 37 |
+
JpegImagePlugin._save(im, fp, filename)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 41 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 42 |
+
if not append_images and not getattr(im, "is_animated", False):
|
| 43 |
+
_save(im, fp, filename)
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
mpf_offset = 28
|
| 47 |
+
offsets: list[int] = []
|
| 48 |
+
for imSequence in itertools.chain([im], append_images):
|
| 49 |
+
for im_frame in ImageSequence.Iterator(imSequence):
|
| 50 |
+
if not offsets:
|
| 51 |
+
# APP2 marker
|
| 52 |
+
im_frame.encoderinfo["extra"] = (
|
| 53 |
+
b"\xFF\xE2" + struct.pack(">H", 6 + 82) + b"MPF\0" + b" " * 82
|
| 54 |
+
)
|
| 55 |
+
exif = im_frame.encoderinfo.get("exif")
|
| 56 |
+
if isinstance(exif, Image.Exif):
|
| 57 |
+
exif = exif.tobytes()
|
| 58 |
+
im_frame.encoderinfo["exif"] = exif
|
| 59 |
+
if exif:
|
| 60 |
+
mpf_offset += 4 + len(exif)
|
| 61 |
+
|
| 62 |
+
JpegImagePlugin._save(im_frame, fp, filename)
|
| 63 |
+
offsets.append(fp.tell())
|
| 64 |
+
else:
|
| 65 |
+
im_frame.save(fp, "JPEG")
|
| 66 |
+
offsets.append(fp.tell() - offsets[-1])
|
| 67 |
+
|
| 68 |
+
ifd = TiffImagePlugin.ImageFileDirectory_v2()
|
| 69 |
+
ifd[0xB000] = b"0100"
|
| 70 |
+
ifd[0xB001] = len(offsets)
|
| 71 |
+
|
| 72 |
+
mpentries = b""
|
| 73 |
+
data_offset = 0
|
| 74 |
+
for i, size in enumerate(offsets):
|
| 75 |
+
if i == 0:
|
| 76 |
+
mptype = 0x030000 # Baseline MP Primary Image
|
| 77 |
+
else:
|
| 78 |
+
mptype = 0x000000 # Undefined
|
| 79 |
+
mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)
|
| 80 |
+
if i == 0:
|
| 81 |
+
data_offset -= mpf_offset
|
| 82 |
+
data_offset += size
|
| 83 |
+
ifd[0xB002] = mpentries
|
| 84 |
+
|
| 85 |
+
fp.seek(mpf_offset)
|
| 86 |
+
fp.write(b"II\x2A\x00" + o32le(8) + ifd.tobytes(8))
|
| 87 |
+
fp.seek(0, os.SEEK_END)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
##
|
| 91 |
+
# Image plugin for MPO images.
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class MpoImageFile(JpegImagePlugin.JpegImageFile):
|
| 95 |
+
format = "MPO"
|
| 96 |
+
format_description = "MPO (CIPA DC-007)"
|
| 97 |
+
_close_exclusive_fp_after_loading = False
|
| 98 |
+
|
| 99 |
+
def _open(self) -> None:
|
| 100 |
+
self.fp.seek(0) # prep the fp in order to pass the JPEG test
|
| 101 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 102 |
+
self._after_jpeg_open()
|
| 103 |
+
|
| 104 |
+
def _after_jpeg_open(self, mpheader=None):
|
| 105 |
+
self.mpinfo = mpheader if mpheader is not None else self._getmp()
|
| 106 |
+
self.n_frames = self.mpinfo[0xB001]
|
| 107 |
+
self.__mpoffsets = [
|
| 108 |
+
mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
|
| 109 |
+
]
|
| 110 |
+
self.__mpoffsets[0] = 0
|
| 111 |
+
# Note that the following assertion will only be invalid if something
|
| 112 |
+
# gets broken within JpegImagePlugin.
|
| 113 |
+
assert self.n_frames == len(self.__mpoffsets)
|
| 114 |
+
del self.info["mpoffset"] # no longer needed
|
| 115 |
+
self.is_animated = self.n_frames > 1
|
| 116 |
+
self._fp = self.fp # FIXME: hack
|
| 117 |
+
self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
|
| 118 |
+
self.__frame = 0
|
| 119 |
+
self.offset = 0
|
| 120 |
+
# for now we can only handle reading and individual frame extraction
|
| 121 |
+
self.readonly = 1
|
| 122 |
+
|
| 123 |
+
def load_seek(self, pos: int) -> None:
|
| 124 |
+
self._fp.seek(pos)
|
| 125 |
+
|
| 126 |
+
def seek(self, frame: int) -> None:
|
| 127 |
+
if not self._seek_check(frame):
|
| 128 |
+
return
|
| 129 |
+
self.fp = self._fp
|
| 130 |
+
self.offset = self.__mpoffsets[frame]
|
| 131 |
+
|
| 132 |
+
original_exif = self.info.get("exif")
|
| 133 |
+
if "exif" in self.info:
|
| 134 |
+
del self.info["exif"]
|
| 135 |
+
|
| 136 |
+
self.fp.seek(self.offset + 2) # skip SOI marker
|
| 137 |
+
if not self.fp.read(2):
|
| 138 |
+
msg = "No data found for frame"
|
| 139 |
+
raise ValueError(msg)
|
| 140 |
+
self.fp.seek(self.offset)
|
| 141 |
+
JpegImagePlugin.JpegImageFile._open(self)
|
| 142 |
+
if self.info.get("exif") != original_exif:
|
| 143 |
+
self._reload_exif()
|
| 144 |
+
|
| 145 |
+
self.tile = [("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])]
|
| 146 |
+
self.__frame = frame
|
| 147 |
+
|
| 148 |
+
def tell(self) -> int:
|
| 149 |
+
return self.__frame
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
def adopt(jpeg_instance, mpheader=None):
|
| 153 |
+
"""
|
| 154 |
+
Transform the instance of JpegImageFile into
|
| 155 |
+
an instance of MpoImageFile.
|
| 156 |
+
After the call, the JpegImageFile is extended
|
| 157 |
+
to be an MpoImageFile.
|
| 158 |
+
|
| 159 |
+
This is essentially useful when opening a JPEG
|
| 160 |
+
file that reveals itself as an MPO, to avoid
|
| 161 |
+
double call to _open.
|
| 162 |
+
"""
|
| 163 |
+
jpeg_instance.__class__ = MpoImageFile
|
| 164 |
+
jpeg_instance._after_jpeg_open(mpheader)
|
| 165 |
+
return jpeg_instance
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ---------------------------------------------------------------------
|
| 169 |
+
# Registry stuff
|
| 170 |
+
|
| 171 |
+
# Note that since MPO shares a factory with JPEG, we do not need to do a
|
| 172 |
+
# separate registration for it here.
|
| 173 |
+
# Image.register_open(MpoImageFile.format,
|
| 174 |
+
# JpegImagePlugin.jpeg_factory, _accept)
|
| 175 |
+
Image.register_save(MpoImageFile.format, _save)
|
| 176 |
+
Image.register_save_all(MpoImageFile.format, _save_all)
|
| 177 |
+
|
| 178 |
+
Image.register_extension(MpoImageFile.format, ".mpo")
|
| 179 |
+
|
| 180 |
+
Image.register_mime(MpoImageFile.format, "image/mpo")
|
valley/lib/python3.10/site-packages/PIL/MspImagePlugin.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
#
|
| 4 |
+
# MSP file handling
|
| 5 |
+
#
|
| 6 |
+
# This is the format used by the Paint program in Windows 1 and 2.
|
| 7 |
+
#
|
| 8 |
+
# History:
|
| 9 |
+
# 95-09-05 fl Created
|
| 10 |
+
# 97-01-03 fl Read/write MSP images
|
| 11 |
+
# 17-02-21 es Fixed RLE interpretation
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
| 15 |
+
# Copyright (c) Eric Soroos 2017.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
# More info on this format: https://archive.org/details/gg243631
|
| 20 |
+
# Page 313:
|
| 21 |
+
# Figure 205. Windows Paint Version 1: "DanM" Format
|
| 22 |
+
# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03
|
| 23 |
+
#
|
| 24 |
+
# See also: https://www.fileformat.info/format/mspaint/egff.htm
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import io
|
| 28 |
+
import struct
|
| 29 |
+
from typing import IO
|
| 30 |
+
|
| 31 |
+
from . import Image, ImageFile
|
| 32 |
+
from ._binary import i16le as i16
|
| 33 |
+
from ._binary import o16le as o16
|
| 34 |
+
|
| 35 |
+
#
|
| 36 |
+
# read MSP files
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _accept(prefix: bytes) -> bool:
|
| 40 |
+
return prefix[:4] in [b"DanM", b"LinS"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
##
|
| 44 |
+
# Image plugin for Windows MSP images. This plugin supports both
|
| 45 |
+
# uncompressed (Windows 1.0).
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MspImageFile(ImageFile.ImageFile):
|
| 49 |
+
format = "MSP"
|
| 50 |
+
format_description = "Windows Paint"
|
| 51 |
+
|
| 52 |
+
def _open(self) -> None:
|
| 53 |
+
# Header
|
| 54 |
+
assert self.fp is not None
|
| 55 |
+
|
| 56 |
+
s = self.fp.read(32)
|
| 57 |
+
if not _accept(s):
|
| 58 |
+
msg = "not an MSP file"
|
| 59 |
+
raise SyntaxError(msg)
|
| 60 |
+
|
| 61 |
+
# Header checksum
|
| 62 |
+
checksum = 0
|
| 63 |
+
for i in range(0, 32, 2):
|
| 64 |
+
checksum = checksum ^ i16(s, i)
|
| 65 |
+
if checksum != 0:
|
| 66 |
+
msg = "bad MSP checksum"
|
| 67 |
+
raise SyntaxError(msg)
|
| 68 |
+
|
| 69 |
+
self._mode = "1"
|
| 70 |
+
self._size = i16(s, 4), i16(s, 6)
|
| 71 |
+
|
| 72 |
+
if s[:4] == b"DanM":
|
| 73 |
+
self.tile = [("raw", (0, 0) + self.size, 32, ("1", 0, 1))]
|
| 74 |
+
else:
|
| 75 |
+
self.tile = [("MSP", (0, 0) + self.size, 32, None)]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class MspDecoder(ImageFile.PyDecoder):
|
| 79 |
+
# The algo for the MSP decoder is from
|
| 80 |
+
# https://www.fileformat.info/format/mspaint/egff.htm
|
| 81 |
+
# cc-by-attribution -- That page references is taken from the
|
| 82 |
+
# Encyclopedia of Graphics File Formats and is licensed by
|
| 83 |
+
# O'Reilly under the Creative Common/Attribution license
|
| 84 |
+
#
|
| 85 |
+
# For RLE encoded files, the 32byte header is followed by a scan
|
| 86 |
+
# line map, encoded as one 16bit word of encoded byte length per
|
| 87 |
+
# line.
|
| 88 |
+
#
|
| 89 |
+
# NOTE: the encoded length of the line can be 0. This was not
|
| 90 |
+
# handled in the previous version of this encoder, and there's no
|
| 91 |
+
# mention of how to handle it in the documentation. From the few
|
| 92 |
+
# examples I've seen, I've assumed that it is a fill of the
|
| 93 |
+
# background color, in this case, white.
|
| 94 |
+
#
|
| 95 |
+
#
|
| 96 |
+
# Pseudocode of the decoder:
|
| 97 |
+
# Read a BYTE value as the RunType
|
| 98 |
+
# If the RunType value is zero
|
| 99 |
+
# Read next byte as the RunCount
|
| 100 |
+
# Read the next byte as the RunValue
|
| 101 |
+
# Write the RunValue byte RunCount times
|
| 102 |
+
# If the RunType value is non-zero
|
| 103 |
+
# Use this value as the RunCount
|
| 104 |
+
# Read and write the next RunCount bytes literally
|
| 105 |
+
#
|
| 106 |
+
# e.g.:
|
| 107 |
+
# 0x00 03 ff 05 00 01 02 03 04
|
| 108 |
+
# would yield the bytes:
|
| 109 |
+
# 0xff ff ff 00 01 02 03 04
|
| 110 |
+
#
|
| 111 |
+
# which are then interpreted as a bit packed mode '1' image
|
| 112 |
+
|
| 113 |
+
_pulls_fd = True
|
| 114 |
+
|
| 115 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 116 |
+
assert self.fd is not None
|
| 117 |
+
|
| 118 |
+
img = io.BytesIO()
|
| 119 |
+
blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8))
|
| 120 |
+
try:
|
| 121 |
+
self.fd.seek(32)
|
| 122 |
+
rowmap = struct.unpack_from(
|
| 123 |
+
f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2)
|
| 124 |
+
)
|
| 125 |
+
except struct.error as e:
|
| 126 |
+
msg = "Truncated MSP file in row map"
|
| 127 |
+
raise OSError(msg) from e
|
| 128 |
+
|
| 129 |
+
for x, rowlen in enumerate(rowmap):
|
| 130 |
+
try:
|
| 131 |
+
if rowlen == 0:
|
| 132 |
+
img.write(blank_line)
|
| 133 |
+
continue
|
| 134 |
+
row = self.fd.read(rowlen)
|
| 135 |
+
if len(row) != rowlen:
|
| 136 |
+
msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}"
|
| 137 |
+
raise OSError(msg)
|
| 138 |
+
idx = 0
|
| 139 |
+
while idx < rowlen:
|
| 140 |
+
runtype = row[idx]
|
| 141 |
+
idx += 1
|
| 142 |
+
if runtype == 0:
|
| 143 |
+
(runcount, runval) = struct.unpack_from("Bc", row, idx)
|
| 144 |
+
img.write(runval * runcount)
|
| 145 |
+
idx += 2
|
| 146 |
+
else:
|
| 147 |
+
runcount = runtype
|
| 148 |
+
img.write(row[idx : idx + runcount])
|
| 149 |
+
idx += runcount
|
| 150 |
+
|
| 151 |
+
except struct.error as e:
|
| 152 |
+
msg = f"Corrupted MSP file in row {x}"
|
| 153 |
+
raise OSError(msg) from e
|
| 154 |
+
|
| 155 |
+
self.set_as_raw(img.getvalue(), ("1", 0, 1))
|
| 156 |
+
|
| 157 |
+
return -1, 0
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
Image.register_decoder("MSP", MspDecoder)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
#
|
| 164 |
+
# write MSP files (uncompressed only)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 168 |
+
if im.mode != "1":
|
| 169 |
+
msg = f"cannot write mode {im.mode} as MSP"
|
| 170 |
+
raise OSError(msg)
|
| 171 |
+
|
| 172 |
+
# create MSP header
|
| 173 |
+
header = [0] * 16
|
| 174 |
+
|
| 175 |
+
header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1
|
| 176 |
+
header[2], header[3] = im.size
|
| 177 |
+
header[4], header[5] = 1, 1
|
| 178 |
+
header[6], header[7] = 1, 1
|
| 179 |
+
header[8], header[9] = im.size
|
| 180 |
+
|
| 181 |
+
checksum = 0
|
| 182 |
+
for h in header:
|
| 183 |
+
checksum = checksum ^ h
|
| 184 |
+
header[12] = checksum # FIXME: is this the right field?
|
| 185 |
+
|
| 186 |
+
# header
|
| 187 |
+
for h in header:
|
| 188 |
+
fp.write(o16(h))
|
| 189 |
+
|
| 190 |
+
# image body
|
| 191 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 32, ("1", 0, 1))])
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
#
|
| 195 |
+
# registry
|
| 196 |
+
|
| 197 |
+
Image.register_open(MspImageFile.format, MspImageFile, _accept)
|
| 198 |
+
Image.register_save(MspImageFile.format, _save)
|
| 199 |
+
|
| 200 |
+
Image.register_extension(MspImageFile.format, ".msp")
|
valley/lib/python3.10/site-packages/PIL/PSDraw.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Simple PostScript graphics interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-04-20 fl Created
|
| 9 |
+
# 1999-01-10 fl Added gsave/grestore to image method
|
| 10 |
+
# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge)
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved.
|
| 13 |
+
# Copyright (c) 1996 by Fredrik Lundh.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import sys
|
| 20 |
+
from typing import TYPE_CHECKING
|
| 21 |
+
|
| 22 |
+
from . import EpsImagePlugin
|
| 23 |
+
|
| 24 |
+
##
|
| 25 |
+
# Simple PostScript graphics interface.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PSDraw:
|
| 29 |
+
"""
|
| 30 |
+
Sets up printing to the given file. If ``fp`` is omitted,
|
| 31 |
+
``sys.stdout.buffer`` or ``sys.stdout`` is assumed.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self, fp=None):
|
| 35 |
+
if not fp:
|
| 36 |
+
try:
|
| 37 |
+
fp = sys.stdout.buffer
|
| 38 |
+
except AttributeError:
|
| 39 |
+
fp = sys.stdout
|
| 40 |
+
self.fp = fp
|
| 41 |
+
|
| 42 |
+
def begin_document(self, id: str | None = None) -> None:
|
| 43 |
+
"""Set up printing of a document. (Write PostScript DSC header.)"""
|
| 44 |
+
# FIXME: incomplete
|
| 45 |
+
self.fp.write(
|
| 46 |
+
b"%!PS-Adobe-3.0\n"
|
| 47 |
+
b"save\n"
|
| 48 |
+
b"/showpage { } def\n"
|
| 49 |
+
b"%%EndComments\n"
|
| 50 |
+
b"%%BeginDocument\n"
|
| 51 |
+
)
|
| 52 |
+
# self.fp.write(ERROR_PS) # debugging!
|
| 53 |
+
self.fp.write(EDROFF_PS)
|
| 54 |
+
self.fp.write(VDI_PS)
|
| 55 |
+
self.fp.write(b"%%EndProlog\n")
|
| 56 |
+
self.isofont: dict[bytes, int] = {}
|
| 57 |
+
|
| 58 |
+
def end_document(self) -> None:
|
| 59 |
+
"""Ends printing. (Write PostScript DSC footer.)"""
|
| 60 |
+
self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n")
|
| 61 |
+
if hasattr(self.fp, "flush"):
|
| 62 |
+
self.fp.flush()
|
| 63 |
+
|
| 64 |
+
def setfont(self, font: str, size: int) -> None:
|
| 65 |
+
"""
|
| 66 |
+
Selects which font to use.
|
| 67 |
+
|
| 68 |
+
:param font: A PostScript font name
|
| 69 |
+
:param size: Size in points.
|
| 70 |
+
"""
|
| 71 |
+
font_bytes = bytes(font, "UTF-8")
|
| 72 |
+
if font_bytes not in self.isofont:
|
| 73 |
+
# reencode font
|
| 74 |
+
self.fp.write(
|
| 75 |
+
b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes)
|
| 76 |
+
)
|
| 77 |
+
self.isofont[font_bytes] = 1
|
| 78 |
+
# rough
|
| 79 |
+
self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes))
|
| 80 |
+
|
| 81 |
+
def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None:
|
| 82 |
+
"""
|
| 83 |
+
Draws a line between the two points. Coordinates are given in
|
| 84 |
+
PostScript point coordinates (72 points per inch, (0, 0) is the lower
|
| 85 |
+
left corner of the page).
|
| 86 |
+
"""
|
| 87 |
+
self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))
|
| 88 |
+
|
| 89 |
+
def rectangle(self, box: tuple[int, int, int, int]) -> None:
|
| 90 |
+
"""
|
| 91 |
+
Draws a rectangle.
|
| 92 |
+
|
| 93 |
+
:param box: A tuple of four integers, specifying left, bottom, width and
|
| 94 |
+
height.
|
| 95 |
+
"""
|
| 96 |
+
self.fp.write(b"%d %d M 0 %d %d Vr\n" % box)
|
| 97 |
+
|
| 98 |
+
def text(self, xy: tuple[int, int], text: str) -> None:
|
| 99 |
+
"""
|
| 100 |
+
Draws text at the given position. You must use
|
| 101 |
+
:py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
|
| 102 |
+
"""
|
| 103 |
+
text_bytes = bytes(text, "UTF-8")
|
| 104 |
+
text_bytes = b"\\(".join(text_bytes.split(b"("))
|
| 105 |
+
text_bytes = b"\\)".join(text_bytes.split(b")"))
|
| 106 |
+
self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,)))
|
| 107 |
+
|
| 108 |
+
if TYPE_CHECKING:
|
| 109 |
+
from . import Image
|
| 110 |
+
|
| 111 |
+
def image(
|
| 112 |
+
self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None
|
| 113 |
+
) -> None:
|
| 114 |
+
"""Draw a PIL image, centered in the given box."""
|
| 115 |
+
# default resolution depends on mode
|
| 116 |
+
if not dpi:
|
| 117 |
+
if im.mode == "1":
|
| 118 |
+
dpi = 200 # fax
|
| 119 |
+
else:
|
| 120 |
+
dpi = 100 # grayscale
|
| 121 |
+
# image size (on paper)
|
| 122 |
+
x = im.size[0] * 72 / dpi
|
| 123 |
+
y = im.size[1] * 72 / dpi
|
| 124 |
+
# max allowed size
|
| 125 |
+
xmax = float(box[2] - box[0])
|
| 126 |
+
ymax = float(box[3] - box[1])
|
| 127 |
+
if x > xmax:
|
| 128 |
+
y = y * xmax / x
|
| 129 |
+
x = xmax
|
| 130 |
+
if y > ymax:
|
| 131 |
+
x = x * ymax / y
|
| 132 |
+
y = ymax
|
| 133 |
+
dx = (xmax - x) / 2 + box[0]
|
| 134 |
+
dy = (ymax - y) / 2 + box[1]
|
| 135 |
+
self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy))
|
| 136 |
+
if (x, y) != im.size:
|
| 137 |
+
# EpsImagePlugin._save prints the image at (0,0,xsize,ysize)
|
| 138 |
+
sx = x / im.size[0]
|
| 139 |
+
sy = y / im.size[1]
|
| 140 |
+
self.fp.write(b"%f %f scale\n" % (sx, sy))
|
| 141 |
+
EpsImagePlugin._save(im, self.fp, "", 0)
|
| 142 |
+
self.fp.write(b"\ngrestore\n")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# --------------------------------------------------------------------
|
| 146 |
+
# PostScript driver
|
| 147 |
+
|
| 148 |
+
#
|
| 149 |
+
# EDROFF.PS -- PostScript driver for Edroff 2
|
| 150 |
+
#
|
| 151 |
+
# History:
|
| 152 |
+
# 94-01-25 fl: created (edroff 2.04)
|
| 153 |
+
#
|
| 154 |
+
# Copyright (c) Fredrik Lundh 1994.
|
| 155 |
+
#
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
EDROFF_PS = b"""\
|
| 159 |
+
/S { show } bind def
|
| 160 |
+
/P { moveto show } bind def
|
| 161 |
+
/M { moveto } bind def
|
| 162 |
+
/X { 0 rmoveto } bind def
|
| 163 |
+
/Y { 0 exch rmoveto } bind def
|
| 164 |
+
/E { findfont
|
| 165 |
+
dup maxlength dict begin
|
| 166 |
+
{
|
| 167 |
+
1 index /FID ne { def } { pop pop } ifelse
|
| 168 |
+
} forall
|
| 169 |
+
/Encoding exch def
|
| 170 |
+
dup /FontName exch def
|
| 171 |
+
currentdict end definefont pop
|
| 172 |
+
} bind def
|
| 173 |
+
/F { findfont exch scalefont dup setfont
|
| 174 |
+
[ exch /setfont cvx ] cvx bind def
|
| 175 |
+
} bind def
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
#
|
| 179 |
+
# VDI.PS -- PostScript driver for VDI meta commands
|
| 180 |
+
#
|
| 181 |
+
# History:
|
| 182 |
+
# 94-01-25 fl: created (edroff 2.04)
|
| 183 |
+
#
|
| 184 |
+
# Copyright (c) Fredrik Lundh 1994.
|
| 185 |
+
#
|
| 186 |
+
|
| 187 |
+
VDI_PS = b"""\
|
| 188 |
+
/Vm { moveto } bind def
|
| 189 |
+
/Va { newpath arcn stroke } bind def
|
| 190 |
+
/Vl { moveto lineto stroke } bind def
|
| 191 |
+
/Vc { newpath 0 360 arc closepath } bind def
|
| 192 |
+
/Vr { exch dup 0 rlineto
|
| 193 |
+
exch dup 0 exch rlineto
|
| 194 |
+
exch neg 0 rlineto
|
| 195 |
+
0 exch neg rlineto
|
| 196 |
+
setgray fill } bind def
|
| 197 |
+
/Tm matrix def
|
| 198 |
+
/Ve { Tm currentmatrix pop
|
| 199 |
+
translate scale newpath 0 0 .5 0 360 arc closepath
|
| 200 |
+
Tm setmatrix
|
| 201 |
+
} bind def
|
| 202 |
+
/Vf { currentgray exch setgray fill setgray } bind def
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
#
|
| 206 |
+
# ERROR.PS -- Error handler
|
| 207 |
+
#
|
| 208 |
+
# History:
|
| 209 |
+
# 89-11-21 fl: created (pslist 1.10)
|
| 210 |
+
#
|
| 211 |
+
|
| 212 |
+
ERROR_PS = b"""\
|
| 213 |
+
/landscape false def
|
| 214 |
+
/errorBUF 200 string def
|
| 215 |
+
/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def
|
| 216 |
+
errordict begin /handleerror {
|
| 217 |
+
initmatrix /Courier findfont 10 scalefont setfont
|
| 218 |
+
newpath 72 720 moveto $error begin /newerror false def
|
| 219 |
+
(PostScript Error) show errorNL errorNL
|
| 220 |
+
(Error: ) show
|
| 221 |
+
/errorname load errorBUF cvs show errorNL errorNL
|
| 222 |
+
(Command: ) show
|
| 223 |
+
/command load dup type /stringtype ne { errorBUF cvs } if show
|
| 224 |
+
errorNL errorNL
|
| 225 |
+
(VMstatus: ) show
|
| 226 |
+
vmstatus errorBUF cvs show ( bytes available, ) show
|
| 227 |
+
errorBUF cvs show ( bytes used at level ) show
|
| 228 |
+
errorBUF cvs show errorNL errorNL
|
| 229 |
+
(Operand stargck: ) show errorNL /ostargck load {
|
| 230 |
+
dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
|
| 231 |
+
} forall errorNL
|
| 232 |
+
(Execution stargck: ) show errorNL /estargck load {
|
| 233 |
+
dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
|
| 234 |
+
} forall
|
| 235 |
+
end showpage
|
| 236 |
+
} def end
|
| 237 |
+
"""
|
valley/lib/python3.10/site-packages/PIL/PaletteFile.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# stuff to read simple, teragon-style palette files
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 97-08-23 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import IO
|
| 18 |
+
|
| 19 |
+
from ._binary import o8
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PaletteFile:
|
| 23 |
+
"""File handler for Teragon-style palette files."""
|
| 24 |
+
|
| 25 |
+
rawmode = "RGB"
|
| 26 |
+
|
| 27 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 28 |
+
palette = [o8(i) * 3 for i in range(256)]
|
| 29 |
+
|
| 30 |
+
while True:
|
| 31 |
+
s = fp.readline()
|
| 32 |
+
|
| 33 |
+
if not s:
|
| 34 |
+
break
|
| 35 |
+
if s[:1] == b"#":
|
| 36 |
+
continue
|
| 37 |
+
if len(s) > 100:
|
| 38 |
+
msg = "bad palette file"
|
| 39 |
+
raise SyntaxError(msg)
|
| 40 |
+
|
| 41 |
+
v = [int(x) for x in s.split()]
|
| 42 |
+
try:
|
| 43 |
+
[i, r, g, b] = v
|
| 44 |
+
except ValueError:
|
| 45 |
+
[i, r] = v
|
| 46 |
+
g = b = r
|
| 47 |
+
|
| 48 |
+
if 0 <= i <= 255:
|
| 49 |
+
palette[i] = o8(r) + o8(g) + o8(b)
|
| 50 |
+
|
| 51 |
+
self.palette = b"".join(palette)
|
| 52 |
+
|
| 53 |
+
def getpalette(self) -> tuple[bytes, str]:
|
| 54 |
+
return self.palette, self.rawmode
|
valley/lib/python3.10/site-packages/PIL/PalmImagePlugin.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
|
| 6 |
+
##
|
| 7 |
+
# Image plugin for Palm pixmap images (output only).
|
| 8 |
+
##
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import IO
|
| 12 |
+
|
| 13 |
+
from . import Image, ImageFile
|
| 14 |
+
from ._binary import o8
|
| 15 |
+
from ._binary import o16be as o16b
|
| 16 |
+
|
| 17 |
+
# fmt: off
|
| 18 |
+
_Palm8BitColormapValues = (
|
| 19 |
+
(255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
|
| 20 |
+
(255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
|
| 21 |
+
(255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
|
| 22 |
+
(255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),
|
| 23 |
+
(255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),
|
| 24 |
+
(204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),
|
| 25 |
+
(204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),
|
| 26 |
+
(204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),
|
| 27 |
+
(204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),
|
| 28 |
+
(153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),
|
| 29 |
+
(153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),
|
| 30 |
+
(153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),
|
| 31 |
+
(153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),
|
| 32 |
+
(153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),
|
| 33 |
+
(102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),
|
| 34 |
+
(102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
|
| 35 |
+
(102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
|
| 36 |
+
(102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
|
| 37 |
+
(51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
|
| 38 |
+
(51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
|
| 39 |
+
(51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
|
| 40 |
+
(51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
|
| 41 |
+
(51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
|
| 42 |
+
(0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
|
| 43 |
+
(0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
|
| 44 |
+
(0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
|
| 45 |
+
(0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
|
| 46 |
+
(255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
|
| 47 |
+
(255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
|
| 48 |
+
(255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
|
| 49 |
+
(255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),
|
| 50 |
+
(255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),
|
| 51 |
+
(204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),
|
| 52 |
+
(204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),
|
| 53 |
+
(204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),
|
| 54 |
+
(204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),
|
| 55 |
+
(153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),
|
| 56 |
+
(153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),
|
| 57 |
+
(153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),
|
| 58 |
+
(153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),
|
| 59 |
+
(153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),
|
| 60 |
+
(102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),
|
| 61 |
+
(102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
|
| 62 |
+
(102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
|
| 63 |
+
(102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
|
| 64 |
+
(51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
|
| 65 |
+
(51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
|
| 66 |
+
(51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
|
| 67 |
+
(51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
|
| 68 |
+
(51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
|
| 69 |
+
(0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
|
| 70 |
+
(0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
|
| 71 |
+
(0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
|
| 72 |
+
(0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
|
| 73 |
+
(34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
|
| 74 |
+
(136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
|
| 75 |
+
(238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
|
| 76 |
+
(0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
|
| 77 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 78 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 79 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 80 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 81 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 82 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
|
| 83 |
+
# fmt: on
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# so build a prototype image to be used for palette resampling
|
| 87 |
+
def build_prototype_image() -> Image.Image:
|
| 88 |
+
image = Image.new("L", (1, len(_Palm8BitColormapValues)))
|
| 89 |
+
image.putdata(list(range(len(_Palm8BitColormapValues))))
|
| 90 |
+
palettedata: tuple[int, ...] = ()
|
| 91 |
+
for colormapValue in _Palm8BitColormapValues:
|
| 92 |
+
palettedata += colormapValue
|
| 93 |
+
palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))
|
| 94 |
+
image.putpalette(palettedata)
|
| 95 |
+
return image
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
Palm8BitColormapImage = build_prototype_image()
|
| 99 |
+
|
| 100 |
+
# OK, we now have in Palm8BitColormapImage,
|
| 101 |
+
# a "P"-mode image with the right palette
|
| 102 |
+
#
|
| 103 |
+
# --------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
|
| 106 |
+
|
| 107 |
+
_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
#
|
| 111 |
+
# --------------------------------------------------------------------
|
| 112 |
+
|
| 113 |
+
##
|
| 114 |
+
# (Internal) Image save plugin for the Palm format.
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 118 |
+
if im.mode == "P":
|
| 119 |
+
# we assume this is a color Palm image with the standard colormap,
|
| 120 |
+
# unless the "info" dict has a "custom-colormap" field
|
| 121 |
+
|
| 122 |
+
rawmode = "P"
|
| 123 |
+
bpp = 8
|
| 124 |
+
version = 1
|
| 125 |
+
|
| 126 |
+
elif im.mode == "L":
|
| 127 |
+
if im.encoderinfo.get("bpp") in (1, 2, 4):
|
| 128 |
+
# this is 8-bit grayscale, so we shift it to get the high-order bits,
|
| 129 |
+
# and invert it because
|
| 130 |
+
# Palm does grayscale from white (0) to black (1)
|
| 131 |
+
bpp = im.encoderinfo["bpp"]
|
| 132 |
+
maxval = (1 << bpp) - 1
|
| 133 |
+
shift = 8 - bpp
|
| 134 |
+
im = im.point(lambda x: maxval - (x >> shift))
|
| 135 |
+
elif im.info.get("bpp") in (1, 2, 4):
|
| 136 |
+
# here we assume that even though the inherent mode is 8-bit grayscale,
|
| 137 |
+
# only the lower bpp bits are significant.
|
| 138 |
+
# We invert them to match the Palm.
|
| 139 |
+
bpp = im.info["bpp"]
|
| 140 |
+
maxval = (1 << bpp) - 1
|
| 141 |
+
im = im.point(lambda x: maxval - (x & maxval))
|
| 142 |
+
else:
|
| 143 |
+
msg = f"cannot write mode {im.mode} as Palm"
|
| 144 |
+
raise OSError(msg)
|
| 145 |
+
|
| 146 |
+
# we ignore the palette here
|
| 147 |
+
im._mode = "P"
|
| 148 |
+
rawmode = f"P;{bpp}"
|
| 149 |
+
version = 1
|
| 150 |
+
|
| 151 |
+
elif im.mode == "1":
|
| 152 |
+
# monochrome -- write it inverted, as is the Palm standard
|
| 153 |
+
rawmode = "1;I"
|
| 154 |
+
bpp = 1
|
| 155 |
+
version = 0
|
| 156 |
+
|
| 157 |
+
else:
|
| 158 |
+
msg = f"cannot write mode {im.mode} as Palm"
|
| 159 |
+
raise OSError(msg)
|
| 160 |
+
|
| 161 |
+
#
|
| 162 |
+
# make sure image data is available
|
| 163 |
+
im.load()
|
| 164 |
+
|
| 165 |
+
# write header
|
| 166 |
+
|
| 167 |
+
cols = im.size[0]
|
| 168 |
+
rows = im.size[1]
|
| 169 |
+
|
| 170 |
+
rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2
|
| 171 |
+
transparent_index = 0
|
| 172 |
+
compression_type = _COMPRESSION_TYPES["none"]
|
| 173 |
+
|
| 174 |
+
flags = 0
|
| 175 |
+
if im.mode == "P" and "custom-colormap" in im.info:
|
| 176 |
+
flags = flags & _FLAGS["custom-colormap"]
|
| 177 |
+
colormapsize = 4 * 256 + 2
|
| 178 |
+
colormapmode = im.palette.mode
|
| 179 |
+
colormap = im.getdata().getpalette()
|
| 180 |
+
else:
|
| 181 |
+
colormapsize = 0
|
| 182 |
+
|
| 183 |
+
if "offset" in im.info:
|
| 184 |
+
offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4
|
| 185 |
+
else:
|
| 186 |
+
offset = 0
|
| 187 |
+
|
| 188 |
+
fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags))
|
| 189 |
+
fp.write(o8(bpp))
|
| 190 |
+
fp.write(o8(version))
|
| 191 |
+
fp.write(o16b(offset))
|
| 192 |
+
fp.write(o8(transparent_index))
|
| 193 |
+
fp.write(o8(compression_type))
|
| 194 |
+
fp.write(o16b(0)) # reserved by Palm
|
| 195 |
+
|
| 196 |
+
# now write colormap if necessary
|
| 197 |
+
|
| 198 |
+
if colormapsize > 0:
|
| 199 |
+
fp.write(o16b(256))
|
| 200 |
+
for i in range(256):
|
| 201 |
+
fp.write(o8(i))
|
| 202 |
+
if colormapmode == "RGB":
|
| 203 |
+
fp.write(
|
| 204 |
+
o8(colormap[3 * i])
|
| 205 |
+
+ o8(colormap[3 * i + 1])
|
| 206 |
+
+ o8(colormap[3 * i + 2])
|
| 207 |
+
)
|
| 208 |
+
elif colormapmode == "RGBA":
|
| 209 |
+
fp.write(
|
| 210 |
+
o8(colormap[4 * i])
|
| 211 |
+
+ o8(colormap[4 * i + 1])
|
| 212 |
+
+ o8(colormap[4 * i + 2])
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# now convert data to raw form
|
| 216 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))])
|
| 217 |
+
|
| 218 |
+
if hasattr(fp, "flush"):
|
| 219 |
+
fp.flush()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
#
|
| 223 |
+
# --------------------------------------------------------------------
|
| 224 |
+
|
| 225 |
+
Image.register_save("Palm", _save)
|
| 226 |
+
|
| 227 |
+
Image.register_extension("Palm", ".palm")
|
| 228 |
+
|
| 229 |
+
Image.register_mime("Palm", "image/palm")
|
valley/lib/python3.10/site-packages/PIL/PcdImagePlugin.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PCD file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-05-10 fl Created
|
| 9 |
+
# 96-05-27 fl Added draft mode (128x192, 256x384)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from . import Image, ImageFile
|
| 19 |
+
|
| 20 |
+
##
|
| 21 |
+
# Image plugin for PhotoCD images. This plugin only reads the 768x512
|
| 22 |
+
# image from the file; higher resolutions are encoded in a proprietary
|
| 23 |
+
# encoding.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PcdImageFile(ImageFile.ImageFile):
|
| 27 |
+
format = "PCD"
|
| 28 |
+
format_description = "Kodak PhotoCD"
|
| 29 |
+
|
| 30 |
+
def _open(self) -> None:
|
| 31 |
+
# rough
|
| 32 |
+
assert self.fp is not None
|
| 33 |
+
|
| 34 |
+
self.fp.seek(2048)
|
| 35 |
+
s = self.fp.read(2048)
|
| 36 |
+
|
| 37 |
+
if s[:4] != b"PCD_":
|
| 38 |
+
msg = "not a PCD file"
|
| 39 |
+
raise SyntaxError(msg)
|
| 40 |
+
|
| 41 |
+
orientation = s[1538] & 3
|
| 42 |
+
self.tile_post_rotate = None
|
| 43 |
+
if orientation == 1:
|
| 44 |
+
self.tile_post_rotate = 90
|
| 45 |
+
elif orientation == 3:
|
| 46 |
+
self.tile_post_rotate = -90
|
| 47 |
+
|
| 48 |
+
self._mode = "RGB"
|
| 49 |
+
self._size = 768, 512 # FIXME: not correct for rotated images!
|
| 50 |
+
self.tile = [("pcd", (0, 0) + self.size, 96 * 2048, None)]
|
| 51 |
+
|
| 52 |
+
def load_end(self) -> None:
|
| 53 |
+
if self.tile_post_rotate:
|
| 54 |
+
# Handle rotated PCDs
|
| 55 |
+
assert self.im is not None
|
| 56 |
+
|
| 57 |
+
self.im = self.im.rotate(self.tile_post_rotate)
|
| 58 |
+
self._size = self.im.size
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
#
|
| 62 |
+
# registry
|
| 63 |
+
|
| 64 |
+
Image.register_open(PcdImageFile.format, PcdImageFile)
|
|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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
|
valley/lib/python3.10/site-packages/PIL/PcxImagePlugin.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PCX file handling
|
| 6 |
+
#
|
| 7 |
+
# This format was originally used by ZSoft's popular PaintBrush
|
| 8 |
+
# program for the IBM PC. It is also supported by many MS-DOS and
|
| 9 |
+
# Windows applications, including the Windows PaintBrush program in
|
| 10 |
+
# Windows 3.
|
| 11 |
+
#
|
| 12 |
+
# history:
|
| 13 |
+
# 1995-09-01 fl Created
|
| 14 |
+
# 1996-05-20 fl Fixed RGB support
|
| 15 |
+
# 1997-01-03 fl Fixed 2-bit and 4-bit support
|
| 16 |
+
# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)
|
| 17 |
+
# 1999-02-07 fl Added write support
|
| 18 |
+
# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust
|
| 19 |
+
# 2002-07-30 fl Seek from to current position, not beginning of file
|
| 20 |
+
# 2003-06-03 fl Extract DPI settings (info["dpi"])
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 23 |
+
# Copyright (c) 1995-2003 by Fredrik Lundh.
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import io
|
| 30 |
+
import logging
|
| 31 |
+
from typing import IO
|
| 32 |
+
|
| 33 |
+
from . import Image, ImageFile, ImagePalette
|
| 34 |
+
from ._binary import i16le as i16
|
| 35 |
+
from ._binary import o8
|
| 36 |
+
from ._binary import o16le as o16
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _accept(prefix: bytes) -> bool:
|
| 42 |
+
return prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
##
|
| 46 |
+
# Image plugin for Paintbrush images.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PcxImageFile(ImageFile.ImageFile):
|
| 50 |
+
format = "PCX"
|
| 51 |
+
format_description = "Paintbrush"
|
| 52 |
+
|
| 53 |
+
def _open(self) -> None:
|
| 54 |
+
# header
|
| 55 |
+
assert self.fp is not None
|
| 56 |
+
|
| 57 |
+
s = self.fp.read(128)
|
| 58 |
+
if not _accept(s):
|
| 59 |
+
msg = "not a PCX file"
|
| 60 |
+
raise SyntaxError(msg)
|
| 61 |
+
|
| 62 |
+
# image
|
| 63 |
+
bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
|
| 64 |
+
if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
|
| 65 |
+
msg = "bad PCX image size"
|
| 66 |
+
raise SyntaxError(msg)
|
| 67 |
+
logger.debug("BBox: %s %s %s %s", *bbox)
|
| 68 |
+
|
| 69 |
+
# format
|
| 70 |
+
version = s[1]
|
| 71 |
+
bits = s[3]
|
| 72 |
+
planes = s[65]
|
| 73 |
+
provided_stride = i16(s, 66)
|
| 74 |
+
logger.debug(
|
| 75 |
+
"PCX version %s, bits %s, planes %s, stride %s",
|
| 76 |
+
version,
|
| 77 |
+
bits,
|
| 78 |
+
planes,
|
| 79 |
+
provided_stride,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
self.info["dpi"] = i16(s, 12), i16(s, 14)
|
| 83 |
+
|
| 84 |
+
if bits == 1 and planes == 1:
|
| 85 |
+
mode = rawmode = "1"
|
| 86 |
+
|
| 87 |
+
elif bits == 1 and planes in (2, 4):
|
| 88 |
+
mode = "P"
|
| 89 |
+
rawmode = "P;%dL" % planes
|
| 90 |
+
self.palette = ImagePalette.raw("RGB", s[16:64])
|
| 91 |
+
|
| 92 |
+
elif version == 5 and bits == 8 and planes == 1:
|
| 93 |
+
mode = rawmode = "L"
|
| 94 |
+
# FIXME: hey, this doesn't work with the incremental loader !!!
|
| 95 |
+
self.fp.seek(-769, io.SEEK_END)
|
| 96 |
+
s = self.fp.read(769)
|
| 97 |
+
if len(s) == 769 and s[0] == 12:
|
| 98 |
+
# check if the palette is linear grayscale
|
| 99 |
+
for i in range(256):
|
| 100 |
+
if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
|
| 101 |
+
mode = rawmode = "P"
|
| 102 |
+
break
|
| 103 |
+
if mode == "P":
|
| 104 |
+
self.palette = ImagePalette.raw("RGB", s[1:])
|
| 105 |
+
self.fp.seek(128)
|
| 106 |
+
|
| 107 |
+
elif version == 5 and bits == 8 and planes == 3:
|
| 108 |
+
mode = "RGB"
|
| 109 |
+
rawmode = "RGB;L"
|
| 110 |
+
|
| 111 |
+
else:
|
| 112 |
+
msg = "unknown PCX mode"
|
| 113 |
+
raise OSError(msg)
|
| 114 |
+
|
| 115 |
+
self._mode = mode
|
| 116 |
+
self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
| 117 |
+
|
| 118 |
+
# Don't trust the passed in stride.
|
| 119 |
+
# Calculate the approximate position for ourselves.
|
| 120 |
+
# CVE-2020-35653
|
| 121 |
+
stride = (self._size[0] * bits + 7) // 8
|
| 122 |
+
|
| 123 |
+
# While the specification states that this must be even,
|
| 124 |
+
# not all images follow this
|
| 125 |
+
if provided_stride != stride:
|
| 126 |
+
stride += stride % 2
|
| 127 |
+
|
| 128 |
+
bbox = (0, 0) + self.size
|
| 129 |
+
logger.debug("size: %sx%s", *self.size)
|
| 130 |
+
|
| 131 |
+
self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# --------------------------------------------------------------------
|
| 135 |
+
# save PCX files
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
SAVE = {
|
| 139 |
+
# mode: (version, bits, planes, raw mode)
|
| 140 |
+
"1": (2, 1, 1, "1"),
|
| 141 |
+
"L": (5, 8, 1, "L"),
|
| 142 |
+
"P": (5, 8, 1, "P"),
|
| 143 |
+
"RGB": (5, 8, 3, "RGB;L"),
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 148 |
+
try:
|
| 149 |
+
version, bits, planes, rawmode = SAVE[im.mode]
|
| 150 |
+
except KeyError as e:
|
| 151 |
+
msg = f"Cannot save {im.mode} images as PCX"
|
| 152 |
+
raise ValueError(msg) from e
|
| 153 |
+
|
| 154 |
+
# bytes per plane
|
| 155 |
+
stride = (im.size[0] * bits + 7) // 8
|
| 156 |
+
# stride should be even
|
| 157 |
+
stride += stride % 2
|
| 158 |
+
# Stride needs to be kept in sync with the PcxEncode.c version.
|
| 159 |
+
# Ideally it should be passed in in the state, but the bytes value
|
| 160 |
+
# gets overwritten.
|
| 161 |
+
|
| 162 |
+
logger.debug(
|
| 163 |
+
"PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
|
| 164 |
+
im.size[0],
|
| 165 |
+
bits,
|
| 166 |
+
stride,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# under windows, we could determine the current screen size with
|
| 170 |
+
# "Image.core.display_mode()[1]", but I think that's overkill...
|
| 171 |
+
|
| 172 |
+
screen = im.size
|
| 173 |
+
|
| 174 |
+
dpi = 100, 100
|
| 175 |
+
|
| 176 |
+
# PCX header
|
| 177 |
+
fp.write(
|
| 178 |
+
o8(10)
|
| 179 |
+
+ o8(version)
|
| 180 |
+
+ o8(1)
|
| 181 |
+
+ o8(bits)
|
| 182 |
+
+ o16(0)
|
| 183 |
+
+ o16(0)
|
| 184 |
+
+ o16(im.size[0] - 1)
|
| 185 |
+
+ o16(im.size[1] - 1)
|
| 186 |
+
+ o16(dpi[0])
|
| 187 |
+
+ o16(dpi[1])
|
| 188 |
+
+ b"\0" * 24
|
| 189 |
+
+ b"\xFF" * 24
|
| 190 |
+
+ b"\0"
|
| 191 |
+
+ o8(planes)
|
| 192 |
+
+ o16(stride)
|
| 193 |
+
+ o16(1)
|
| 194 |
+
+ o16(screen[0])
|
| 195 |
+
+ o16(screen[1])
|
| 196 |
+
+ b"\0" * 54
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
assert fp.tell() == 128
|
| 200 |
+
|
| 201 |
+
ImageFile._save(im, fp, [("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))])
|
| 202 |
+
|
| 203 |
+
if im.mode == "P":
|
| 204 |
+
# colour palette
|
| 205 |
+
assert im.im is not None
|
| 206 |
+
|
| 207 |
+
fp.write(o8(12))
|
| 208 |
+
palette = im.im.getpalette("RGB", "RGB")
|
| 209 |
+
palette += b"\x00" * (768 - len(palette))
|
| 210 |
+
fp.write(palette) # 768 bytes
|
| 211 |
+
elif im.mode == "L":
|
| 212 |
+
# grayscale palette
|
| 213 |
+
fp.write(o8(12))
|
| 214 |
+
for i in range(256):
|
| 215 |
+
fp.write(o8(i) * 3)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# --------------------------------------------------------------------
|
| 219 |
+
# registry
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
|
| 223 |
+
Image.register_save(PcxImageFile.format, _save)
|
| 224 |
+
|
| 225 |
+
Image.register_extension(PcxImageFile.format, ".pcx")
|
| 226 |
+
|
| 227 |
+
Image.register_mime(PcxImageFile.format, "image/x-pcx")
|
valley/lib/python3.10/site-packages/PIL/PdfImagePlugin.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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
|
| 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(im, filename, existing_pdf, image_refs):
|
| 52 |
+
# FIXME: Should replace ASCIIHexDecode with RunLengthDecode
|
| 53 |
+
# (packbits) or LZWDecode (tiff/lzw compression). Note that
|
| 54 |
+
# PDF 1.2 also supports Flatedecode (zip compression).
|
| 55 |
+
|
| 56 |
+
params = None
|
| 57 |
+
decode = None
|
| 58 |
+
|
| 59 |
+
#
|
| 60 |
+
# Get image characteristics
|
| 61 |
+
|
| 62 |
+
width, height = im.size
|
| 63 |
+
|
| 64 |
+
dict_obj = {"BitsPerComponent": 8}
|
| 65 |
+
if im.mode == "1":
|
| 66 |
+
if features.check("libtiff"):
|
| 67 |
+
filter = "CCITTFaxDecode"
|
| 68 |
+
dict_obj["BitsPerComponent"] = 1
|
| 69 |
+
params = PdfParser.PdfArray(
|
| 70 |
+
[
|
| 71 |
+
PdfParser.PdfDict(
|
| 72 |
+
{
|
| 73 |
+
"K": -1,
|
| 74 |
+
"BlackIs1": True,
|
| 75 |
+
"Columns": width,
|
| 76 |
+
"Rows": height,
|
| 77 |
+
}
|
| 78 |
+
)
|
| 79 |
+
]
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
filter = "DCTDecode"
|
| 83 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
|
| 84 |
+
procset = "ImageB" # grayscale
|
| 85 |
+
elif im.mode == "L":
|
| 86 |
+
filter = "DCTDecode"
|
| 87 |
+
# params = f"<< /Predictor 15 /Columns {width-2} >>"
|
| 88 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
|
| 89 |
+
procset = "ImageB" # grayscale
|
| 90 |
+
elif im.mode == "LA":
|
| 91 |
+
filter = "JPXDecode"
|
| 92 |
+
# params = f"<< /Predictor 15 /Columns {width-2} >>"
|
| 93 |
+
procset = "ImageB" # grayscale
|
| 94 |
+
dict_obj["SMaskInData"] = 1
|
| 95 |
+
elif im.mode == "P":
|
| 96 |
+
filter = "ASCIIHexDecode"
|
| 97 |
+
palette = im.getpalette()
|
| 98 |
+
dict_obj["ColorSpace"] = [
|
| 99 |
+
PdfParser.PdfName("Indexed"),
|
| 100 |
+
PdfParser.PdfName("DeviceRGB"),
|
| 101 |
+
len(palette) // 3 - 1,
|
| 102 |
+
PdfParser.PdfBinary(palette),
|
| 103 |
+
]
|
| 104 |
+
procset = "ImageI" # indexed color
|
| 105 |
+
|
| 106 |
+
if "transparency" in im.info:
|
| 107 |
+
smask = im.convert("LA").getchannel("A")
|
| 108 |
+
smask.encoderinfo = {}
|
| 109 |
+
|
| 110 |
+
image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]
|
| 111 |
+
dict_obj["SMask"] = image_ref
|
| 112 |
+
elif im.mode == "RGB":
|
| 113 |
+
filter = "DCTDecode"
|
| 114 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")
|
| 115 |
+
procset = "ImageC" # color images
|
| 116 |
+
elif im.mode == "RGBA":
|
| 117 |
+
filter = "JPXDecode"
|
| 118 |
+
procset = "ImageC" # color images
|
| 119 |
+
dict_obj["SMaskInData"] = 1
|
| 120 |
+
elif im.mode == "CMYK":
|
| 121 |
+
filter = "DCTDecode"
|
| 122 |
+
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")
|
| 123 |
+
procset = "ImageC" # color images
|
| 124 |
+
decode = [1, 0, 1, 0, 1, 0, 1, 0]
|
| 125 |
+
else:
|
| 126 |
+
msg = f"cannot save mode {im.mode}"
|
| 127 |
+
raise ValueError(msg)
|
| 128 |
+
|
| 129 |
+
#
|
| 130 |
+
# image
|
| 131 |
+
|
| 132 |
+
op = io.BytesIO()
|
| 133 |
+
|
| 134 |
+
if filter == "ASCIIHexDecode":
|
| 135 |
+
ImageFile._save(im, op, [("hex", (0, 0) + im.size, 0, im.mode)])
|
| 136 |
+
elif filter == "CCITTFaxDecode":
|
| 137 |
+
im.save(
|
| 138 |
+
op,
|
| 139 |
+
"TIFF",
|
| 140 |
+
compression="group4",
|
| 141 |
+
# use a single strip
|
| 142 |
+
strip_size=math.ceil(width / 8) * height,
|
| 143 |
+
)
|
| 144 |
+
elif filter == "DCTDecode":
|
| 145 |
+
Image.SAVE["JPEG"](im, op, filename)
|
| 146 |
+
elif filter == "JPXDecode":
|
| 147 |
+
del dict_obj["BitsPerComponent"]
|
| 148 |
+
Image.SAVE["JPEG2000"](im, op, filename)
|
| 149 |
+
else:
|
| 150 |
+
msg = f"unsupported PDF filter ({filter})"
|
| 151 |
+
raise ValueError(msg)
|
| 152 |
+
|
| 153 |
+
stream = op.getvalue()
|
| 154 |
+
if filter == "CCITTFaxDecode":
|
| 155 |
+
stream = stream[8:]
|
| 156 |
+
filter = PdfParser.PdfArray([PdfParser.PdfName(filter)])
|
| 157 |
+
else:
|
| 158 |
+
filter = PdfParser.PdfName(filter)
|
| 159 |
+
|
| 160 |
+
image_ref = image_refs.pop(0)
|
| 161 |
+
existing_pdf.write_obj(
|
| 162 |
+
image_ref,
|
| 163 |
+
stream=stream,
|
| 164 |
+
Type=PdfParser.PdfName("XObject"),
|
| 165 |
+
Subtype=PdfParser.PdfName("Image"),
|
| 166 |
+
Width=width, # * 72.0 / x_resolution,
|
| 167 |
+
Height=height, # * 72.0 / y_resolution,
|
| 168 |
+
Filter=filter,
|
| 169 |
+
Decode=decode,
|
| 170 |
+
DecodeParms=params,
|
| 171 |
+
**dict_obj,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
return image_ref, procset
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _save(im, fp, filename, save_all=False):
|
| 178 |
+
is_appending = im.encoderinfo.get("append", False)
|
| 179 |
+
if is_appending:
|
| 180 |
+
existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="r+b")
|
| 181 |
+
else:
|
| 182 |
+
existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="w+b")
|
| 183 |
+
|
| 184 |
+
dpi = im.encoderinfo.get("dpi")
|
| 185 |
+
if dpi:
|
| 186 |
+
x_resolution = dpi[0]
|
| 187 |
+
y_resolution = dpi[1]
|
| 188 |
+
else:
|
| 189 |
+
x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0)
|
| 190 |
+
|
| 191 |
+
info = {
|
| 192 |
+
"title": (
|
| 193 |
+
None if is_appending else os.path.splitext(os.path.basename(filename))[0]
|
| 194 |
+
),
|
| 195 |
+
"author": None,
|
| 196 |
+
"subject": None,
|
| 197 |
+
"keywords": None,
|
| 198 |
+
"creator": None,
|
| 199 |
+
"producer": None,
|
| 200 |
+
"creationDate": None if is_appending else time.gmtime(),
|
| 201 |
+
"modDate": None if is_appending else time.gmtime(),
|
| 202 |
+
}
|
| 203 |
+
for k, default in info.items():
|
| 204 |
+
v = im.encoderinfo.get(k) if k in im.encoderinfo else default
|
| 205 |
+
if v:
|
| 206 |
+
existing_pdf.info[k[0].upper() + k[1:]] = v
|
| 207 |
+
|
| 208 |
+
#
|
| 209 |
+
# make sure image data is available
|
| 210 |
+
im.load()
|
| 211 |
+
|
| 212 |
+
existing_pdf.start_writing()
|
| 213 |
+
existing_pdf.write_header()
|
| 214 |
+
existing_pdf.write_comment(f"created by Pillow {__version__} PDF driver")
|
| 215 |
+
|
| 216 |
+
#
|
| 217 |
+
# pages
|
| 218 |
+
ims = [im]
|
| 219 |
+
if save_all:
|
| 220 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 221 |
+
for append_im in append_images:
|
| 222 |
+
append_im.encoderinfo = im.encoderinfo.copy()
|
| 223 |
+
ims.append(append_im)
|
| 224 |
+
number_of_pages = 0
|
| 225 |
+
image_refs = []
|
| 226 |
+
page_refs = []
|
| 227 |
+
contents_refs = []
|
| 228 |
+
for im in ims:
|
| 229 |
+
im_number_of_pages = 1
|
| 230 |
+
if save_all:
|
| 231 |
+
try:
|
| 232 |
+
im_number_of_pages = im.n_frames
|
| 233 |
+
except AttributeError:
|
| 234 |
+
# Image format does not have n_frames.
|
| 235 |
+
# It is a single frame image
|
| 236 |
+
pass
|
| 237 |
+
number_of_pages += im_number_of_pages
|
| 238 |
+
for i in range(im_number_of_pages):
|
| 239 |
+
image_refs.append(existing_pdf.next_object_id(0))
|
| 240 |
+
if im.mode == "P" and "transparency" in im.info:
|
| 241 |
+
image_refs.append(existing_pdf.next_object_id(0))
|
| 242 |
+
|
| 243 |
+
page_refs.append(existing_pdf.next_object_id(0))
|
| 244 |
+
contents_refs.append(existing_pdf.next_object_id(0))
|
| 245 |
+
existing_pdf.pages.append(page_refs[-1])
|
| 246 |
+
|
| 247 |
+
#
|
| 248 |
+
# catalog and list of pages
|
| 249 |
+
existing_pdf.write_catalog()
|
| 250 |
+
|
| 251 |
+
page_number = 0
|
| 252 |
+
for im_sequence in ims:
|
| 253 |
+
im_pages = ImageSequence.Iterator(im_sequence) if save_all else [im_sequence]
|
| 254 |
+
for im in im_pages:
|
| 255 |
+
image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)
|
| 256 |
+
|
| 257 |
+
#
|
| 258 |
+
# page
|
| 259 |
+
|
| 260 |
+
existing_pdf.write_page(
|
| 261 |
+
page_refs[page_number],
|
| 262 |
+
Resources=PdfParser.PdfDict(
|
| 263 |
+
ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],
|
| 264 |
+
XObject=PdfParser.PdfDict(image=image_ref),
|
| 265 |
+
),
|
| 266 |
+
MediaBox=[
|
| 267 |
+
0,
|
| 268 |
+
0,
|
| 269 |
+
im.width * 72.0 / x_resolution,
|
| 270 |
+
im.height * 72.0 / y_resolution,
|
| 271 |
+
],
|
| 272 |
+
Contents=contents_refs[page_number],
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
#
|
| 276 |
+
# page contents
|
| 277 |
+
|
| 278 |
+
page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (
|
| 279 |
+
im.width * 72.0 / x_resolution,
|
| 280 |
+
im.height * 72.0 / y_resolution,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
existing_pdf.write_obj(contents_refs[page_number], stream=page_contents)
|
| 284 |
+
|
| 285 |
+
page_number += 1
|
| 286 |
+
|
| 287 |
+
#
|
| 288 |
+
# trailer
|
| 289 |
+
existing_pdf.write_xref_and_trailer()
|
| 290 |
+
if hasattr(fp, "flush"):
|
| 291 |
+
fp.flush()
|
| 292 |
+
existing_pdf.close()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
#
|
| 296 |
+
# --------------------------------------------------------------------
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
Image.register_save("PDF", _save)
|
| 300 |
+
Image.register_save_all("PDF", _save_all)
|
| 301 |
+
|
| 302 |
+
Image.register_extension("PDF", ".pdf")
|
| 303 |
+
|
| 304 |
+
Image.register_mime("PDF", "application/pdf")
|
valley/lib/python3.10/site-packages/PIL/P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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PNG support code
|
| 6 |
+
#
|
| 7 |
+
# See "PNG (Portable Network Graphics) Specification, version 1.0;
|
| 8 |
+
# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
|
| 9 |
+
#
|
| 10 |
+
# history:
|
| 11 |
+
# 1996-05-06 fl Created (couldn't resist it)
|
| 12 |
+
# 1996-12-14 fl Upgraded, added read and verify support (0.2)
|
| 13 |
+
# 1996-12-15 fl Separate PNG stream parser
|
| 14 |
+
# 1996-12-29 fl Added write support, added getchunks
|
| 15 |
+
# 1996-12-30 fl Eliminated circular references in decoder (0.3)
|
| 16 |
+
# 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
|
| 17 |
+
# 2001-02-08 fl Added transparency support (from Zircon) (0.5)
|
| 18 |
+
# 2001-04-16 fl Don't close data source in "open" method (0.6)
|
| 19 |
+
# 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
|
| 20 |
+
# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
|
| 21 |
+
# 2004-09-20 fl Added PngInfo chunk container
|
| 22 |
+
# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
|
| 23 |
+
# 2008-08-13 fl Added tRNS support for RGB images
|
| 24 |
+
# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
|
| 25 |
+
# 2009-03-08 fl Added zTXT support (from Lowell Alleman)
|
| 26 |
+
# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
|
| 27 |
+
#
|
| 28 |
+
# Copyright (c) 1997-2009 by Secret Labs AB
|
| 29 |
+
# Copyright (c) 1996 by Fredrik Lundh
|
| 30 |
+
#
|
| 31 |
+
# See the README file for information on usage and redistribution.
|
| 32 |
+
#
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import itertools
|
| 36 |
+
import logging
|
| 37 |
+
import re
|
| 38 |
+
import struct
|
| 39 |
+
import warnings
|
| 40 |
+
import zlib
|
| 41 |
+
from enum import IntEnum
|
| 42 |
+
from typing import IO, TYPE_CHECKING, Any, NoReturn
|
| 43 |
+
|
| 44 |
+
from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
|
| 45 |
+
from ._binary import i16be as i16
|
| 46 |
+
from ._binary import i32be as i32
|
| 47 |
+
from ._binary import o8
|
| 48 |
+
from ._binary import o16be as o16
|
| 49 |
+
from ._binary import o32be as o32
|
| 50 |
+
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
from . import _imaging
|
| 53 |
+
|
| 54 |
+
logger = logging.getLogger(__name__)
|
| 55 |
+
|
| 56 |
+
is_cid = re.compile(rb"\w\w\w\w").match
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_MAGIC = b"\211PNG\r\n\032\n"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
_MODES = {
|
| 63 |
+
# supported bits/color combinations, and corresponding modes/rawmodes
|
| 64 |
+
# Grayscale
|
| 65 |
+
(1, 0): ("1", "1"),
|
| 66 |
+
(2, 0): ("L", "L;2"),
|
| 67 |
+
(4, 0): ("L", "L;4"),
|
| 68 |
+
(8, 0): ("L", "L"),
|
| 69 |
+
(16, 0): ("I;16", "I;16B"),
|
| 70 |
+
# Truecolour
|
| 71 |
+
(8, 2): ("RGB", "RGB"),
|
| 72 |
+
(16, 2): ("RGB", "RGB;16B"),
|
| 73 |
+
# Indexed-colour
|
| 74 |
+
(1, 3): ("P", "P;1"),
|
| 75 |
+
(2, 3): ("P", "P;2"),
|
| 76 |
+
(4, 3): ("P", "P;4"),
|
| 77 |
+
(8, 3): ("P", "P"),
|
| 78 |
+
# Grayscale with alpha
|
| 79 |
+
(8, 4): ("LA", "LA"),
|
| 80 |
+
(16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
|
| 81 |
+
# Truecolour with alpha
|
| 82 |
+
(8, 6): ("RGBA", "RGBA"),
|
| 83 |
+
(16, 6): ("RGBA", "RGBA;16B"),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
_simple_palette = re.compile(b"^\xff*\x00\xff*$")
|
| 88 |
+
|
| 89 |
+
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
|
| 90 |
+
"""
|
| 91 |
+
Maximum decompressed size for a iTXt or zTXt chunk.
|
| 92 |
+
Eliminates decompression bombs where compressed chunks can expand 1000x.
|
| 93 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 94 |
+
"""
|
| 95 |
+
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
|
| 96 |
+
"""
|
| 97 |
+
Set the maximum total text chunk size.
|
| 98 |
+
See :ref:`Text in PNG File Format<png-text>`.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# APNG frame disposal modes
|
| 103 |
+
class Disposal(IntEnum):
|
| 104 |
+
OP_NONE = 0
|
| 105 |
+
"""
|
| 106 |
+
No disposal is done on this frame before rendering the next frame.
|
| 107 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 108 |
+
"""
|
| 109 |
+
OP_BACKGROUND = 1
|
| 110 |
+
"""
|
| 111 |
+
This frame’s modified region is cleared to fully transparent black before rendering
|
| 112 |
+
the next frame.
|
| 113 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 114 |
+
"""
|
| 115 |
+
OP_PREVIOUS = 2
|
| 116 |
+
"""
|
| 117 |
+
This frame’s modified region is reverted to the previous frame’s contents before
|
| 118 |
+
rendering the next frame.
|
| 119 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# APNG frame blend modes
|
| 124 |
+
class Blend(IntEnum):
|
| 125 |
+
OP_SOURCE = 0
|
| 126 |
+
"""
|
| 127 |
+
All color components of this frame, including alpha, overwrite the previous output
|
| 128 |
+
image contents.
|
| 129 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 130 |
+
"""
|
| 131 |
+
OP_OVER = 1
|
| 132 |
+
"""
|
| 133 |
+
This frame should be alpha composited with the previous output image contents.
|
| 134 |
+
See :ref:`Saving APNG sequences<apng-saving>`.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _safe_zlib_decompress(s):
|
| 139 |
+
dobj = zlib.decompressobj()
|
| 140 |
+
plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
|
| 141 |
+
if dobj.unconsumed_tail:
|
| 142 |
+
msg = "Decompressed Data Too Large"
|
| 143 |
+
raise ValueError(msg)
|
| 144 |
+
return plaintext
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _crc32(data, seed=0):
|
| 148 |
+
return zlib.crc32(data, seed) & 0xFFFFFFFF
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# --------------------------------------------------------------------
|
| 152 |
+
# Support classes. Suitable for PNG and related formats like MNG etc.
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class ChunkStream:
|
| 156 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 157 |
+
self.fp: IO[bytes] | None = fp
|
| 158 |
+
self.queue: list[tuple[bytes, int, int]] | None = []
|
| 159 |
+
|
| 160 |
+
def read(self) -> tuple[bytes, int, int]:
|
| 161 |
+
"""Fetch a new chunk. Returns header information."""
|
| 162 |
+
cid = None
|
| 163 |
+
|
| 164 |
+
assert self.fp is not None
|
| 165 |
+
if self.queue:
|
| 166 |
+
cid, pos, length = self.queue.pop()
|
| 167 |
+
self.fp.seek(pos)
|
| 168 |
+
else:
|
| 169 |
+
s = self.fp.read(8)
|
| 170 |
+
cid = s[4:]
|
| 171 |
+
pos = self.fp.tell()
|
| 172 |
+
length = i32(s)
|
| 173 |
+
|
| 174 |
+
if not is_cid(cid):
|
| 175 |
+
if not ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 176 |
+
msg = f"broken PNG file (chunk {repr(cid)})"
|
| 177 |
+
raise SyntaxError(msg)
|
| 178 |
+
|
| 179 |
+
return cid, pos, length
|
| 180 |
+
|
| 181 |
+
def __enter__(self) -> ChunkStream:
|
| 182 |
+
return self
|
| 183 |
+
|
| 184 |
+
def __exit__(self, *args: object) -> None:
|
| 185 |
+
self.close()
|
| 186 |
+
|
| 187 |
+
def close(self) -> None:
|
| 188 |
+
self.queue = self.fp = None
|
| 189 |
+
|
| 190 |
+
def push(self, cid: bytes, pos: int, length: int) -> None:
|
| 191 |
+
assert self.queue is not None
|
| 192 |
+
self.queue.append((cid, pos, length))
|
| 193 |
+
|
| 194 |
+
def call(self, cid, pos, length):
|
| 195 |
+
"""Call the appropriate chunk handler"""
|
| 196 |
+
|
| 197 |
+
logger.debug("STREAM %r %s %s", cid, pos, length)
|
| 198 |
+
return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
|
| 199 |
+
|
| 200 |
+
def crc(self, cid: bytes, data: bytes) -> None:
|
| 201 |
+
"""Read and verify checksum"""
|
| 202 |
+
|
| 203 |
+
# Skip CRC checks for ancillary chunks if allowed to load truncated
|
| 204 |
+
# images
|
| 205 |
+
# 5th byte of first char is 1 [specs, section 5.4]
|
| 206 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
|
| 207 |
+
self.crc_skip(cid, data)
|
| 208 |
+
return
|
| 209 |
+
|
| 210 |
+
assert self.fp is not None
|
| 211 |
+
try:
|
| 212 |
+
crc1 = _crc32(data, _crc32(cid))
|
| 213 |
+
crc2 = i32(self.fp.read(4))
|
| 214 |
+
if crc1 != crc2:
|
| 215 |
+
msg = f"broken PNG file (bad header checksum in {repr(cid)})"
|
| 216 |
+
raise SyntaxError(msg)
|
| 217 |
+
except struct.error as e:
|
| 218 |
+
msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
|
| 219 |
+
raise SyntaxError(msg) from e
|
| 220 |
+
|
| 221 |
+
def crc_skip(self, cid: bytes, data: bytes) -> None:
|
| 222 |
+
"""Read checksum"""
|
| 223 |
+
|
| 224 |
+
assert self.fp is not None
|
| 225 |
+
self.fp.read(4)
|
| 226 |
+
|
| 227 |
+
def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
|
| 228 |
+
# Simple approach; just calculate checksum for all remaining
|
| 229 |
+
# blocks. Must be called directly after open.
|
| 230 |
+
|
| 231 |
+
cids = []
|
| 232 |
+
|
| 233 |
+
while True:
|
| 234 |
+
try:
|
| 235 |
+
cid, pos, length = self.read()
|
| 236 |
+
except struct.error as e:
|
| 237 |
+
msg = "truncated PNG file"
|
| 238 |
+
raise OSError(msg) from e
|
| 239 |
+
|
| 240 |
+
if cid == endchunk:
|
| 241 |
+
break
|
| 242 |
+
self.crc(cid, ImageFile._safe_read(self.fp, length))
|
| 243 |
+
cids.append(cid)
|
| 244 |
+
|
| 245 |
+
return cids
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class iTXt(str):
|
| 249 |
+
"""
|
| 250 |
+
Subclass of string to allow iTXt chunks to look like strings while
|
| 251 |
+
keeping their extra information
|
| 252 |
+
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
lang: str | bytes | None
|
| 256 |
+
tkey: str | bytes | None
|
| 257 |
+
|
| 258 |
+
@staticmethod
|
| 259 |
+
def __new__(cls, text, lang=None, tkey=None):
|
| 260 |
+
"""
|
| 261 |
+
:param cls: the class to use when creating the instance
|
| 262 |
+
:param text: value for this key
|
| 263 |
+
:param lang: language code
|
| 264 |
+
:param tkey: UTF-8 version of the key name
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
self = str.__new__(cls, text)
|
| 268 |
+
self.lang = lang
|
| 269 |
+
self.tkey = tkey
|
| 270 |
+
return self
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class PngInfo:
|
| 274 |
+
"""
|
| 275 |
+
PNG chunk container (for use with save(pnginfo=))
|
| 276 |
+
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
def __init__(self) -> None:
|
| 280 |
+
self.chunks: list[tuple[bytes, bytes, bool]] = []
|
| 281 |
+
|
| 282 |
+
def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
|
| 283 |
+
"""Appends an arbitrary chunk. Use with caution.
|
| 284 |
+
|
| 285 |
+
:param cid: a byte string, 4 bytes long.
|
| 286 |
+
:param data: a byte string of the encoded data
|
| 287 |
+
:param after_idat: for use with private chunks. Whether the chunk
|
| 288 |
+
should be written after IDAT
|
| 289 |
+
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
self.chunks.append((cid, data, after_idat))
|
| 293 |
+
|
| 294 |
+
def add_itxt(
|
| 295 |
+
self,
|
| 296 |
+
key: str | bytes,
|
| 297 |
+
value: str | bytes,
|
| 298 |
+
lang: str | bytes = "",
|
| 299 |
+
tkey: str | bytes = "",
|
| 300 |
+
zip: bool = False,
|
| 301 |
+
) -> None:
|
| 302 |
+
"""Appends an iTXt chunk.
|
| 303 |
+
|
| 304 |
+
:param key: latin-1 encodable text key name
|
| 305 |
+
:param value: value for this key
|
| 306 |
+
:param lang: language code
|
| 307 |
+
:param tkey: UTF-8 version of the key name
|
| 308 |
+
:param zip: compression flag
|
| 309 |
+
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
if not isinstance(key, bytes):
|
| 313 |
+
key = key.encode("latin-1", "strict")
|
| 314 |
+
if not isinstance(value, bytes):
|
| 315 |
+
value = value.encode("utf-8", "strict")
|
| 316 |
+
if not isinstance(lang, bytes):
|
| 317 |
+
lang = lang.encode("utf-8", "strict")
|
| 318 |
+
if not isinstance(tkey, bytes):
|
| 319 |
+
tkey = tkey.encode("utf-8", "strict")
|
| 320 |
+
|
| 321 |
+
if zip:
|
| 322 |
+
self.add(
|
| 323 |
+
b"iTXt",
|
| 324 |
+
key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
|
| 325 |
+
)
|
| 326 |
+
else:
|
| 327 |
+
self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
|
| 328 |
+
|
| 329 |
+
def add_text(
|
| 330 |
+
self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
|
| 331 |
+
) -> None:
|
| 332 |
+
"""Appends a text chunk.
|
| 333 |
+
|
| 334 |
+
:param key: latin-1 encodable text key name
|
| 335 |
+
:param value: value for this key, text or an
|
| 336 |
+
:py:class:`PIL.PngImagePlugin.iTXt` instance
|
| 337 |
+
:param zip: compression flag
|
| 338 |
+
|
| 339 |
+
"""
|
| 340 |
+
if isinstance(value, iTXt):
|
| 341 |
+
return self.add_itxt(
|
| 342 |
+
key,
|
| 343 |
+
value,
|
| 344 |
+
value.lang if value.lang is not None else b"",
|
| 345 |
+
value.tkey if value.tkey is not None else b"",
|
| 346 |
+
zip=zip,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# The tEXt chunk stores latin-1 text
|
| 350 |
+
if not isinstance(value, bytes):
|
| 351 |
+
try:
|
| 352 |
+
value = value.encode("latin-1", "strict")
|
| 353 |
+
except UnicodeError:
|
| 354 |
+
return self.add_itxt(key, value, zip=zip)
|
| 355 |
+
|
| 356 |
+
if not isinstance(key, bytes):
|
| 357 |
+
key = key.encode("latin-1", "strict")
|
| 358 |
+
|
| 359 |
+
if zip:
|
| 360 |
+
self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
|
| 361 |
+
else:
|
| 362 |
+
self.add(b"tEXt", key + b"\0" + value)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# --------------------------------------------------------------------
|
| 366 |
+
# PNG image stream (IHDR/IEND)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class PngStream(ChunkStream):
|
| 370 |
+
def __init__(self, fp):
|
| 371 |
+
super().__init__(fp)
|
| 372 |
+
|
| 373 |
+
# local copies of Image attributes
|
| 374 |
+
self.im_info = {}
|
| 375 |
+
self.im_text = {}
|
| 376 |
+
self.im_size = (0, 0)
|
| 377 |
+
self.im_mode = None
|
| 378 |
+
self.im_tile = None
|
| 379 |
+
self.im_palette = None
|
| 380 |
+
self.im_custom_mimetype = None
|
| 381 |
+
self.im_n_frames = None
|
| 382 |
+
self._seq_num = None
|
| 383 |
+
self.rewind_state = None
|
| 384 |
+
|
| 385 |
+
self.text_memory = 0
|
| 386 |
+
|
| 387 |
+
def check_text_memory(self, chunklen: int) -> None:
|
| 388 |
+
self.text_memory += chunklen
|
| 389 |
+
if self.text_memory > MAX_TEXT_MEMORY:
|
| 390 |
+
msg = (
|
| 391 |
+
"Too much memory used in text chunks: "
|
| 392 |
+
f"{self.text_memory}>MAX_TEXT_MEMORY"
|
| 393 |
+
)
|
| 394 |
+
raise ValueError(msg)
|
| 395 |
+
|
| 396 |
+
def save_rewind(self) -> None:
|
| 397 |
+
self.rewind_state = {
|
| 398 |
+
"info": self.im_info.copy(),
|
| 399 |
+
"tile": self.im_tile,
|
| 400 |
+
"seq_num": self._seq_num,
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
def rewind(self) -> None:
|
| 404 |
+
self.im_info = self.rewind_state["info"].copy()
|
| 405 |
+
self.im_tile = self.rewind_state["tile"]
|
| 406 |
+
self._seq_num = self.rewind_state["seq_num"]
|
| 407 |
+
|
| 408 |
+
def chunk_iCCP(self, pos: int, length: int) -> bytes:
|
| 409 |
+
# ICC profile
|
| 410 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 411 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 412 |
+
# Profile name 1-79 bytes (character string)
|
| 413 |
+
# Null separator 1 byte (null character)
|
| 414 |
+
# Compression method 1 byte (0)
|
| 415 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 416 |
+
i = s.find(b"\0")
|
| 417 |
+
logger.debug("iCCP profile name %r", s[:i])
|
| 418 |
+
comp_method = s[i + 1]
|
| 419 |
+
logger.debug("Compression method %s", comp_method)
|
| 420 |
+
if comp_method != 0:
|
| 421 |
+
msg = f"Unknown compression method {comp_method} in iCCP chunk"
|
| 422 |
+
raise SyntaxError(msg)
|
| 423 |
+
try:
|
| 424 |
+
icc_profile = _safe_zlib_decompress(s[i + 2 :])
|
| 425 |
+
except ValueError:
|
| 426 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 427 |
+
icc_profile = None
|
| 428 |
+
else:
|
| 429 |
+
raise
|
| 430 |
+
except zlib.error:
|
| 431 |
+
icc_profile = None # FIXME
|
| 432 |
+
self.im_info["icc_profile"] = icc_profile
|
| 433 |
+
return s
|
| 434 |
+
|
| 435 |
+
def chunk_IHDR(self, pos: int, length: int) -> bytes:
|
| 436 |
+
# image header
|
| 437 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 438 |
+
if length < 13:
|
| 439 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 440 |
+
return s
|
| 441 |
+
msg = "Truncated IHDR chunk"
|
| 442 |
+
raise ValueError(msg)
|
| 443 |
+
self.im_size = i32(s, 0), i32(s, 4)
|
| 444 |
+
try:
|
| 445 |
+
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
|
| 446 |
+
except Exception:
|
| 447 |
+
pass
|
| 448 |
+
if s[12]:
|
| 449 |
+
self.im_info["interlace"] = 1
|
| 450 |
+
if s[11]:
|
| 451 |
+
msg = "unknown filter category"
|
| 452 |
+
raise SyntaxError(msg)
|
| 453 |
+
return s
|
| 454 |
+
|
| 455 |
+
def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
|
| 456 |
+
# image data
|
| 457 |
+
if "bbox" in self.im_info:
|
| 458 |
+
tile = [("zip", self.im_info["bbox"], pos, self.im_rawmode)]
|
| 459 |
+
else:
|
| 460 |
+
if self.im_n_frames is not None:
|
| 461 |
+
self.im_info["default_image"] = True
|
| 462 |
+
tile = [("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
|
| 463 |
+
self.im_tile = tile
|
| 464 |
+
self.im_idat = length
|
| 465 |
+
msg = "image data found"
|
| 466 |
+
raise EOFError(msg)
|
| 467 |
+
|
| 468 |
+
def chunk_IEND(self, pos: int, length: int) -> NoReturn:
|
| 469 |
+
msg = "end of PNG image"
|
| 470 |
+
raise EOFError(msg)
|
| 471 |
+
|
| 472 |
+
def chunk_PLTE(self, pos: int, length: int) -> bytes:
|
| 473 |
+
# palette
|
| 474 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 475 |
+
if self.im_mode == "P":
|
| 476 |
+
self.im_palette = "RGB", s
|
| 477 |
+
return s
|
| 478 |
+
|
| 479 |
+
def chunk_tRNS(self, pos: int, length: int) -> bytes:
|
| 480 |
+
# transparency
|
| 481 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 482 |
+
if self.im_mode == "P":
|
| 483 |
+
if _simple_palette.match(s):
|
| 484 |
+
# tRNS contains only one full-transparent entry,
|
| 485 |
+
# other entries are full opaque
|
| 486 |
+
i = s.find(b"\0")
|
| 487 |
+
if i >= 0:
|
| 488 |
+
self.im_info["transparency"] = i
|
| 489 |
+
else:
|
| 490 |
+
# otherwise, we have a byte string with one alpha value
|
| 491 |
+
# for each palette entry
|
| 492 |
+
self.im_info["transparency"] = s
|
| 493 |
+
elif self.im_mode in ("1", "L", "I;16"):
|
| 494 |
+
self.im_info["transparency"] = i16(s)
|
| 495 |
+
elif self.im_mode == "RGB":
|
| 496 |
+
self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
|
| 497 |
+
return s
|
| 498 |
+
|
| 499 |
+
def chunk_gAMA(self, pos: int, length: int) -> bytes:
|
| 500 |
+
# gamma setting
|
| 501 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 502 |
+
self.im_info["gamma"] = i32(s) / 100000.0
|
| 503 |
+
return s
|
| 504 |
+
|
| 505 |
+
def chunk_cHRM(self, pos: int, length: int) -> bytes:
|
| 506 |
+
# chromaticity, 8 unsigned ints, actual value is scaled by 100,000
|
| 507 |
+
# WP x,y, Red x,y, Green x,y Blue x,y
|
| 508 |
+
|
| 509 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 510 |
+
raw_vals = struct.unpack(">%dI" % (len(s) // 4), s)
|
| 511 |
+
self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
|
| 512 |
+
return s
|
| 513 |
+
|
| 514 |
+
def chunk_sRGB(self, pos: int, length: int) -> bytes:
|
| 515 |
+
# srgb rendering intent, 1 byte
|
| 516 |
+
# 0 perceptual
|
| 517 |
+
# 1 relative colorimetric
|
| 518 |
+
# 2 saturation
|
| 519 |
+
# 3 absolute colorimetric
|
| 520 |
+
|
| 521 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 522 |
+
if length < 1:
|
| 523 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 524 |
+
return s
|
| 525 |
+
msg = "Truncated sRGB chunk"
|
| 526 |
+
raise ValueError(msg)
|
| 527 |
+
self.im_info["srgb"] = s[0]
|
| 528 |
+
return s
|
| 529 |
+
|
| 530 |
+
def chunk_pHYs(self, pos: int, length: int) -> bytes:
|
| 531 |
+
# pixels per unit
|
| 532 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 533 |
+
if length < 9:
|
| 534 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 535 |
+
return s
|
| 536 |
+
msg = "Truncated pHYs chunk"
|
| 537 |
+
raise ValueError(msg)
|
| 538 |
+
px, py = i32(s, 0), i32(s, 4)
|
| 539 |
+
unit = s[8]
|
| 540 |
+
if unit == 1: # meter
|
| 541 |
+
dpi = px * 0.0254, py * 0.0254
|
| 542 |
+
self.im_info["dpi"] = dpi
|
| 543 |
+
elif unit == 0:
|
| 544 |
+
self.im_info["aspect"] = px, py
|
| 545 |
+
return s
|
| 546 |
+
|
| 547 |
+
def chunk_tEXt(self, pos: int, length: int) -> bytes:
|
| 548 |
+
# text
|
| 549 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 550 |
+
try:
|
| 551 |
+
k, v = s.split(b"\0", 1)
|
| 552 |
+
except ValueError:
|
| 553 |
+
# fallback for broken tEXt tags
|
| 554 |
+
k = s
|
| 555 |
+
v = b""
|
| 556 |
+
if k:
|
| 557 |
+
k = k.decode("latin-1", "strict")
|
| 558 |
+
v_str = v.decode("latin-1", "replace")
|
| 559 |
+
|
| 560 |
+
self.im_info[k] = v if k == "exif" else v_str
|
| 561 |
+
self.im_text[k] = v_str
|
| 562 |
+
self.check_text_memory(len(v_str))
|
| 563 |
+
|
| 564 |
+
return s
|
| 565 |
+
|
| 566 |
+
def chunk_zTXt(self, pos: int, length: int) -> bytes:
|
| 567 |
+
# compressed text
|
| 568 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 569 |
+
try:
|
| 570 |
+
k, v = s.split(b"\0", 1)
|
| 571 |
+
except ValueError:
|
| 572 |
+
k = s
|
| 573 |
+
v = b""
|
| 574 |
+
if v:
|
| 575 |
+
comp_method = v[0]
|
| 576 |
+
else:
|
| 577 |
+
comp_method = 0
|
| 578 |
+
if comp_method != 0:
|
| 579 |
+
msg = f"Unknown compression method {comp_method} in zTXt chunk"
|
| 580 |
+
raise SyntaxError(msg)
|
| 581 |
+
try:
|
| 582 |
+
v = _safe_zlib_decompress(v[1:])
|
| 583 |
+
except ValueError:
|
| 584 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 585 |
+
v = b""
|
| 586 |
+
else:
|
| 587 |
+
raise
|
| 588 |
+
except zlib.error:
|
| 589 |
+
v = b""
|
| 590 |
+
|
| 591 |
+
if k:
|
| 592 |
+
k = k.decode("latin-1", "strict")
|
| 593 |
+
v = v.decode("latin-1", "replace")
|
| 594 |
+
|
| 595 |
+
self.im_info[k] = self.im_text[k] = v
|
| 596 |
+
self.check_text_memory(len(v))
|
| 597 |
+
|
| 598 |
+
return s
|
| 599 |
+
|
| 600 |
+
def chunk_iTXt(self, pos: int, length: int) -> bytes:
|
| 601 |
+
# international text
|
| 602 |
+
r = s = ImageFile._safe_read(self.fp, length)
|
| 603 |
+
try:
|
| 604 |
+
k, r = r.split(b"\0", 1)
|
| 605 |
+
except ValueError:
|
| 606 |
+
return s
|
| 607 |
+
if len(r) < 2:
|
| 608 |
+
return s
|
| 609 |
+
cf, cm, r = r[0], r[1], r[2:]
|
| 610 |
+
try:
|
| 611 |
+
lang, tk, v = r.split(b"\0", 2)
|
| 612 |
+
except ValueError:
|
| 613 |
+
return s
|
| 614 |
+
if cf != 0:
|
| 615 |
+
if cm == 0:
|
| 616 |
+
try:
|
| 617 |
+
v = _safe_zlib_decompress(v)
|
| 618 |
+
except ValueError:
|
| 619 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 620 |
+
return s
|
| 621 |
+
else:
|
| 622 |
+
raise
|
| 623 |
+
except zlib.error:
|
| 624 |
+
return s
|
| 625 |
+
else:
|
| 626 |
+
return s
|
| 627 |
+
if k == b"XML:com.adobe.xmp":
|
| 628 |
+
self.im_info["xmp"] = v
|
| 629 |
+
try:
|
| 630 |
+
k = k.decode("latin-1", "strict")
|
| 631 |
+
lang = lang.decode("utf-8", "strict")
|
| 632 |
+
tk = tk.decode("utf-8", "strict")
|
| 633 |
+
v = v.decode("utf-8", "strict")
|
| 634 |
+
except UnicodeError:
|
| 635 |
+
return s
|
| 636 |
+
|
| 637 |
+
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
|
| 638 |
+
self.check_text_memory(len(v))
|
| 639 |
+
|
| 640 |
+
return s
|
| 641 |
+
|
| 642 |
+
def chunk_eXIf(self, pos: int, length: int) -> bytes:
|
| 643 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 644 |
+
self.im_info["exif"] = b"Exif\x00\x00" + s
|
| 645 |
+
return s
|
| 646 |
+
|
| 647 |
+
# APNG chunks
|
| 648 |
+
def chunk_acTL(self, pos: int, length: int) -> bytes:
|
| 649 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 650 |
+
if length < 8:
|
| 651 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 652 |
+
return s
|
| 653 |
+
msg = "APNG contains truncated acTL chunk"
|
| 654 |
+
raise ValueError(msg)
|
| 655 |
+
if self.im_n_frames is not None:
|
| 656 |
+
self.im_n_frames = None
|
| 657 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 658 |
+
return s
|
| 659 |
+
n_frames = i32(s)
|
| 660 |
+
if n_frames == 0 or n_frames > 0x80000000:
|
| 661 |
+
warnings.warn("Invalid APNG, will use default PNG image if possible")
|
| 662 |
+
return s
|
| 663 |
+
self.im_n_frames = n_frames
|
| 664 |
+
self.im_info["loop"] = i32(s, 4)
|
| 665 |
+
self.im_custom_mimetype = "image/apng"
|
| 666 |
+
return s
|
| 667 |
+
|
| 668 |
+
def chunk_fcTL(self, pos: int, length: int) -> bytes:
|
| 669 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 670 |
+
if length < 26:
|
| 671 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 672 |
+
return s
|
| 673 |
+
msg = "APNG contains truncated fcTL chunk"
|
| 674 |
+
raise ValueError(msg)
|
| 675 |
+
seq = i32(s)
|
| 676 |
+
if (self._seq_num is None and seq != 0) or (
|
| 677 |
+
self._seq_num is not None and self._seq_num != seq - 1
|
| 678 |
+
):
|
| 679 |
+
msg = "APNG contains frame sequence errors"
|
| 680 |
+
raise SyntaxError(msg)
|
| 681 |
+
self._seq_num = seq
|
| 682 |
+
width, height = i32(s, 4), i32(s, 8)
|
| 683 |
+
px, py = i32(s, 12), i32(s, 16)
|
| 684 |
+
im_w, im_h = self.im_size
|
| 685 |
+
if px + width > im_w or py + height > im_h:
|
| 686 |
+
msg = "APNG contains invalid frames"
|
| 687 |
+
raise SyntaxError(msg)
|
| 688 |
+
self.im_info["bbox"] = (px, py, px + width, py + height)
|
| 689 |
+
delay_num, delay_den = i16(s, 20), i16(s, 22)
|
| 690 |
+
if delay_den == 0:
|
| 691 |
+
delay_den = 100
|
| 692 |
+
self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
|
| 693 |
+
self.im_info["disposal"] = s[24]
|
| 694 |
+
self.im_info["blend"] = s[25]
|
| 695 |
+
return s
|
| 696 |
+
|
| 697 |
+
def chunk_fdAT(self, pos: int, length: int) -> bytes:
|
| 698 |
+
if length < 4:
|
| 699 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 700 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 701 |
+
return s
|
| 702 |
+
msg = "APNG contains truncated fDAT chunk"
|
| 703 |
+
raise ValueError(msg)
|
| 704 |
+
s = ImageFile._safe_read(self.fp, 4)
|
| 705 |
+
seq = i32(s)
|
| 706 |
+
if self._seq_num != seq - 1:
|
| 707 |
+
msg = "APNG contains frame sequence errors"
|
| 708 |
+
raise SyntaxError(msg)
|
| 709 |
+
self._seq_num = seq
|
| 710 |
+
return self.chunk_IDAT(pos + 4, length - 4)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
# --------------------------------------------------------------------
|
| 714 |
+
# PNG reader
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def _accept(prefix: bytes) -> bool:
|
| 718 |
+
return prefix[:8] == _MAGIC
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
##
|
| 722 |
+
# Image plugin for PNG images.
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
class PngImageFile(ImageFile.ImageFile):
|
| 726 |
+
format = "PNG"
|
| 727 |
+
format_description = "Portable network graphics"
|
| 728 |
+
|
| 729 |
+
def _open(self) -> None:
|
| 730 |
+
if not _accept(self.fp.read(8)):
|
| 731 |
+
msg = "not a PNG file"
|
| 732 |
+
raise SyntaxError(msg)
|
| 733 |
+
self._fp = self.fp
|
| 734 |
+
self.__frame = 0
|
| 735 |
+
|
| 736 |
+
#
|
| 737 |
+
# Parse headers up to the first IDAT or fDAT chunk
|
| 738 |
+
|
| 739 |
+
self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
|
| 740 |
+
self.png: PngStream | None = PngStream(self.fp)
|
| 741 |
+
|
| 742 |
+
while True:
|
| 743 |
+
#
|
| 744 |
+
# get next chunk
|
| 745 |
+
|
| 746 |
+
cid, pos, length = self.png.read()
|
| 747 |
+
|
| 748 |
+
try:
|
| 749 |
+
s = self.png.call(cid, pos, length)
|
| 750 |
+
except EOFError:
|
| 751 |
+
break
|
| 752 |
+
except AttributeError:
|
| 753 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 754 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 755 |
+
if cid[1:2].islower():
|
| 756 |
+
self.private_chunks.append((cid, s))
|
| 757 |
+
|
| 758 |
+
self.png.crc(cid, s)
|
| 759 |
+
|
| 760 |
+
#
|
| 761 |
+
# Copy relevant attributes from the PngStream. An alternative
|
| 762 |
+
# would be to let the PngStream class modify these attributes
|
| 763 |
+
# directly, but that introduces circular references which are
|
| 764 |
+
# difficult to break if things go wrong in the decoder...
|
| 765 |
+
# (believe me, I've tried ;-)
|
| 766 |
+
|
| 767 |
+
self._mode = self.png.im_mode
|
| 768 |
+
self._size = self.png.im_size
|
| 769 |
+
self.info = self.png.im_info
|
| 770 |
+
self._text = None
|
| 771 |
+
self.tile = self.png.im_tile
|
| 772 |
+
self.custom_mimetype = self.png.im_custom_mimetype
|
| 773 |
+
self.n_frames = self.png.im_n_frames or 1
|
| 774 |
+
self.default_image = self.info.get("default_image", False)
|
| 775 |
+
|
| 776 |
+
if self.png.im_palette:
|
| 777 |
+
rawmode, data = self.png.im_palette
|
| 778 |
+
self.palette = ImagePalette.raw(rawmode, data)
|
| 779 |
+
|
| 780 |
+
if cid == b"fdAT":
|
| 781 |
+
self.__prepare_idat = length - 4
|
| 782 |
+
else:
|
| 783 |
+
self.__prepare_idat = length # used by load_prepare()
|
| 784 |
+
|
| 785 |
+
if self.png.im_n_frames is not None:
|
| 786 |
+
self._close_exclusive_fp_after_loading = False
|
| 787 |
+
self.png.save_rewind()
|
| 788 |
+
self.__rewind_idat = self.__prepare_idat
|
| 789 |
+
self.__rewind = self._fp.tell()
|
| 790 |
+
if self.default_image:
|
| 791 |
+
# IDAT chunk contains default image and not first animation frame
|
| 792 |
+
self.n_frames += 1
|
| 793 |
+
self._seek(0)
|
| 794 |
+
self.is_animated = self.n_frames > 1
|
| 795 |
+
|
| 796 |
+
@property
|
| 797 |
+
def text(self):
|
| 798 |
+
# experimental
|
| 799 |
+
if self._text is None:
|
| 800 |
+
# iTxt, tEXt and zTXt chunks may appear at the end of the file
|
| 801 |
+
# So load the file to ensure that they are read
|
| 802 |
+
if self.is_animated:
|
| 803 |
+
frame = self.__frame
|
| 804 |
+
# for APNG, seek to the final frame before loading
|
| 805 |
+
self.seek(self.n_frames - 1)
|
| 806 |
+
self.load()
|
| 807 |
+
if self.is_animated:
|
| 808 |
+
self.seek(frame)
|
| 809 |
+
return self._text
|
| 810 |
+
|
| 811 |
+
def verify(self) -> None:
|
| 812 |
+
"""Verify PNG file"""
|
| 813 |
+
|
| 814 |
+
if self.fp is None:
|
| 815 |
+
msg = "verify must be called directly after open"
|
| 816 |
+
raise RuntimeError(msg)
|
| 817 |
+
|
| 818 |
+
# back up to beginning of IDAT block
|
| 819 |
+
self.fp.seek(self.tile[0][2] - 8)
|
| 820 |
+
|
| 821 |
+
assert self.png is not None
|
| 822 |
+
self.png.verify()
|
| 823 |
+
self.png.close()
|
| 824 |
+
|
| 825 |
+
if self._exclusive_fp:
|
| 826 |
+
self.fp.close()
|
| 827 |
+
self.fp = None
|
| 828 |
+
|
| 829 |
+
def seek(self, frame: int) -> None:
|
| 830 |
+
if not self._seek_check(frame):
|
| 831 |
+
return
|
| 832 |
+
if frame < self.__frame:
|
| 833 |
+
self._seek(0, True)
|
| 834 |
+
|
| 835 |
+
last_frame = self.__frame
|
| 836 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 837 |
+
try:
|
| 838 |
+
self._seek(f)
|
| 839 |
+
except EOFError as e:
|
| 840 |
+
self.seek(last_frame)
|
| 841 |
+
msg = "no more images in APNG file"
|
| 842 |
+
raise EOFError(msg) from e
|
| 843 |
+
|
| 844 |
+
def _seek(self, frame: int, rewind: bool = False) -> None:
|
| 845 |
+
assert self.png is not None
|
| 846 |
+
|
| 847 |
+
self.dispose: _imaging.ImagingCore | None
|
| 848 |
+
if frame == 0:
|
| 849 |
+
if rewind:
|
| 850 |
+
self._fp.seek(self.__rewind)
|
| 851 |
+
self.png.rewind()
|
| 852 |
+
self.__prepare_idat = self.__rewind_idat
|
| 853 |
+
self.im = None
|
| 854 |
+
if self.pyaccess:
|
| 855 |
+
self.pyaccess = None
|
| 856 |
+
self.info = self.png.im_info
|
| 857 |
+
self.tile = self.png.im_tile
|
| 858 |
+
self.fp = self._fp
|
| 859 |
+
self._prev_im = None
|
| 860 |
+
self.dispose = None
|
| 861 |
+
self.default_image = self.info.get("default_image", False)
|
| 862 |
+
self.dispose_op = self.info.get("disposal")
|
| 863 |
+
self.blend_op = self.info.get("blend")
|
| 864 |
+
self.dispose_extent = self.info.get("bbox")
|
| 865 |
+
self.__frame = 0
|
| 866 |
+
else:
|
| 867 |
+
if frame != self.__frame + 1:
|
| 868 |
+
msg = f"cannot seek to frame {frame}"
|
| 869 |
+
raise ValueError(msg)
|
| 870 |
+
|
| 871 |
+
# ensure previous frame was loaded
|
| 872 |
+
self.load()
|
| 873 |
+
|
| 874 |
+
if self.dispose:
|
| 875 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
| 876 |
+
self._prev_im = self.im.copy()
|
| 877 |
+
|
| 878 |
+
self.fp = self._fp
|
| 879 |
+
|
| 880 |
+
# advance to the next frame
|
| 881 |
+
if self.__prepare_idat:
|
| 882 |
+
ImageFile._safe_read(self.fp, self.__prepare_idat)
|
| 883 |
+
self.__prepare_idat = 0
|
| 884 |
+
frame_start = False
|
| 885 |
+
while True:
|
| 886 |
+
self.fp.read(4) # CRC
|
| 887 |
+
|
| 888 |
+
try:
|
| 889 |
+
cid, pos, length = self.png.read()
|
| 890 |
+
except (struct.error, SyntaxError):
|
| 891 |
+
break
|
| 892 |
+
|
| 893 |
+
if cid == b"IEND":
|
| 894 |
+
msg = "No more images in APNG file"
|
| 895 |
+
raise EOFError(msg)
|
| 896 |
+
if cid == b"fcTL":
|
| 897 |
+
if frame_start:
|
| 898 |
+
# there must be at least one fdAT chunk between fcTL chunks
|
| 899 |
+
msg = "APNG missing frame data"
|
| 900 |
+
raise SyntaxError(msg)
|
| 901 |
+
frame_start = True
|
| 902 |
+
|
| 903 |
+
try:
|
| 904 |
+
self.png.call(cid, pos, length)
|
| 905 |
+
except UnicodeDecodeError:
|
| 906 |
+
break
|
| 907 |
+
except EOFError:
|
| 908 |
+
if cid == b"fdAT":
|
| 909 |
+
length -= 4
|
| 910 |
+
if frame_start:
|
| 911 |
+
self.__prepare_idat = length
|
| 912 |
+
break
|
| 913 |
+
ImageFile._safe_read(self.fp, length)
|
| 914 |
+
except AttributeError:
|
| 915 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 916 |
+
ImageFile._safe_read(self.fp, length)
|
| 917 |
+
|
| 918 |
+
self.__frame = frame
|
| 919 |
+
self.tile = self.png.im_tile
|
| 920 |
+
self.dispose_op = self.info.get("disposal")
|
| 921 |
+
self.blend_op = self.info.get("blend")
|
| 922 |
+
self.dispose_extent = self.info.get("bbox")
|
| 923 |
+
|
| 924 |
+
if not self.tile:
|
| 925 |
+
msg = "image not found in APNG frame"
|
| 926 |
+
raise EOFError(msg)
|
| 927 |
+
|
| 928 |
+
# setup frame disposal (actual disposal done when needed in the next _seek())
|
| 929 |
+
if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
|
| 930 |
+
self.dispose_op = Disposal.OP_BACKGROUND
|
| 931 |
+
|
| 932 |
+
self.dispose = None
|
| 933 |
+
if self.dispose_op == Disposal.OP_PREVIOUS:
|
| 934 |
+
if self._prev_im:
|
| 935 |
+
self.dispose = self._prev_im.copy()
|
| 936 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 937 |
+
elif self.dispose_op == Disposal.OP_BACKGROUND:
|
| 938 |
+
self.dispose = Image.core.fill(self.mode, self.size)
|
| 939 |
+
self.dispose = self._crop(self.dispose, self.dispose_extent)
|
| 940 |
+
|
| 941 |
+
def tell(self) -> int:
|
| 942 |
+
return self.__frame
|
| 943 |
+
|
| 944 |
+
def load_prepare(self) -> None:
|
| 945 |
+
"""internal: prepare to read PNG file"""
|
| 946 |
+
|
| 947 |
+
if self.info.get("interlace"):
|
| 948 |
+
self.decoderconfig = self.decoderconfig + (1,)
|
| 949 |
+
|
| 950 |
+
self.__idat = self.__prepare_idat # used by load_read()
|
| 951 |
+
ImageFile.ImageFile.load_prepare(self)
|
| 952 |
+
|
| 953 |
+
def load_read(self, read_bytes: int) -> bytes:
|
| 954 |
+
"""internal: read more image data"""
|
| 955 |
+
|
| 956 |
+
assert self.png is not None
|
| 957 |
+
while self.__idat == 0:
|
| 958 |
+
# end of chunk, skip forward to next one
|
| 959 |
+
|
| 960 |
+
self.fp.read(4) # CRC
|
| 961 |
+
|
| 962 |
+
cid, pos, length = self.png.read()
|
| 963 |
+
|
| 964 |
+
if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
|
| 965 |
+
self.png.push(cid, pos, length)
|
| 966 |
+
return b""
|
| 967 |
+
|
| 968 |
+
if cid == b"fdAT":
|
| 969 |
+
try:
|
| 970 |
+
self.png.call(cid, pos, length)
|
| 971 |
+
except EOFError:
|
| 972 |
+
pass
|
| 973 |
+
self.__idat = length - 4 # sequence_num has already been read
|
| 974 |
+
else:
|
| 975 |
+
self.__idat = length # empty chunks are allowed
|
| 976 |
+
|
| 977 |
+
# read more data from this chunk
|
| 978 |
+
if read_bytes <= 0:
|
| 979 |
+
read_bytes = self.__idat
|
| 980 |
+
else:
|
| 981 |
+
read_bytes = min(read_bytes, self.__idat)
|
| 982 |
+
|
| 983 |
+
self.__idat = self.__idat - read_bytes
|
| 984 |
+
|
| 985 |
+
return self.fp.read(read_bytes)
|
| 986 |
+
|
| 987 |
+
def load_end(self) -> None:
|
| 988 |
+
"""internal: finished reading image data"""
|
| 989 |
+
assert self.png is not None
|
| 990 |
+
if self.__idat != 0:
|
| 991 |
+
self.fp.read(self.__idat)
|
| 992 |
+
while True:
|
| 993 |
+
self.fp.read(4) # CRC
|
| 994 |
+
|
| 995 |
+
try:
|
| 996 |
+
cid, pos, length = self.png.read()
|
| 997 |
+
except (struct.error, SyntaxError):
|
| 998 |
+
break
|
| 999 |
+
|
| 1000 |
+
if cid == b"IEND":
|
| 1001 |
+
break
|
| 1002 |
+
elif cid == b"fcTL" and self.is_animated:
|
| 1003 |
+
# start of the next frame, stop reading
|
| 1004 |
+
self.__prepare_idat = 0
|
| 1005 |
+
self.png.push(cid, pos, length)
|
| 1006 |
+
break
|
| 1007 |
+
|
| 1008 |
+
try:
|
| 1009 |
+
self.png.call(cid, pos, length)
|
| 1010 |
+
except UnicodeDecodeError:
|
| 1011 |
+
break
|
| 1012 |
+
except EOFError:
|
| 1013 |
+
if cid == b"fdAT":
|
| 1014 |
+
length -= 4
|
| 1015 |
+
try:
|
| 1016 |
+
ImageFile._safe_read(self.fp, length)
|
| 1017 |
+
except OSError as e:
|
| 1018 |
+
if ImageFile.LOAD_TRUNCATED_IMAGES:
|
| 1019 |
+
break
|
| 1020 |
+
else:
|
| 1021 |
+
raise e
|
| 1022 |
+
except AttributeError:
|
| 1023 |
+
logger.debug("%r %s %s (unknown)", cid, pos, length)
|
| 1024 |
+
s = ImageFile._safe_read(self.fp, length)
|
| 1025 |
+
if cid[1:2].islower():
|
| 1026 |
+
self.private_chunks.append((cid, s, True))
|
| 1027 |
+
self._text = self.png.im_text
|
| 1028 |
+
if not self.is_animated:
|
| 1029 |
+
self.png.close()
|
| 1030 |
+
self.png = None
|
| 1031 |
+
else:
|
| 1032 |
+
if self._prev_im and self.blend_op == Blend.OP_OVER:
|
| 1033 |
+
updated = self._crop(self.im, self.dispose_extent)
|
| 1034 |
+
if self.im.mode == "RGB" and "transparency" in self.info:
|
| 1035 |
+
mask = updated.convert_transparent(
|
| 1036 |
+
"RGBA", self.info["transparency"]
|
| 1037 |
+
)
|
| 1038 |
+
else:
|
| 1039 |
+
mask = updated.convert("RGBA")
|
| 1040 |
+
self._prev_im.paste(updated, self.dispose_extent, mask)
|
| 1041 |
+
self.im = self._prev_im
|
| 1042 |
+
if self.pyaccess:
|
| 1043 |
+
self.pyaccess = None
|
| 1044 |
+
|
| 1045 |
+
def _getexif(self) -> dict[str, Any] | None:
|
| 1046 |
+
if "exif" not in self.info:
|
| 1047 |
+
self.load()
|
| 1048 |
+
if "exif" not in self.info and "Raw profile type exif" not in self.info:
|
| 1049 |
+
return None
|
| 1050 |
+
return self.getexif()._get_merged_dict()
|
| 1051 |
+
|
| 1052 |
+
def getexif(self) -> Image.Exif:
|
| 1053 |
+
if "exif" not in self.info:
|
| 1054 |
+
self.load()
|
| 1055 |
+
|
| 1056 |
+
return super().getexif()
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
# --------------------------------------------------------------------
|
| 1060 |
+
# PNG writer
|
| 1061 |
+
|
| 1062 |
+
_OUTMODES = {
|
| 1063 |
+
# supported PIL modes, and corresponding rawmode, bit depth and color type
|
| 1064 |
+
"1": ("1", b"\x01", b"\x00"),
|
| 1065 |
+
"L;1": ("L;1", b"\x01", b"\x00"),
|
| 1066 |
+
"L;2": ("L;2", b"\x02", b"\x00"),
|
| 1067 |
+
"L;4": ("L;4", b"\x04", b"\x00"),
|
| 1068 |
+
"L": ("L", b"\x08", b"\x00"),
|
| 1069 |
+
"LA": ("LA", b"\x08", b"\x04"),
|
| 1070 |
+
"I": ("I;16B", b"\x10", b"\x00"),
|
| 1071 |
+
"I;16": ("I;16B", b"\x10", b"\x00"),
|
| 1072 |
+
"I;16B": ("I;16B", b"\x10", b"\x00"),
|
| 1073 |
+
"P;1": ("P;1", b"\x01", b"\x03"),
|
| 1074 |
+
"P;2": ("P;2", b"\x02", b"\x03"),
|
| 1075 |
+
"P;4": ("P;4", b"\x04", b"\x03"),
|
| 1076 |
+
"P": ("P", b"\x08", b"\x03"),
|
| 1077 |
+
"RGB": ("RGB", b"\x08", b"\x02"),
|
| 1078 |
+
"RGBA": ("RGBA", b"\x08", b"\x06"),
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
def putchunk(fp, cid, *data):
|
| 1083 |
+
"""Write a PNG chunk (including CRC field)"""
|
| 1084 |
+
|
| 1085 |
+
data = b"".join(data)
|
| 1086 |
+
|
| 1087 |
+
fp.write(o32(len(data)) + cid)
|
| 1088 |
+
fp.write(data)
|
| 1089 |
+
crc = _crc32(data, _crc32(cid))
|
| 1090 |
+
fp.write(o32(crc))
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
class _idat:
|
| 1094 |
+
# wrap output from the encoder in IDAT chunks
|
| 1095 |
+
|
| 1096 |
+
def __init__(self, fp, chunk):
|
| 1097 |
+
self.fp = fp
|
| 1098 |
+
self.chunk = chunk
|
| 1099 |
+
|
| 1100 |
+
def write(self, data: bytes) -> None:
|
| 1101 |
+
self.chunk(self.fp, b"IDAT", data)
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
class _fdat:
|
| 1105 |
+
# wrap encoder output in fdAT chunks
|
| 1106 |
+
|
| 1107 |
+
def __init__(self, fp, chunk, seq_num):
|
| 1108 |
+
self.fp = fp
|
| 1109 |
+
self.chunk = chunk
|
| 1110 |
+
self.seq_num = seq_num
|
| 1111 |
+
|
| 1112 |
+
def write(self, data: bytes) -> None:
|
| 1113 |
+
self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
|
| 1114 |
+
self.seq_num += 1
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def _write_multiple_frames(im, fp, chunk, mode, rawmode, default_image, append_images):
|
| 1118 |
+
duration = im.encoderinfo.get("duration")
|
| 1119 |
+
loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
|
| 1120 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
|
| 1121 |
+
blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
|
| 1122 |
+
|
| 1123 |
+
if default_image:
|
| 1124 |
+
chain = itertools.chain(append_images)
|
| 1125 |
+
else:
|
| 1126 |
+
chain = itertools.chain([im], append_images)
|
| 1127 |
+
|
| 1128 |
+
im_frames = []
|
| 1129 |
+
frame_count = 0
|
| 1130 |
+
for im_seq in chain:
|
| 1131 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1132 |
+
if im_frame.mode == mode:
|
| 1133 |
+
im_frame = im_frame.copy()
|
| 1134 |
+
else:
|
| 1135 |
+
im_frame = im_frame.convert(mode)
|
| 1136 |
+
encoderinfo = im.encoderinfo.copy()
|
| 1137 |
+
if isinstance(duration, (list, tuple)):
|
| 1138 |
+
encoderinfo["duration"] = duration[frame_count]
|
| 1139 |
+
elif duration is None and "duration" in im_frame.info:
|
| 1140 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
| 1141 |
+
if isinstance(disposal, (list, tuple)):
|
| 1142 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
| 1143 |
+
if isinstance(blend, (list, tuple)):
|
| 1144 |
+
encoderinfo["blend"] = blend[frame_count]
|
| 1145 |
+
frame_count += 1
|
| 1146 |
+
|
| 1147 |
+
if im_frames:
|
| 1148 |
+
previous = im_frames[-1]
|
| 1149 |
+
prev_disposal = previous["encoderinfo"].get("disposal")
|
| 1150 |
+
prev_blend = previous["encoderinfo"].get("blend")
|
| 1151 |
+
if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
|
| 1152 |
+
prev_disposal = Disposal.OP_BACKGROUND
|
| 1153 |
+
|
| 1154 |
+
if prev_disposal == Disposal.OP_BACKGROUND:
|
| 1155 |
+
base_im = previous["im"].copy()
|
| 1156 |
+
dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
|
| 1157 |
+
bbox = previous["bbox"]
|
| 1158 |
+
if bbox:
|
| 1159 |
+
dispose = dispose.crop(bbox)
|
| 1160 |
+
else:
|
| 1161 |
+
bbox = (0, 0) + im.size
|
| 1162 |
+
base_im.paste(dispose, bbox)
|
| 1163 |
+
elif prev_disposal == Disposal.OP_PREVIOUS:
|
| 1164 |
+
base_im = im_frames[-2]["im"]
|
| 1165 |
+
else:
|
| 1166 |
+
base_im = previous["im"]
|
| 1167 |
+
delta = ImageChops.subtract_modulo(
|
| 1168 |
+
im_frame.convert("RGBA"), base_im.convert("RGBA")
|
| 1169 |
+
)
|
| 1170 |
+
bbox = delta.getbbox(alpha_only=False)
|
| 1171 |
+
if (
|
| 1172 |
+
not bbox
|
| 1173 |
+
and prev_disposal == encoderinfo.get("disposal")
|
| 1174 |
+
and prev_blend == encoderinfo.get("blend")
|
| 1175 |
+
and "duration" in encoderinfo
|
| 1176 |
+
):
|
| 1177 |
+
previous["encoderinfo"]["duration"] += encoderinfo["duration"]
|
| 1178 |
+
continue
|
| 1179 |
+
else:
|
| 1180 |
+
bbox = None
|
| 1181 |
+
im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})
|
| 1182 |
+
|
| 1183 |
+
if len(im_frames) == 1 and not default_image:
|
| 1184 |
+
return im_frames[0]["im"]
|
| 1185 |
+
|
| 1186 |
+
# animation control
|
| 1187 |
+
chunk(
|
| 1188 |
+
fp,
|
| 1189 |
+
b"acTL",
|
| 1190 |
+
o32(len(im_frames)), # 0: num_frames
|
| 1191 |
+
o32(loop), # 4: num_plays
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
# default image IDAT (if it exists)
|
| 1195 |
+
if default_image:
|
| 1196 |
+
if im.mode != mode:
|
| 1197 |
+
im = im.convert(mode)
|
| 1198 |
+
ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])
|
| 1199 |
+
|
| 1200 |
+
seq_num = 0
|
| 1201 |
+
for frame, frame_data in enumerate(im_frames):
|
| 1202 |
+
im_frame = frame_data["im"]
|
| 1203 |
+
if not frame_data["bbox"]:
|
| 1204 |
+
bbox = (0, 0) + im_frame.size
|
| 1205 |
+
else:
|
| 1206 |
+
bbox = frame_data["bbox"]
|
| 1207 |
+
im_frame = im_frame.crop(bbox)
|
| 1208 |
+
size = im_frame.size
|
| 1209 |
+
encoderinfo = frame_data["encoderinfo"]
|
| 1210 |
+
frame_duration = int(round(encoderinfo.get("duration", 0)))
|
| 1211 |
+
frame_disposal = encoderinfo.get("disposal", disposal)
|
| 1212 |
+
frame_blend = encoderinfo.get("blend", blend)
|
| 1213 |
+
# frame control
|
| 1214 |
+
chunk(
|
| 1215 |
+
fp,
|
| 1216 |
+
b"fcTL",
|
| 1217 |
+
o32(seq_num), # sequence_number
|
| 1218 |
+
o32(size[0]), # width
|
| 1219 |
+
o32(size[1]), # height
|
| 1220 |
+
o32(bbox[0]), # x_offset
|
| 1221 |
+
o32(bbox[1]), # y_offset
|
| 1222 |
+
o16(frame_duration), # delay_numerator
|
| 1223 |
+
o16(1000), # delay_denominator
|
| 1224 |
+
o8(frame_disposal), # dispose_op
|
| 1225 |
+
o8(frame_blend), # blend_op
|
| 1226 |
+
)
|
| 1227 |
+
seq_num += 1
|
| 1228 |
+
# frame data
|
| 1229 |
+
if frame == 0 and not default_image:
|
| 1230 |
+
# first frame must be in IDAT chunks for backwards compatibility
|
| 1231 |
+
ImageFile._save(
|
| 1232 |
+
im_frame,
|
| 1233 |
+
_idat(fp, chunk),
|
| 1234 |
+
[("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1235 |
+
)
|
| 1236 |
+
else:
|
| 1237 |
+
fdat_chunks = _fdat(fp, chunk, seq_num)
|
| 1238 |
+
ImageFile._save(
|
| 1239 |
+
im_frame,
|
| 1240 |
+
fdat_chunks,
|
| 1241 |
+
[("zip", (0, 0) + im_frame.size, 0, rawmode)],
|
| 1242 |
+
)
|
| 1243 |
+
seq_num = fdat_chunks.seq_num
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 1247 |
+
_save(im, fp, filename, save_all=True)
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
def _save(im, fp, filename, chunk=putchunk, save_all=False):
|
| 1251 |
+
# save an image to disk (called by the save method)
|
| 1252 |
+
|
| 1253 |
+
if save_all:
|
| 1254 |
+
default_image = im.encoderinfo.get(
|
| 1255 |
+
"default_image", im.info.get("default_image")
|
| 1256 |
+
)
|
| 1257 |
+
modes = set()
|
| 1258 |
+
sizes = set()
|
| 1259 |
+
append_images = im.encoderinfo.get("append_images", [])
|
| 1260 |
+
for im_seq in itertools.chain([im], append_images):
|
| 1261 |
+
for im_frame in ImageSequence.Iterator(im_seq):
|
| 1262 |
+
modes.add(im_frame.mode)
|
| 1263 |
+
sizes.add(im_frame.size)
|
| 1264 |
+
for mode in ("RGBA", "RGB", "P"):
|
| 1265 |
+
if mode in modes:
|
| 1266 |
+
break
|
| 1267 |
+
else:
|
| 1268 |
+
mode = modes.pop()
|
| 1269 |
+
size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
|
| 1270 |
+
else:
|
| 1271 |
+
size = im.size
|
| 1272 |
+
mode = im.mode
|
| 1273 |
+
|
| 1274 |
+
outmode = mode
|
| 1275 |
+
if mode == "P":
|
| 1276 |
+
#
|
| 1277 |
+
# attempt to minimize storage requirements for palette images
|
| 1278 |
+
if "bits" in im.encoderinfo:
|
| 1279 |
+
# number of bits specified by user
|
| 1280 |
+
colors = min(1 << im.encoderinfo["bits"], 256)
|
| 1281 |
+
else:
|
| 1282 |
+
# check palette contents
|
| 1283 |
+
if im.palette:
|
| 1284 |
+
colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
|
| 1285 |
+
else:
|
| 1286 |
+
colors = 256
|
| 1287 |
+
|
| 1288 |
+
if colors <= 16:
|
| 1289 |
+
if colors <= 2:
|
| 1290 |
+
bits = 1
|
| 1291 |
+
elif colors <= 4:
|
| 1292 |
+
bits = 2
|
| 1293 |
+
else:
|
| 1294 |
+
bits = 4
|
| 1295 |
+
outmode += f";{bits}"
|
| 1296 |
+
|
| 1297 |
+
# encoder options
|
| 1298 |
+
im.encoderconfig = (
|
| 1299 |
+
im.encoderinfo.get("optimize", False),
|
| 1300 |
+
im.encoderinfo.get("compress_level", -1),
|
| 1301 |
+
im.encoderinfo.get("compress_type", -1),
|
| 1302 |
+
im.encoderinfo.get("dictionary", b""),
|
| 1303 |
+
)
|
| 1304 |
+
|
| 1305 |
+
# get the corresponding PNG mode
|
| 1306 |
+
try:
|
| 1307 |
+
rawmode, bit_depth, color_type = _OUTMODES[outmode]
|
| 1308 |
+
except KeyError as e:
|
| 1309 |
+
msg = f"cannot write mode {mode} as PNG"
|
| 1310 |
+
raise OSError(msg) from e
|
| 1311 |
+
|
| 1312 |
+
#
|
| 1313 |
+
# write minimal PNG file
|
| 1314 |
+
|
| 1315 |
+
fp.write(_MAGIC)
|
| 1316 |
+
|
| 1317 |
+
chunk(
|
| 1318 |
+
fp,
|
| 1319 |
+
b"IHDR",
|
| 1320 |
+
o32(size[0]), # 0: size
|
| 1321 |
+
o32(size[1]),
|
| 1322 |
+
bit_depth,
|
| 1323 |
+
color_type,
|
| 1324 |
+
b"\0", # 10: compression
|
| 1325 |
+
b"\0", # 11: filter category
|
| 1326 |
+
b"\0", # 12: interlace flag
|
| 1327 |
+
)
|
| 1328 |
+
|
| 1329 |
+
chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
|
| 1330 |
+
|
| 1331 |
+
icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1332 |
+
if icc:
|
| 1333 |
+
# ICC profile
|
| 1334 |
+
# according to PNG spec, the iCCP chunk contains:
|
| 1335 |
+
# Profile name 1-79 bytes (character string)
|
| 1336 |
+
# Null separator 1 byte (null character)
|
| 1337 |
+
# Compression method 1 byte (0)
|
| 1338 |
+
# Compressed profile n bytes (zlib with deflate compression)
|
| 1339 |
+
name = b"ICC Profile"
|
| 1340 |
+
data = name + b"\0\0" + zlib.compress(icc)
|
| 1341 |
+
chunk(fp, b"iCCP", data)
|
| 1342 |
+
|
| 1343 |
+
# You must either have sRGB or iCCP.
|
| 1344 |
+
# Disallow sRGB chunks when an iCCP-chunk has been emitted.
|
| 1345 |
+
chunks.remove(b"sRGB")
|
| 1346 |
+
|
| 1347 |
+
info = im.encoderinfo.get("pnginfo")
|
| 1348 |
+
if info:
|
| 1349 |
+
chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
|
| 1350 |
+
for info_chunk in info.chunks:
|
| 1351 |
+
cid, data = info_chunk[:2]
|
| 1352 |
+
if cid in chunks:
|
| 1353 |
+
chunks.remove(cid)
|
| 1354 |
+
chunk(fp, cid, data)
|
| 1355 |
+
elif cid in chunks_multiple_allowed:
|
| 1356 |
+
chunk(fp, cid, data)
|
| 1357 |
+
elif cid[1:2].islower():
|
| 1358 |
+
# Private chunk
|
| 1359 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1360 |
+
if not after_idat:
|
| 1361 |
+
chunk(fp, cid, data)
|
| 1362 |
+
|
| 1363 |
+
if im.mode == "P":
|
| 1364 |
+
palette_byte_number = colors * 3
|
| 1365 |
+
palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
|
| 1366 |
+
while len(palette_bytes) < palette_byte_number:
|
| 1367 |
+
palette_bytes += b"\0"
|
| 1368 |
+
chunk(fp, b"PLTE", palette_bytes)
|
| 1369 |
+
|
| 1370 |
+
transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
|
| 1371 |
+
|
| 1372 |
+
if transparency or transparency == 0:
|
| 1373 |
+
if im.mode == "P":
|
| 1374 |
+
# limit to actual palette size
|
| 1375 |
+
alpha_bytes = colors
|
| 1376 |
+
if isinstance(transparency, bytes):
|
| 1377 |
+
chunk(fp, b"tRNS", transparency[:alpha_bytes])
|
| 1378 |
+
else:
|
| 1379 |
+
transparency = max(0, min(255, transparency))
|
| 1380 |
+
alpha = b"\xFF" * transparency + b"\0"
|
| 1381 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1382 |
+
elif im.mode in ("1", "L", "I", "I;16"):
|
| 1383 |
+
transparency = max(0, min(65535, transparency))
|
| 1384 |
+
chunk(fp, b"tRNS", o16(transparency))
|
| 1385 |
+
elif im.mode == "RGB":
|
| 1386 |
+
red, green, blue = transparency
|
| 1387 |
+
chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
|
| 1388 |
+
else:
|
| 1389 |
+
if "transparency" in im.encoderinfo:
|
| 1390 |
+
# don't bother with transparency if it's an RGBA
|
| 1391 |
+
# and it's in the info dict. It's probably just stale.
|
| 1392 |
+
msg = "cannot use transparency for this mode"
|
| 1393 |
+
raise OSError(msg)
|
| 1394 |
+
else:
|
| 1395 |
+
if im.mode == "P" and im.im.getpalettemode() == "RGBA":
|
| 1396 |
+
alpha = im.im.getpalette("RGBA", "A")
|
| 1397 |
+
alpha_bytes = colors
|
| 1398 |
+
chunk(fp, b"tRNS", alpha[:alpha_bytes])
|
| 1399 |
+
|
| 1400 |
+
dpi = im.encoderinfo.get("dpi")
|
| 1401 |
+
if dpi:
|
| 1402 |
+
chunk(
|
| 1403 |
+
fp,
|
| 1404 |
+
b"pHYs",
|
| 1405 |
+
o32(int(dpi[0] / 0.0254 + 0.5)),
|
| 1406 |
+
o32(int(dpi[1] / 0.0254 + 0.5)),
|
| 1407 |
+
b"\x01",
|
| 1408 |
+
)
|
| 1409 |
+
|
| 1410 |
+
if info:
|
| 1411 |
+
chunks = [b"bKGD", b"hIST"]
|
| 1412 |
+
for info_chunk in info.chunks:
|
| 1413 |
+
cid, data = info_chunk[:2]
|
| 1414 |
+
if cid in chunks:
|
| 1415 |
+
chunks.remove(cid)
|
| 1416 |
+
chunk(fp, cid, data)
|
| 1417 |
+
|
| 1418 |
+
exif = im.encoderinfo.get("exif")
|
| 1419 |
+
if exif:
|
| 1420 |
+
if isinstance(exif, Image.Exif):
|
| 1421 |
+
exif = exif.tobytes(8)
|
| 1422 |
+
if exif.startswith(b"Exif\x00\x00"):
|
| 1423 |
+
exif = exif[6:]
|
| 1424 |
+
chunk(fp, b"eXIf", exif)
|
| 1425 |
+
|
| 1426 |
+
if save_all:
|
| 1427 |
+
im = _write_multiple_frames(
|
| 1428 |
+
im, fp, chunk, mode, rawmode, default_image, append_images
|
| 1429 |
+
)
|
| 1430 |
+
if im:
|
| 1431 |
+
ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])
|
| 1432 |
+
|
| 1433 |
+
if info:
|
| 1434 |
+
for info_chunk in info.chunks:
|
| 1435 |
+
cid, data = info_chunk[:2]
|
| 1436 |
+
if cid[1:2].islower():
|
| 1437 |
+
# Private chunk
|
| 1438 |
+
after_idat = len(info_chunk) == 3 and info_chunk[2]
|
| 1439 |
+
if after_idat:
|
| 1440 |
+
chunk(fp, cid, data)
|
| 1441 |
+
|
| 1442 |
+
chunk(fp, b"IEND", b"")
|
| 1443 |
+
|
| 1444 |
+
if hasattr(fp, "flush"):
|
| 1445 |
+
fp.flush()
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
# --------------------------------------------------------------------
|
| 1449 |
+
# PNG chunk converter
|
| 1450 |
+
|
| 1451 |
+
|
| 1452 |
+
def getchunks(im, **params):
|
| 1453 |
+
"""Return a list of PNG chunks representing this image."""
|
| 1454 |
+
|
| 1455 |
+
class collector:
|
| 1456 |
+
data = []
|
| 1457 |
+
|
| 1458 |
+
def write(self, data: bytes) -> None:
|
| 1459 |
+
pass
|
| 1460 |
+
|
| 1461 |
+
def append(self, chunk: bytes) -> None:
|
| 1462 |
+
self.data.append(chunk)
|
| 1463 |
+
|
| 1464 |
+
def append(fp, cid, *data):
|
| 1465 |
+
data = b"".join(data)
|
| 1466 |
+
crc = o32(_crc32(data, _crc32(cid)))
|
| 1467 |
+
fp.append((cid, data, crc))
|
| 1468 |
+
|
| 1469 |
+
fp = collector()
|
| 1470 |
+
|
| 1471 |
+
try:
|
| 1472 |
+
im.encoderinfo = params
|
| 1473 |
+
_save(im, fp, None, append)
|
| 1474 |
+
finally:
|
| 1475 |
+
del im.encoderinfo
|
| 1476 |
+
|
| 1477 |
+
return fp.data
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
# --------------------------------------------------------------------
|
| 1481 |
+
# Registry
|
| 1482 |
+
|
| 1483 |
+
Image.register_open(PngImageFile.format, PngImageFile, _accept)
|
| 1484 |
+
Image.register_save(PngImageFile.format, _save)
|
| 1485 |
+
Image.register_save_all(PngImageFile.format, _save_all)
|
| 1486 |
+
|
| 1487 |
+
Image.register_extensions(P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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 |
+
|
| 23 |
+
from . import Image, ImageFile, ImagePalette
|
| 24 |
+
from ._binary import i8
|
| 25 |
+
from ._binary import i16be as i16
|
| 26 |
+
from ._binary import i32be as i32
|
| 27 |
+
from ._binary import si16be as si16
|
| 28 |
+
from ._binary import si32be as si32
|
| 29 |
+
|
| 30 |
+
MODES = {
|
| 31 |
+
# (photoshop mode, bits) -> (pil mode, required channels)
|
| 32 |
+
(0, 1): ("1", 1),
|
| 33 |
+
(0, 8): ("L", 1),
|
| 34 |
+
(1, 8): ("L", 1),
|
| 35 |
+
(2, 8): ("P", 1),
|
| 36 |
+
(3, 8): ("RGB", 3),
|
| 37 |
+
(4, 8): ("CMYK", 4),
|
| 38 |
+
(7, 8): ("L", 1), # FIXME: multilayer
|
| 39 |
+
(8, 8): ("L", 1), # duotone
|
| 40 |
+
(9, 8): ("LAB", 3),
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------------.
|
| 45 |
+
# read PSD images
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _accept(prefix: bytes) -> bool:
|
| 49 |
+
return prefix[:4] == b"8BPS"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
##
|
| 53 |
+
# Image plugin for Photoshop images.
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class PsdImageFile(ImageFile.ImageFile):
|
| 57 |
+
format = "PSD"
|
| 58 |
+
format_description = "Adobe Photoshop"
|
| 59 |
+
_close_exclusive_fp_after_loading = False
|
| 60 |
+
|
| 61 |
+
def _open(self) -> None:
|
| 62 |
+
read = self.fp.read
|
| 63 |
+
|
| 64 |
+
#
|
| 65 |
+
# header
|
| 66 |
+
|
| 67 |
+
s = read(26)
|
| 68 |
+
if not _accept(s) or i16(s, 4) != 1:
|
| 69 |
+
msg = "not a PSD file"
|
| 70 |
+
raise SyntaxError(msg)
|
| 71 |
+
|
| 72 |
+
psd_bits = i16(s, 22)
|
| 73 |
+
psd_channels = i16(s, 12)
|
| 74 |
+
psd_mode = i16(s, 24)
|
| 75 |
+
|
| 76 |
+
mode, channels = MODES[(psd_mode, psd_bits)]
|
| 77 |
+
|
| 78 |
+
if channels > psd_channels:
|
| 79 |
+
msg = "not enough channels"
|
| 80 |
+
raise OSError(msg)
|
| 81 |
+
if mode == "RGB" and psd_channels == 4:
|
| 82 |
+
mode = "RGBA"
|
| 83 |
+
channels = 4
|
| 84 |
+
|
| 85 |
+
self._mode = mode
|
| 86 |
+
self._size = i32(s, 18), i32(s, 14)
|
| 87 |
+
|
| 88 |
+
#
|
| 89 |
+
# color mode data
|
| 90 |
+
|
| 91 |
+
size = i32(read(4))
|
| 92 |
+
if size:
|
| 93 |
+
data = read(size)
|
| 94 |
+
if mode == "P" and size == 768:
|
| 95 |
+
self.palette = ImagePalette.raw("RGB;L", data)
|
| 96 |
+
|
| 97 |
+
#
|
| 98 |
+
# image resources
|
| 99 |
+
|
| 100 |
+
self.resources = []
|
| 101 |
+
|
| 102 |
+
size = i32(read(4))
|
| 103 |
+
if size:
|
| 104 |
+
# load resources
|
| 105 |
+
end = self.fp.tell() + size
|
| 106 |
+
while self.fp.tell() < end:
|
| 107 |
+
read(4) # signature
|
| 108 |
+
id = i16(read(2))
|
| 109 |
+
name = read(i8(read(1)))
|
| 110 |
+
if not (len(name) & 1):
|
| 111 |
+
read(1) # padding
|
| 112 |
+
data = read(i32(read(4)))
|
| 113 |
+
if len(data) & 1:
|
| 114 |
+
read(1) # padding
|
| 115 |
+
self.resources.append((id, name, data))
|
| 116 |
+
if id == 1039: # ICC profile
|
| 117 |
+
self.info["icc_profile"] = data
|
| 118 |
+
|
| 119 |
+
#
|
| 120 |
+
# layer and mask information
|
| 121 |
+
|
| 122 |
+
self._layers_position = None
|
| 123 |
+
|
| 124 |
+
size = i32(read(4))
|
| 125 |
+
if size:
|
| 126 |
+
end = self.fp.tell() + size
|
| 127 |
+
size = i32(read(4))
|
| 128 |
+
if size:
|
| 129 |
+
self._layers_position = self.fp.tell()
|
| 130 |
+
self._layers_size = size
|
| 131 |
+
self.fp.seek(end)
|
| 132 |
+
self._n_frames: int | None = None
|
| 133 |
+
|
| 134 |
+
#
|
| 135 |
+
# image descriptor
|
| 136 |
+
|
| 137 |
+
self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)
|
| 138 |
+
|
| 139 |
+
# keep the file open
|
| 140 |
+
self._fp = self.fp
|
| 141 |
+
self.frame = 1
|
| 142 |
+
self._min_frame = 1
|
| 143 |
+
|
| 144 |
+
@cached_property
|
| 145 |
+
def layers(self):
|
| 146 |
+
layers = []
|
| 147 |
+
if self._layers_position is not None:
|
| 148 |
+
self._fp.seek(self._layers_position)
|
| 149 |
+
_layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size))
|
| 150 |
+
layers = _layerinfo(_layer_data, self._layers_size)
|
| 151 |
+
self._n_frames = len(layers)
|
| 152 |
+
return layers
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def n_frames(self) -> int:
|
| 156 |
+
if self._n_frames is None:
|
| 157 |
+
self._n_frames = len(self.layers)
|
| 158 |
+
return self._n_frames
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def is_animated(self) -> bool:
|
| 162 |
+
return len(self.layers) > 1
|
| 163 |
+
|
| 164 |
+
def seek(self, layer: int) -> None:
|
| 165 |
+
if not self._seek_check(layer):
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
# seek to given layer (1..max)
|
| 169 |
+
try:
|
| 170 |
+
_, mode, _, tile = self.layers[layer - 1]
|
| 171 |
+
self._mode = mode
|
| 172 |
+
self.tile = tile
|
| 173 |
+
self.frame = layer
|
| 174 |
+
self.fp = self._fp
|
| 175 |
+
except IndexError as e:
|
| 176 |
+
msg = "no such layer"
|
| 177 |
+
raise EOFError(msg) from e
|
| 178 |
+
|
| 179 |
+
def tell(self) -> int:
|
| 180 |
+
# return layer number (0=image, 1..max=layers)
|
| 181 |
+
return self.frame
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _layerinfo(fp, ct_bytes):
|
| 185 |
+
# read layerinfo block
|
| 186 |
+
layers = []
|
| 187 |
+
|
| 188 |
+
def read(size):
|
| 189 |
+
return ImageFile._safe_read(fp, size)
|
| 190 |
+
|
| 191 |
+
ct = si16(read(2))
|
| 192 |
+
|
| 193 |
+
# sanity check
|
| 194 |
+
if ct_bytes < (abs(ct) * 20):
|
| 195 |
+
msg = "Layer block too short for number of layers requested"
|
| 196 |
+
raise SyntaxError(msg)
|
| 197 |
+
|
| 198 |
+
for _ in range(abs(ct)):
|
| 199 |
+
# bounding box
|
| 200 |
+
y0 = si32(read(4))
|
| 201 |
+
x0 = si32(read(4))
|
| 202 |
+
y1 = si32(read(4))
|
| 203 |
+
x1 = si32(read(4))
|
| 204 |
+
|
| 205 |
+
# image info
|
| 206 |
+
mode = []
|
| 207 |
+
ct_types = i16(read(2))
|
| 208 |
+
if ct_types > 4:
|
| 209 |
+
fp.seek(ct_types * 6 + 12, io.SEEK_CUR)
|
| 210 |
+
size = i32(read(4))
|
| 211 |
+
fp.seek(size, io.SEEK_CUR)
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
for _ in range(ct_types):
|
| 215 |
+
type = i16(read(2))
|
| 216 |
+
|
| 217 |
+
if type == 65535:
|
| 218 |
+
m = "A"
|
| 219 |
+
else:
|
| 220 |
+
m = "RGBA"[type]
|
| 221 |
+
|
| 222 |
+
mode.append(m)
|
| 223 |
+
read(4) # size
|
| 224 |
+
|
| 225 |
+
# figure out the image mode
|
| 226 |
+
mode.sort()
|
| 227 |
+
if mode == ["R"]:
|
| 228 |
+
mode = "L"
|
| 229 |
+
elif mode == ["B", "G", "R"]:
|
| 230 |
+
mode = "RGB"
|
| 231 |
+
elif mode == ["A", "B", "G", "R"]:
|
| 232 |
+
mode = "RGBA"
|
| 233 |
+
else:
|
| 234 |
+
mode = None # unknown
|
| 235 |
+
|
| 236 |
+
# skip over blend flags and extra information
|
| 237 |
+
read(12) # filler
|
| 238 |
+
name = ""
|
| 239 |
+
size = i32(read(4)) # length of the extra data field
|
| 240 |
+
if size:
|
| 241 |
+
data_end = fp.tell() + size
|
| 242 |
+
|
| 243 |
+
length = i32(read(4))
|
| 244 |
+
if length:
|
| 245 |
+
fp.seek(length - 16, io.SEEK_CUR)
|
| 246 |
+
|
| 247 |
+
length = i32(read(4))
|
| 248 |
+
if length:
|
| 249 |
+
fp.seek(length, io.SEEK_CUR)
|
| 250 |
+
|
| 251 |
+
length = i8(read(1))
|
| 252 |
+
if length:
|
| 253 |
+
# Don't know the proper encoding,
|
| 254 |
+
# Latin-1 should be a good guess
|
| 255 |
+
name = read(length).decode("latin-1", "replace")
|
| 256 |
+
|
| 257 |
+
fp.seek(data_end)
|
| 258 |
+
layers.append((name, mode, (x0, y0, x1, y1)))
|
| 259 |
+
|
| 260 |
+
# get tiles
|
| 261 |
+
for i, (name, mode, bbox) in enumerate(layers):
|
| 262 |
+
tile = []
|
| 263 |
+
for m in mode:
|
| 264 |
+
t = _maketile(fp, m, bbox, 1)
|
| 265 |
+
if t:
|
| 266 |
+
tile.extend(t)
|
| 267 |
+
layers[i] = name, mode, bbox, tile
|
| 268 |
+
|
| 269 |
+
return layers
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _maketile(file, mode, bbox, channels):
|
| 273 |
+
tile = None
|
| 274 |
+
read = file.read
|
| 275 |
+
|
| 276 |
+
compression = i16(read(2))
|
| 277 |
+
|
| 278 |
+
xsize = bbox[2] - bbox[0]
|
| 279 |
+
ysize = bbox[3] - bbox[1]
|
| 280 |
+
|
| 281 |
+
offset = file.tell()
|
| 282 |
+
|
| 283 |
+
if compression == 0:
|
| 284 |
+
#
|
| 285 |
+
# raw compression
|
| 286 |
+
tile = []
|
| 287 |
+
for channel in range(channels):
|
| 288 |
+
layer = mode[channel]
|
| 289 |
+
if mode == "CMYK":
|
| 290 |
+
layer += ";I"
|
| 291 |
+
tile.append(("raw", bbox, offset, layer))
|
| 292 |
+
offset = offset + xsize * ysize
|
| 293 |
+
|
| 294 |
+
elif compression == 1:
|
| 295 |
+
#
|
| 296 |
+
# packbits compression
|
| 297 |
+
i = 0
|
| 298 |
+
tile = []
|
| 299 |
+
bytecount = read(channels * ysize * 2)
|
| 300 |
+
offset = file.tell()
|
| 301 |
+
for channel in range(channels):
|
| 302 |
+
layer = mode[channel]
|
| 303 |
+
if mode == "CMYK":
|
| 304 |
+
layer += ";I"
|
| 305 |
+
tile.append(("packbits", bbox, offset, layer))
|
| 306 |
+
for y in range(ysize):
|
| 307 |
+
offset = offset + i16(bytecount, i)
|
| 308 |
+
i += 2
|
| 309 |
+
|
| 310 |
+
file.seek(offset)
|
| 311 |
+
|
| 312 |
+
if offset & 1:
|
| 313 |
+
read(1) # padding
|
| 314 |
+
|
| 315 |
+
return tile
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# --------------------------------------------------------------------
|
| 319 |
+
# registry
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
Image.register_open(PsdImageFile.format, PsdImageFile, _accept)
|
| 323 |
+
|
| 324 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# Pillow fork
|
| 4 |
+
#
|
| 5 |
+
# Python implementation of the PixelAccess Object
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
|
| 8 |
+
# Copyright (c) 1995-2009 by Fredrik Lundh.
|
| 9 |
+
# Copyright (c) 2013 Eric Soroos
|
| 10 |
+
#
|
| 11 |
+
# See the README file for information on usage and redistribution
|
| 12 |
+
#
|
| 13 |
+
|
| 14 |
+
# Notes:
|
| 15 |
+
#
|
| 16 |
+
# * Implements the pixel access object following Access.c
|
| 17 |
+
# * Taking only the tuple form, which is used from python.
|
| 18 |
+
# * Fill.c uses the integer form, but it's still going to use the old
|
| 19 |
+
# Access.c implementation.
|
| 20 |
+
#
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import logging
|
| 24 |
+
import sys
|
| 25 |
+
from typing import TYPE_CHECKING
|
| 26 |
+
|
| 27 |
+
from ._deprecate import deprecate
|
| 28 |
+
|
| 29 |
+
FFI: type
|
| 30 |
+
try:
|
| 31 |
+
from cffi import FFI
|
| 32 |
+
|
| 33 |
+
defs = """
|
| 34 |
+
struct Pixel_RGBA {
|
| 35 |
+
unsigned char r,g,b,a;
|
| 36 |
+
};
|
| 37 |
+
struct Pixel_I16 {
|
| 38 |
+
unsigned char l,r;
|
| 39 |
+
};
|
| 40 |
+
"""
|
| 41 |
+
ffi = FFI()
|
| 42 |
+
ffi.cdef(defs)
|
| 43 |
+
except ImportError as ex:
|
| 44 |
+
# Allow error import for doc purposes, but error out when accessing
|
| 45 |
+
# anything in core.
|
| 46 |
+
from ._util import DeferredError
|
| 47 |
+
|
| 48 |
+
FFI = ffi = DeferredError.new(ex)
|
| 49 |
+
|
| 50 |
+
logger = logging.getLogger(__name__)
|
| 51 |
+
|
| 52 |
+
if TYPE_CHECKING:
|
| 53 |
+
from . import Image
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class PyAccess:
|
| 57 |
+
def __init__(self, img: Image.Image, readonly: bool = False) -> None:
|
| 58 |
+
deprecate("PyAccess", 11)
|
| 59 |
+
vals = dict(img.im.unsafe_ptrs)
|
| 60 |
+
self.readonly = readonly
|
| 61 |
+
self.image8 = ffi.cast("unsigned char **", vals["image8"])
|
| 62 |
+
self.image32 = ffi.cast("int **", vals["image32"])
|
| 63 |
+
self.image = ffi.cast("unsigned char **", vals["image"])
|
| 64 |
+
self.xsize, self.ysize = img.im.size
|
| 65 |
+
self._img = img
|
| 66 |
+
|
| 67 |
+
# Keep pointer to im object to prevent dereferencing.
|
| 68 |
+
self._im = img.im
|
| 69 |
+
if self._im.mode in ("P", "PA"):
|
| 70 |
+
self._palette = img.palette
|
| 71 |
+
|
| 72 |
+
# Debugging is polluting test traces, only useful here
|
| 73 |
+
# when hacking on PyAccess
|
| 74 |
+
# logger.debug("%s", vals)
|
| 75 |
+
self._post_init()
|
| 76 |
+
|
| 77 |
+
def _post_init(self) -> None:
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def __setitem__(
|
| 81 |
+
self,
|
| 82 |
+
xy: tuple[int, int] | list[int],
|
| 83 |
+
color: float | tuple[int, ...] | list[int],
|
| 84 |
+
) -> None:
|
| 85 |
+
"""
|
| 86 |
+
Modifies the pixel at x,y. The color is given as a single
|
| 87 |
+
numerical value for single band images, and a tuple for
|
| 88 |
+
multi-band images. In addition to this, RGB and RGBA tuples
|
| 89 |
+
are accepted for P and PA images.
|
| 90 |
+
|
| 91 |
+
:param xy: The pixel coordinate, given as (x, y). See
|
| 92 |
+
:ref:`coordinate-system`.
|
| 93 |
+
:param color: The pixel value.
|
| 94 |
+
"""
|
| 95 |
+
if self.readonly:
|
| 96 |
+
msg = "Attempt to putpixel a read only image"
|
| 97 |
+
raise ValueError(msg)
|
| 98 |
+
(x, y) = xy
|
| 99 |
+
if x < 0:
|
| 100 |
+
x = self.xsize + x
|
| 101 |
+
if y < 0:
|
| 102 |
+
y = self.ysize + y
|
| 103 |
+
(x, y) = self.check_xy((x, y))
|
| 104 |
+
|
| 105 |
+
if (
|
| 106 |
+
self._im.mode in ("P", "PA")
|
| 107 |
+
and isinstance(color, (list, tuple))
|
| 108 |
+
and len(color) in [3, 4]
|
| 109 |
+
):
|
| 110 |
+
# RGB or RGBA value for a P or PA image
|
| 111 |
+
if self._im.mode == "PA":
|
| 112 |
+
alpha = color[3] if len(color) == 4 else 255
|
| 113 |
+
color = color[:3]
|
| 114 |
+
palette_index = self._palette.getcolor(color, self._img)
|
| 115 |
+
color = (palette_index, alpha) if self._im.mode == "PA" else palette_index
|
| 116 |
+
|
| 117 |
+
return self.set_pixel(x, y, color)
|
| 118 |
+
|
| 119 |
+
def __getitem__(self, xy: tuple[int, int] | list[int]) -> float | tuple[int, ...]:
|
| 120 |
+
"""
|
| 121 |
+
Returns the pixel at x,y. The pixel is returned as a single
|
| 122 |
+
value for single band images or a tuple for multiple band
|
| 123 |
+
images
|
| 124 |
+
|
| 125 |
+
:param xy: The pixel coordinate, given as (x, y). See
|
| 126 |
+
:ref:`coordinate-system`.
|
| 127 |
+
:returns: a pixel value for single band images, a tuple of
|
| 128 |
+
pixel values for multiband images.
|
| 129 |
+
"""
|
| 130 |
+
(x, y) = xy
|
| 131 |
+
if x < 0:
|
| 132 |
+
x = self.xsize + x
|
| 133 |
+
if y < 0:
|
| 134 |
+
y = self.ysize + y
|
| 135 |
+
(x, y) = self.check_xy((x, y))
|
| 136 |
+
return self.get_pixel(x, y)
|
| 137 |
+
|
| 138 |
+
putpixel = __setitem__
|
| 139 |
+
getpixel = __getitem__
|
| 140 |
+
|
| 141 |
+
def check_xy(self, xy: tuple[int, int]) -> tuple[int, int]:
|
| 142 |
+
(x, y) = xy
|
| 143 |
+
if not (0 <= x < self.xsize and 0 <= y < self.ysize):
|
| 144 |
+
msg = "pixel location out of range"
|
| 145 |
+
raise ValueError(msg)
|
| 146 |
+
return xy
|
| 147 |
+
|
| 148 |
+
def get_pixel(self, x: int, y: int) -> float | tuple[int, ...]:
|
| 149 |
+
raise NotImplementedError()
|
| 150 |
+
|
| 151 |
+
def set_pixel(
|
| 152 |
+
self, x: int, y: int, color: float | tuple[int, ...] | list[int]
|
| 153 |
+
) -> None:
|
| 154 |
+
raise NotImplementedError()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class _PyAccess32_2(PyAccess):
|
| 158 |
+
"""PA, LA, stored in first and last bytes of a 32 bit word"""
|
| 159 |
+
|
| 160 |
+
def _post_init(self, *args, **kwargs):
|
| 161 |
+
self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
|
| 162 |
+
|
| 163 |
+
def get_pixel(self, x: int, y: int) -> tuple[int, int]:
|
| 164 |
+
pixel = self.pixels[y][x]
|
| 165 |
+
return pixel.r, pixel.a
|
| 166 |
+
|
| 167 |
+
def set_pixel(self, x, y, color):
|
| 168 |
+
pixel = self.pixels[y][x]
|
| 169 |
+
# tuple
|
| 170 |
+
pixel.r = min(color[0], 255)
|
| 171 |
+
pixel.a = min(color[1], 255)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class _PyAccess32_3(PyAccess):
|
| 175 |
+
"""RGB and friends, stored in the first three bytes of a 32 bit word"""
|
| 176 |
+
|
| 177 |
+
def _post_init(self, *args, **kwargs):
|
| 178 |
+
self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
|
| 179 |
+
|
| 180 |
+
def get_pixel(self, x: int, y: int) -> tuple[int, int, int]:
|
| 181 |
+
pixel = self.pixels[y][x]
|
| 182 |
+
return pixel.r, pixel.g, pixel.b
|
| 183 |
+
|
| 184 |
+
def set_pixel(self, x, y, color):
|
| 185 |
+
pixel = self.pixels[y][x]
|
| 186 |
+
# tuple
|
| 187 |
+
pixel.r = min(color[0], 255)
|
| 188 |
+
pixel.g = min(color[1], 255)
|
| 189 |
+
pixel.b = min(color[2], 255)
|
| 190 |
+
pixel.a = 255
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class _PyAccess32_4(PyAccess):
|
| 194 |
+
"""RGBA etc, all 4 bytes of a 32 bit word"""
|
| 195 |
+
|
| 196 |
+
def _post_init(self, *args, **kwargs):
|
| 197 |
+
self.pixels = ffi.cast("struct Pixel_RGBA **", self.image32)
|
| 198 |
+
|
| 199 |
+
def get_pixel(self, x: int, y: int) -> tuple[int, int, int, int]:
|
| 200 |
+
pixel = self.pixels[y][x]
|
| 201 |
+
return pixel.r, pixel.g, pixel.b, pixel.a
|
| 202 |
+
|
| 203 |
+
def set_pixel(self, x, y, color):
|
| 204 |
+
pixel = self.pixels[y][x]
|
| 205 |
+
# tuple
|
| 206 |
+
pixel.r = min(color[0], 255)
|
| 207 |
+
pixel.g = min(color[1], 255)
|
| 208 |
+
pixel.b = min(color[2], 255)
|
| 209 |
+
pixel.a = min(color[3], 255)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class _PyAccess8(PyAccess):
|
| 213 |
+
"""1, L, P, 8 bit images stored as uint8"""
|
| 214 |
+
|
| 215 |
+
def _post_init(self, *args, **kwargs):
|
| 216 |
+
self.pixels = self.image8
|
| 217 |
+
|
| 218 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 219 |
+
return self.pixels[y][x]
|
| 220 |
+
|
| 221 |
+
def set_pixel(self, x, y, color):
|
| 222 |
+
try:
|
| 223 |
+
# integer
|
| 224 |
+
self.pixels[y][x] = min(color, 255)
|
| 225 |
+
except TypeError:
|
| 226 |
+
# tuple
|
| 227 |
+
self.pixels[y][x] = min(color[0], 255)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class _PyAccessI16_N(PyAccess):
|
| 231 |
+
"""I;16 access, native bitendian without conversion"""
|
| 232 |
+
|
| 233 |
+
def _post_init(self, *args, **kwargs):
|
| 234 |
+
self.pixels = ffi.cast("unsigned short **", self.image)
|
| 235 |
+
|
| 236 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 237 |
+
return self.pixels[y][x]
|
| 238 |
+
|
| 239 |
+
def set_pixel(self, x, y, color):
|
| 240 |
+
try:
|
| 241 |
+
# integer
|
| 242 |
+
self.pixels[y][x] = min(color, 65535)
|
| 243 |
+
except TypeError:
|
| 244 |
+
# tuple
|
| 245 |
+
self.pixels[y][x] = min(color[0], 65535)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class _PyAccessI16_L(PyAccess):
|
| 249 |
+
"""I;16L access, with conversion"""
|
| 250 |
+
|
| 251 |
+
def _post_init(self, *args, **kwargs):
|
| 252 |
+
self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
|
| 253 |
+
|
| 254 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 255 |
+
pixel = self.pixels[y][x]
|
| 256 |
+
return pixel.l + pixel.r * 256
|
| 257 |
+
|
| 258 |
+
def set_pixel(self, x, y, color):
|
| 259 |
+
pixel = self.pixels[y][x]
|
| 260 |
+
try:
|
| 261 |
+
color = min(color, 65535)
|
| 262 |
+
except TypeError:
|
| 263 |
+
color = min(color[0], 65535)
|
| 264 |
+
|
| 265 |
+
pixel.l = color & 0xFF
|
| 266 |
+
pixel.r = color >> 8
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class _PyAccessI16_B(PyAccess):
|
| 270 |
+
"""I;16B access, with conversion"""
|
| 271 |
+
|
| 272 |
+
def _post_init(self, *args, **kwargs):
|
| 273 |
+
self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
|
| 274 |
+
|
| 275 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 276 |
+
pixel = self.pixels[y][x]
|
| 277 |
+
return pixel.l * 256 + pixel.r
|
| 278 |
+
|
| 279 |
+
def set_pixel(self, x, y, color):
|
| 280 |
+
pixel = self.pixels[y][x]
|
| 281 |
+
try:
|
| 282 |
+
color = min(color, 65535)
|
| 283 |
+
except Exception:
|
| 284 |
+
color = min(color[0], 65535)
|
| 285 |
+
|
| 286 |
+
pixel.l = color >> 8
|
| 287 |
+
pixel.r = color & 0xFF
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class _PyAccessI32_N(PyAccess):
|
| 291 |
+
"""Signed Int32 access, native endian"""
|
| 292 |
+
|
| 293 |
+
def _post_init(self, *args, **kwargs):
|
| 294 |
+
self.pixels = self.image32
|
| 295 |
+
|
| 296 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 297 |
+
return self.pixels[y][x]
|
| 298 |
+
|
| 299 |
+
def set_pixel(self, x, y, color):
|
| 300 |
+
self.pixels[y][x] = color
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class _PyAccessI32_Swap(PyAccess):
|
| 304 |
+
"""I;32L/B access, with byteswapping conversion"""
|
| 305 |
+
|
| 306 |
+
def _post_init(self, *args, **kwargs):
|
| 307 |
+
self.pixels = self.image32
|
| 308 |
+
|
| 309 |
+
def reverse(self, i):
|
| 310 |
+
orig = ffi.new("int *", i)
|
| 311 |
+
chars = ffi.cast("unsigned char *", orig)
|
| 312 |
+
chars[0], chars[1], chars[2], chars[3] = chars[3], chars[2], chars[1], chars[0]
|
| 313 |
+
return ffi.cast("int *", chars)[0]
|
| 314 |
+
|
| 315 |
+
def get_pixel(self, x: int, y: int) -> int:
|
| 316 |
+
return self.reverse(self.pixels[y][x])
|
| 317 |
+
|
| 318 |
+
def set_pixel(self, x, y, color):
|
| 319 |
+
self.pixels[y][x] = self.reverse(color)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class _PyAccessF(PyAccess):
|
| 323 |
+
"""32 bit float access"""
|
| 324 |
+
|
| 325 |
+
def _post_init(self, *args, **kwargs):
|
| 326 |
+
self.pixels = ffi.cast("float **", self.image32)
|
| 327 |
+
|
| 328 |
+
def get_pixel(self, x: int, y: int) -> float:
|
| 329 |
+
return self.pixels[y][x]
|
| 330 |
+
|
| 331 |
+
def set_pixel(self, x, y, color):
|
| 332 |
+
try:
|
| 333 |
+
# not a tuple
|
| 334 |
+
self.pixels[y][x] = color
|
| 335 |
+
except TypeError:
|
| 336 |
+
# tuple
|
| 337 |
+
self.pixels[y][x] = color[0]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
mode_map = {
|
| 341 |
+
"1": _PyAccess8,
|
| 342 |
+
"L": _PyAccess8,
|
| 343 |
+
"P": _PyAccess8,
|
| 344 |
+
"I;16N": _PyAccessI16_N,
|
| 345 |
+
"LA": _PyAccess32_2,
|
| 346 |
+
"La": _PyAccess32_2,
|
| 347 |
+
"PA": _PyAccess32_2,
|
| 348 |
+
"RGB": _PyAccess32_3,
|
| 349 |
+
"LAB": _PyAccess32_3,
|
| 350 |
+
"HSV": _PyAccess32_3,
|
| 351 |
+
"YCbCr": _PyAccess32_3,
|
| 352 |
+
"RGBA": _PyAccess32_4,
|
| 353 |
+
"RGBa": _PyAccess32_4,
|
| 354 |
+
"RGBX": _PyAccess32_4,
|
| 355 |
+
"CMYK": _PyAccess32_4,
|
| 356 |
+
"F": _PyAccessF,
|
| 357 |
+
"I": _PyAccessI32_N,
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
if sys.byteorder == "little":
|
| 361 |
+
mode_map["I;16"] = _PyAccessI16_N
|
| 362 |
+
mode_map["I;16L"] = _PyAccessI16_N
|
| 363 |
+
mode_map["I;16B"] = _PyAccessI16_B
|
| 364 |
+
|
| 365 |
+
mode_map["I;32L"] = _PyAccessI32_N
|
| 366 |
+
mode_map["I;32B"] = _PyAccessI32_Swap
|
| 367 |
+
else:
|
| 368 |
+
mode_map["I;16"] = _PyAccessI16_L
|
| 369 |
+
mode_map["I;16L"] = _PyAccessI16_L
|
| 370 |
+
mode_map["I;16B"] = _PyAccessI16_N
|
| 371 |
+
|
| 372 |
+
mode_map["I;32L"] = _PyAccessI32_Swap
|
| 373 |
+
mode_map["I;32B"] = _PyAccessI32_N
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def new(img: Image.Image, readonly: bool = False) -> PyAccess | None:
|
| 377 |
+
access_type = mode_map.get(img.mode, None)
|
| 378 |
+
if not access_type:
|
| 379 |
+
logger.debug("PyAccess Not Implemented: %s", img.mode)
|
| 380 |
+
return None
|
| 381 |
+
return access_type(img, readonly)
|
valley/lib/python3.10/site-packages/PIL/SgiImagePlugin.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
|
| 9 |
+
#
|
| 10 |
+
#
|
| 11 |
+
# History:
|
| 12 |
+
# 2017-22-07 mb Add RLE decompression
|
| 13 |
+
# 2016-16-10 mb Add save method without compression
|
| 14 |
+
# 1995-09-10 fl Created
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) 2016 by Mickael Bonfill.
|
| 17 |
+
# Copyright (c) 2008 by Karsten Hiddemann.
|
| 18 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 19 |
+
# Copyright (c) 1995 by Fredrik Lundh.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
import struct
|
| 27 |
+
from typing import IO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageFile
|
| 30 |
+
from ._binary import i16be as i16
|
| 31 |
+
from ._binary import o8
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return len(prefix) >= 2 and i16(prefix) == 474
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
MODES = {
|
| 39 |
+
(1, 1, 1): "L",
|
| 40 |
+
(1, 2, 1): "L",
|
| 41 |
+
(2, 1, 1): "L;16B",
|
| 42 |
+
(2, 2, 1): "L;16B",
|
| 43 |
+
(1, 3, 3): "RGB",
|
| 44 |
+
(2, 3, 3): "RGB;16B",
|
| 45 |
+
(1, 3, 4): "RGBA",
|
| 46 |
+
(2, 3, 4): "RGBA;16B",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
##
|
| 51 |
+
# Image plugin for SGI images.
|
| 52 |
+
class SgiImageFile(ImageFile.ImageFile):
|
| 53 |
+
format = "SGI"
|
| 54 |
+
format_description = "SGI Image File Format"
|
| 55 |
+
|
| 56 |
+
def _open(self) -> None:
|
| 57 |
+
# HEAD
|
| 58 |
+
assert self.fp is not None
|
| 59 |
+
|
| 60 |
+
headlen = 512
|
| 61 |
+
s = self.fp.read(headlen)
|
| 62 |
+
|
| 63 |
+
if not _accept(s):
|
| 64 |
+
msg = "Not an SGI image file"
|
| 65 |
+
raise ValueError(msg)
|
| 66 |
+
|
| 67 |
+
# compression : verbatim or RLE
|
| 68 |
+
compression = s[2]
|
| 69 |
+
|
| 70 |
+
# bpc : 1 or 2 bytes (8bits or 16bits)
|
| 71 |
+
bpc = s[3]
|
| 72 |
+
|
| 73 |
+
# dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
|
| 74 |
+
dimension = i16(s, 4)
|
| 75 |
+
|
| 76 |
+
# xsize : width
|
| 77 |
+
xsize = i16(s, 6)
|
| 78 |
+
|
| 79 |
+
# ysize : height
|
| 80 |
+
ysize = i16(s, 8)
|
| 81 |
+
|
| 82 |
+
# zsize : channels count
|
| 83 |
+
zsize = i16(s, 10)
|
| 84 |
+
|
| 85 |
+
# layout
|
| 86 |
+
layout = bpc, dimension, zsize
|
| 87 |
+
|
| 88 |
+
# determine mode from bits/zsize
|
| 89 |
+
rawmode = ""
|
| 90 |
+
try:
|
| 91 |
+
rawmode = MODES[layout]
|
| 92 |
+
except KeyError:
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
if rawmode == "":
|
| 96 |
+
msg = "Unsupported SGI image mode"
|
| 97 |
+
raise ValueError(msg)
|
| 98 |
+
|
| 99 |
+
self._size = xsize, ysize
|
| 100 |
+
self._mode = rawmode.split(";")[0]
|
| 101 |
+
if self.mode == "RGB":
|
| 102 |
+
self.custom_mimetype = "image/rgb"
|
| 103 |
+
|
| 104 |
+
# orientation -1 : scanlines begins at the bottom-left corner
|
| 105 |
+
orientation = -1
|
| 106 |
+
|
| 107 |
+
# decoder info
|
| 108 |
+
if compression == 0:
|
| 109 |
+
pagesize = xsize * ysize * bpc
|
| 110 |
+
if bpc == 2:
|
| 111 |
+
self.tile = [
|
| 112 |
+
("SGI16", (0, 0) + self.size, headlen, (self.mode, 0, orientation))
|
| 113 |
+
]
|
| 114 |
+
else:
|
| 115 |
+
self.tile = []
|
| 116 |
+
offset = headlen
|
| 117 |
+
for layer in self.mode:
|
| 118 |
+
self.tile.append(
|
| 119 |
+
("raw", (0, 0) + self.size, offset, (layer, 0, orientation))
|
| 120 |
+
)
|
| 121 |
+
offset += pagesize
|
| 122 |
+
elif compression == 1:
|
| 123 |
+
self.tile = [
|
| 124 |
+
("sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc))
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 129 |
+
if im.mode not in {"RGB", "RGBA", "L"}:
|
| 130 |
+
msg = "Unsupported SGI image mode"
|
| 131 |
+
raise ValueError(msg)
|
| 132 |
+
|
| 133 |
+
# Get the keyword arguments
|
| 134 |
+
info = im.encoderinfo
|
| 135 |
+
|
| 136 |
+
# Byte-per-pixel precision, 1 = 8bits per pixel
|
| 137 |
+
bpc = info.get("bpc", 1)
|
| 138 |
+
|
| 139 |
+
if bpc not in (1, 2):
|
| 140 |
+
msg = "Unsupported number of bytes per pixel"
|
| 141 |
+
raise ValueError(msg)
|
| 142 |
+
|
| 143 |
+
# Flip the image, since the origin of SGI file is the bottom-left corner
|
| 144 |
+
orientation = -1
|
| 145 |
+
# Define the file as SGI File Format
|
| 146 |
+
magic_number = 474
|
| 147 |
+
# Run-Length Encoding Compression - Unsupported at this time
|
| 148 |
+
rle = 0
|
| 149 |
+
|
| 150 |
+
# Number of dimensions (x,y,z)
|
| 151 |
+
dim = 3
|
| 152 |
+
# X Dimension = width / Y Dimension = height
|
| 153 |
+
x, y = im.size
|
| 154 |
+
if im.mode == "L" and y == 1:
|
| 155 |
+
dim = 1
|
| 156 |
+
elif im.mode == "L":
|
| 157 |
+
dim = 2
|
| 158 |
+
# Z Dimension: Number of channels
|
| 159 |
+
z = len(im.mode)
|
| 160 |
+
|
| 161 |
+
if dim in {1, 2}:
|
| 162 |
+
z = 1
|
| 163 |
+
|
| 164 |
+
# assert we've got the right number of bands.
|
| 165 |
+
if len(im.getbands()) != z:
|
| 166 |
+
msg = f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}"
|
| 167 |
+
raise ValueError(msg)
|
| 168 |
+
|
| 169 |
+
# Minimum Byte value
|
| 170 |
+
pinmin = 0
|
| 171 |
+
# Maximum Byte value (255 = 8bits per pixel)
|
| 172 |
+
pinmax = 255
|
| 173 |
+
# Image name (79 characters max, truncated below in write)
|
| 174 |
+
img_name = os.path.splitext(os.path.basename(filename))[0]
|
| 175 |
+
if isinstance(img_name, str):
|
| 176 |
+
img_name = img_name.encode("ascii", "ignore")
|
| 177 |
+
# Standard representation of pixel in the file
|
| 178 |
+
colormap = 0
|
| 179 |
+
fp.write(struct.pack(">h", magic_number))
|
| 180 |
+
fp.write(o8(rle))
|
| 181 |
+
fp.write(o8(bpc))
|
| 182 |
+
fp.write(struct.pack(">H", dim))
|
| 183 |
+
fp.write(struct.pack(">H", x))
|
| 184 |
+
fp.write(struct.pack(">H", y))
|
| 185 |
+
fp.write(struct.pack(">H", z))
|
| 186 |
+
fp.write(struct.pack(">l", pinmin))
|
| 187 |
+
fp.write(struct.pack(">l", pinmax))
|
| 188 |
+
fp.write(struct.pack("4s", b"")) # dummy
|
| 189 |
+
fp.write(struct.pack("79s", img_name)) # truncates to 79 chars
|
| 190 |
+
fp.write(struct.pack("s", b"")) # force null byte after img_name
|
| 191 |
+
fp.write(struct.pack(">l", colormap))
|
| 192 |
+
fp.write(struct.pack("404s", b"")) # dummy
|
| 193 |
+
|
| 194 |
+
rawmode = "L"
|
| 195 |
+
if bpc == 2:
|
| 196 |
+
rawmode = "L;16B"
|
| 197 |
+
|
| 198 |
+
for channel in im.split():
|
| 199 |
+
fp.write(channel.tobytes("raw", rawmode, 0, orientation))
|
| 200 |
+
|
| 201 |
+
if hasattr(fp, "flush"):
|
| 202 |
+
fp.flush()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class SGI16Decoder(ImageFile.PyDecoder):
|
| 206 |
+
_pulls_fd = True
|
| 207 |
+
|
| 208 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 209 |
+
assert self.fd is not None
|
| 210 |
+
assert self.im is not None
|
| 211 |
+
|
| 212 |
+
rawmode, stride, orientation = self.args
|
| 213 |
+
pagesize = self.state.xsize * self.state.ysize
|
| 214 |
+
zsize = len(self.mode)
|
| 215 |
+
self.fd.seek(512)
|
| 216 |
+
|
| 217 |
+
for band in range(zsize):
|
| 218 |
+
channel = Image.new("L", (self.state.xsize, self.state.ysize))
|
| 219 |
+
channel.frombytes(
|
| 220 |
+
self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
|
| 221 |
+
)
|
| 222 |
+
self.im.putband(channel.im, band)
|
| 223 |
+
|
| 224 |
+
return -1, 0
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
#
|
| 228 |
+
# registry
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
Image.register_decoder("SGI16", SGI16Decoder)
|
| 232 |
+
Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
|
| 233 |
+
Image.register_save(SgiImageFile.format, _save)
|
| 234 |
+
Image.register_mime(SgiImageFile.format, "image/sgi")
|
| 235 |
+
|
| 236 |
+
Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
|
| 237 |
+
|
| 238 |
+
# End of file
|
valley/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
#
|
| 4 |
+
# SPIDER image file handling
|
| 5 |
+
#
|
| 6 |
+
# History:
|
| 7 |
+
# 2004-08-02 Created BB
|
| 8 |
+
# 2006-03-02 added save method
|
| 9 |
+
# 2006-03-13 added support for stack images
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
|
| 12 |
+
# Copyright (c) 2004 by William Baxter.
|
| 13 |
+
# Copyright (c) 2004 by Secret Labs AB.
|
| 14 |
+
# Copyright (c) 2004 by Fredrik Lundh.
|
| 15 |
+
#
|
| 16 |
+
|
| 17 |
+
##
|
| 18 |
+
# Image plugin for the Spider image format. This format is used
|
| 19 |
+
# by the SPIDER software, in processing image data from electron
|
| 20 |
+
# microscopy and tomography.
|
| 21 |
+
##
|
| 22 |
+
|
| 23 |
+
#
|
| 24 |
+
# SpiderImagePlugin.py
|
| 25 |
+
#
|
| 26 |
+
# The Spider image format is used by SPIDER software, in processing
|
| 27 |
+
# image data from electron microscopy and tomography.
|
| 28 |
+
#
|
| 29 |
+
# Spider home page:
|
| 30 |
+
# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
|
| 31 |
+
#
|
| 32 |
+
# Details about the Spider image format:
|
| 33 |
+
# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
|
| 34 |
+
#
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
|
| 37 |
+
import os
|
| 38 |
+
import struct
|
| 39 |
+
import sys
|
| 40 |
+
from typing import IO, TYPE_CHECKING, Any, Tuple, cast
|
| 41 |
+
|
| 42 |
+
from . import Image, ImageFile
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def isInt(f: Any) -> int:
|
| 46 |
+
try:
|
| 47 |
+
i = int(f)
|
| 48 |
+
if f - i == 0:
|
| 49 |
+
return 1
|
| 50 |
+
else:
|
| 51 |
+
return 0
|
| 52 |
+
except (ValueError, OverflowError):
|
| 53 |
+
return 0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
iforms = [1, 3, -11, -12, -21, -22]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# There is no magic number to identify Spider files, so just check a
|
| 60 |
+
# series of header locations to see if they have reasonable values.
|
| 61 |
+
# Returns no. of bytes in the header, if it is a valid Spider header,
|
| 62 |
+
# otherwise returns 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def isSpiderHeader(t: tuple[float, ...]) -> int:
|
| 66 |
+
h = (99,) + t # add 1 value so can use spider header index start=1
|
| 67 |
+
# header values 1,2,5,12,13,22,23 should be integers
|
| 68 |
+
for i in [1, 2, 5, 12, 13, 22, 23]:
|
| 69 |
+
if not isInt(h[i]):
|
| 70 |
+
return 0
|
| 71 |
+
# check iform
|
| 72 |
+
iform = int(h[5])
|
| 73 |
+
if iform not in iforms:
|
| 74 |
+
return 0
|
| 75 |
+
# check other header values
|
| 76 |
+
labrec = int(h[13]) # no. records in file header
|
| 77 |
+
labbyt = int(h[22]) # total no. of bytes in header
|
| 78 |
+
lenbyt = int(h[23]) # record length in bytes
|
| 79 |
+
if labbyt != (labrec * lenbyt):
|
| 80 |
+
return 0
|
| 81 |
+
# looks like a valid header
|
| 82 |
+
return labbyt
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def isSpiderImage(filename: str) -> int:
|
| 86 |
+
with open(filename, "rb") as fp:
|
| 87 |
+
f = fp.read(92) # read 23 * 4 bytes
|
| 88 |
+
t = struct.unpack(">23f", f) # try big-endian first
|
| 89 |
+
hdrlen = isSpiderHeader(t)
|
| 90 |
+
if hdrlen == 0:
|
| 91 |
+
t = struct.unpack("<23f", f) # little-endian
|
| 92 |
+
hdrlen = isSpiderHeader(t)
|
| 93 |
+
return hdrlen
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class SpiderImageFile(ImageFile.ImageFile):
|
| 97 |
+
format = "SPIDER"
|
| 98 |
+
format_description = "Spider 2D image"
|
| 99 |
+
_close_exclusive_fp_after_loading = False
|
| 100 |
+
|
| 101 |
+
def _open(self) -> None:
|
| 102 |
+
# check header
|
| 103 |
+
n = 27 * 4 # read 27 float values
|
| 104 |
+
f = self.fp.read(n)
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
self.bigendian = 1
|
| 108 |
+
t = struct.unpack(">27f", f) # try big-endian first
|
| 109 |
+
hdrlen = isSpiderHeader(t)
|
| 110 |
+
if hdrlen == 0:
|
| 111 |
+
self.bigendian = 0
|
| 112 |
+
t = struct.unpack("<27f", f) # little-endian
|
| 113 |
+
hdrlen = isSpiderHeader(t)
|
| 114 |
+
if hdrlen == 0:
|
| 115 |
+
msg = "not a valid Spider file"
|
| 116 |
+
raise SyntaxError(msg)
|
| 117 |
+
except struct.error as e:
|
| 118 |
+
msg = "not a valid Spider file"
|
| 119 |
+
raise SyntaxError(msg) from e
|
| 120 |
+
|
| 121 |
+
h = (99,) + t # add 1 value : spider header index starts at 1
|
| 122 |
+
iform = int(h[5])
|
| 123 |
+
if iform != 1:
|
| 124 |
+
msg = "not a Spider 2D image"
|
| 125 |
+
raise SyntaxError(msg)
|
| 126 |
+
|
| 127 |
+
self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
|
| 128 |
+
self.istack = int(h[24])
|
| 129 |
+
self.imgnumber = int(h[27])
|
| 130 |
+
|
| 131 |
+
if self.istack == 0 and self.imgnumber == 0:
|
| 132 |
+
# stk=0, img=0: a regular 2D image
|
| 133 |
+
offset = hdrlen
|
| 134 |
+
self._nimages = 1
|
| 135 |
+
elif self.istack > 0 and self.imgnumber == 0:
|
| 136 |
+
# stk>0, img=0: Opening the stack for the first time
|
| 137 |
+
self.imgbytes = int(h[12]) * int(h[2]) * 4
|
| 138 |
+
self.hdrlen = hdrlen
|
| 139 |
+
self._nimages = int(h[26])
|
| 140 |
+
# Point to the first image in the stack
|
| 141 |
+
offset = hdrlen * 2
|
| 142 |
+
self.imgnumber = 1
|
| 143 |
+
elif self.istack == 0 and self.imgnumber > 0:
|
| 144 |
+
# stk=0, img>0: an image within the stack
|
| 145 |
+
offset = hdrlen + self.stkoffset
|
| 146 |
+
self.istack = 2 # So Image knows it's still a stack
|
| 147 |
+
else:
|
| 148 |
+
msg = "inconsistent stack header values"
|
| 149 |
+
raise SyntaxError(msg)
|
| 150 |
+
|
| 151 |
+
if self.bigendian:
|
| 152 |
+
self.rawmode = "F;32BF"
|
| 153 |
+
else:
|
| 154 |
+
self.rawmode = "F;32F"
|
| 155 |
+
self._mode = "F"
|
| 156 |
+
|
| 157 |
+
self.tile = [("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))]
|
| 158 |
+
self._fp = self.fp # FIXME: hack
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def n_frames(self) -> int:
|
| 162 |
+
return self._nimages
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def is_animated(self) -> bool:
|
| 166 |
+
return self._nimages > 1
|
| 167 |
+
|
| 168 |
+
# 1st image index is zero (although SPIDER imgnumber starts at 1)
|
| 169 |
+
def tell(self) -> int:
|
| 170 |
+
if self.imgnumber < 1:
|
| 171 |
+
return 0
|
| 172 |
+
else:
|
| 173 |
+
return self.imgnumber - 1
|
| 174 |
+
|
| 175 |
+
def seek(self, frame: int) -> None:
|
| 176 |
+
if self.istack == 0:
|
| 177 |
+
msg = "attempt to seek in a non-stack file"
|
| 178 |
+
raise EOFError(msg)
|
| 179 |
+
if not self._seek_check(frame):
|
| 180 |
+
return
|
| 181 |
+
self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
|
| 182 |
+
self.fp = self._fp
|
| 183 |
+
self.fp.seek(self.stkoffset)
|
| 184 |
+
self._open()
|
| 185 |
+
|
| 186 |
+
# returns a byte image after rescaling to 0..255
|
| 187 |
+
def convert2byte(self, depth: int = 255) -> Image.Image:
|
| 188 |
+
extrema = self.getextrema()
|
| 189 |
+
assert isinstance(extrema[0], float)
|
| 190 |
+
minimum, maximum = cast(Tuple[float, float], extrema)
|
| 191 |
+
m: float = 1
|
| 192 |
+
if maximum != minimum:
|
| 193 |
+
m = depth / (maximum - minimum)
|
| 194 |
+
b = -m * minimum
|
| 195 |
+
return self.point(lambda i: i * m + b).convert("L")
|
| 196 |
+
|
| 197 |
+
if TYPE_CHECKING:
|
| 198 |
+
from . import ImageTk
|
| 199 |
+
|
| 200 |
+
# returns a ImageTk.PhotoImage object, after rescaling to 0..255
|
| 201 |
+
def tkPhotoImage(self) -> ImageTk.PhotoImage:
|
| 202 |
+
from . import ImageTk
|
| 203 |
+
|
| 204 |
+
return ImageTk.PhotoImage(self.convert2byte(), palette=256)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# --------------------------------------------------------------------
|
| 208 |
+
# Image series
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# given a list of filenames, return a list of images
|
| 212 |
+
def loadImageSeries(filelist: list[str] | None = None) -> list[SpiderImageFile] | None:
|
| 213 |
+
"""create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
|
| 214 |
+
if filelist is None or len(filelist) < 1:
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
imglist = []
|
| 218 |
+
for img in filelist:
|
| 219 |
+
if not os.path.exists(img):
|
| 220 |
+
print(f"unable to find {img}")
|
| 221 |
+
continue
|
| 222 |
+
try:
|
| 223 |
+
with Image.open(img) as im:
|
| 224 |
+
im = im.convert2byte()
|
| 225 |
+
except Exception:
|
| 226 |
+
if not isSpiderImage(img):
|
| 227 |
+
print(f"{img} is not a Spider image file")
|
| 228 |
+
continue
|
| 229 |
+
im.info["filename"] = img
|
| 230 |
+
imglist.append(im)
|
| 231 |
+
return imglist
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# --------------------------------------------------------------------
|
| 235 |
+
# For saving images in Spider format
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def makeSpiderHeader(im: Image.Image) -> list[bytes]:
|
| 239 |
+
nsam, nrow = im.size
|
| 240 |
+
lenbyt = nsam * 4 # There are labrec records in the header
|
| 241 |
+
labrec = int(1024 / lenbyt)
|
| 242 |
+
if 1024 % lenbyt != 0:
|
| 243 |
+
labrec += 1
|
| 244 |
+
labbyt = labrec * lenbyt
|
| 245 |
+
nvalues = int(labbyt / 4)
|
| 246 |
+
if nvalues < 23:
|
| 247 |
+
return []
|
| 248 |
+
|
| 249 |
+
hdr = [0.0] * nvalues
|
| 250 |
+
|
| 251 |
+
# NB these are Fortran indices
|
| 252 |
+
hdr[1] = 1.0 # nslice (=1 for an image)
|
| 253 |
+
hdr[2] = float(nrow) # number of rows per slice
|
| 254 |
+
hdr[3] = float(nrow) # number of records in the image
|
| 255 |
+
hdr[5] = 1.0 # iform for 2D image
|
| 256 |
+
hdr[12] = float(nsam) # number of pixels per line
|
| 257 |
+
hdr[13] = float(labrec) # number of records in file header
|
| 258 |
+
hdr[22] = float(labbyt) # total number of bytes in header
|
| 259 |
+
hdr[23] = float(lenbyt) # record length in bytes
|
| 260 |
+
|
| 261 |
+
# adjust for Fortran indexing
|
| 262 |
+
hdr = hdr[1:]
|
| 263 |
+
hdr.append(0.0)
|
| 264 |
+
# pack binary data into a string
|
| 265 |
+
return [struct.pack("f", v) for v in hdr]
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 269 |
+
if im.mode[0] != "F":
|
| 270 |
+
im = im.convert("F")
|
| 271 |
+
|
| 272 |
+
hdr = makeSpiderHeader(im)
|
| 273 |
+
if len(hdr) < 256:
|
| 274 |
+
msg = "Error creating Spider header"
|
| 275 |
+
raise OSError(msg)
|
| 276 |
+
|
| 277 |
+
# write the SPIDER header
|
| 278 |
+
fp.writelines(hdr)
|
| 279 |
+
|
| 280 |
+
rawmode = "F;32NF" # 32-bit native floating point
|
| 281 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 285 |
+
# get the filename extension and register it with Image
|
| 286 |
+
filename_ext = os.path.splitext(filename)[1]
|
| 287 |
+
ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
|
| 288 |
+
Image.register_extension(SpiderImageFile.format, ext)
|
| 289 |
+
_save(im, fp, filename)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# --------------------------------------------------------------------
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
Image.register_open(SpiderImageFile.format, SpiderImageFile)
|
| 296 |
+
Image.register_save(SpiderImageFile.format, _save_spider)
|
| 297 |
+
|
| 298 |
+
if __name__ == "__main__":
|
| 299 |
+
if len(sys.argv) < 2:
|
| 300 |
+
print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
|
| 301 |
+
sys.exit()
|
| 302 |
+
|
| 303 |
+
filename = sys.argv[1]
|
| 304 |
+
if not isSpiderImage(filename):
|
| 305 |
+
print("input image must be in Spider format")
|
| 306 |
+
sys.exit()
|
| 307 |
+
|
| 308 |
+
with Image.open(filename) as im:
|
| 309 |
+
print(f"image: {im}")
|
| 310 |
+
print(f"format: {im.format}")
|
| 311 |
+
print(f"size: {im.size}")
|
| 312 |
+
print(f"mode: {im.mode}")
|
| 313 |
+
print("max, min: ", end=" ")
|
| 314 |
+
print(im.getextrema())
|
| 315 |
+
|
| 316 |
+
if len(sys.argv) > 2:
|
| 317 |
+
outfile = sys.argv[2]
|
| 318 |
+
|
| 319 |
+
# perform some image operation
|
| 320 |
+
im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
| 321 |
+
print(
|
| 322 |
+
f"saving a flipped version of {os.path.basename(filename)} "
|
| 323 |
+
f"as {outfile} "
|
| 324 |
+
)
|
| 325 |
+
im.save(outfile, SpiderImageFile.format)
|
valley/lib/python3.10/site-packages/PIL/SunImagePlugin.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Sun image file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-09-10 fl Created
|
| 9 |
+
# 1996-05-28 fl Fixed 32-bit alignment
|
| 10 |
+
# 1998-12-29 fl Import ImagePalette module
|
| 11 |
+
# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault)
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
| 14 |
+
# Copyright (c) 1995-1996 by Fredrik Lundh
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from . import Image, ImageFile, ImagePalette
|
| 21 |
+
from ._binary import i32be as i32
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _accept(prefix: bytes) -> bool:
|
| 25 |
+
return len(prefix) >= 4 and i32(prefix) == 0x59A66A95
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
##
|
| 29 |
+
# Image plugin for Sun raster files.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SunImageFile(ImageFile.ImageFile):
|
| 33 |
+
format = "SUN"
|
| 34 |
+
format_description = "Sun Raster File"
|
| 35 |
+
|
| 36 |
+
def _open(self) -> None:
|
| 37 |
+
# The Sun Raster file header is 32 bytes in length
|
| 38 |
+
# and has the following format:
|
| 39 |
+
|
| 40 |
+
# typedef struct _SunRaster
|
| 41 |
+
# {
|
| 42 |
+
# DWORD MagicNumber; /* Magic (identification) number */
|
| 43 |
+
# DWORD Width; /* Width of image in pixels */
|
| 44 |
+
# DWORD Height; /* Height of image in pixels */
|
| 45 |
+
# DWORD Depth; /* Number of bits per pixel */
|
| 46 |
+
# DWORD Length; /* Size of image data in bytes */
|
| 47 |
+
# DWORD Type; /* Type of raster file */
|
| 48 |
+
# DWORD ColorMapType; /* Type of color map */
|
| 49 |
+
# DWORD ColorMapLength; /* Size of the color map in bytes */
|
| 50 |
+
# } SUNRASTER;
|
| 51 |
+
|
| 52 |
+
assert self.fp is not None
|
| 53 |
+
|
| 54 |
+
# HEAD
|
| 55 |
+
s = self.fp.read(32)
|
| 56 |
+
if not _accept(s):
|
| 57 |
+
msg = "not an SUN raster file"
|
| 58 |
+
raise SyntaxError(msg)
|
| 59 |
+
|
| 60 |
+
offset = 32
|
| 61 |
+
|
| 62 |
+
self._size = i32(s, 4), i32(s, 8)
|
| 63 |
+
|
| 64 |
+
depth = i32(s, 12)
|
| 65 |
+
# data_length = i32(s, 16) # unreliable, ignore.
|
| 66 |
+
file_type = i32(s, 20)
|
| 67 |
+
palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary
|
| 68 |
+
palette_length = i32(s, 28)
|
| 69 |
+
|
| 70 |
+
if depth == 1:
|
| 71 |
+
self._mode, rawmode = "1", "1;I"
|
| 72 |
+
elif depth == 4:
|
| 73 |
+
self._mode, rawmode = "L", "L;4"
|
| 74 |
+
elif depth == 8:
|
| 75 |
+
self._mode = rawmode = "L"
|
| 76 |
+
elif depth == 24:
|
| 77 |
+
if file_type == 3:
|
| 78 |
+
self._mode, rawmode = "RGB", "RGB"
|
| 79 |
+
else:
|
| 80 |
+
self._mode, rawmode = "RGB", "BGR"
|
| 81 |
+
elif depth == 32:
|
| 82 |
+
if file_type == 3:
|
| 83 |
+
self._mode, rawmode = "RGB", "RGBX"
|
| 84 |
+
else:
|
| 85 |
+
self._mode, rawmode = "RGB", "BGRX"
|
| 86 |
+
else:
|
| 87 |
+
msg = "Unsupported Mode/Bit Depth"
|
| 88 |
+
raise SyntaxError(msg)
|
| 89 |
+
|
| 90 |
+
if palette_length:
|
| 91 |
+
if palette_length > 1024:
|
| 92 |
+
msg = "Unsupported Color Palette Length"
|
| 93 |
+
raise SyntaxError(msg)
|
| 94 |
+
|
| 95 |
+
if palette_type != 1:
|
| 96 |
+
msg = "Unsupported Palette Type"
|
| 97 |
+
raise SyntaxError(msg)
|
| 98 |
+
|
| 99 |
+
offset = offset + palette_length
|
| 100 |
+
self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))
|
| 101 |
+
if self.mode == "L":
|
| 102 |
+
self._mode = "P"
|
| 103 |
+
rawmode = rawmode.replace("L", "P")
|
| 104 |
+
|
| 105 |
+
# 16 bit boundaries on stride
|
| 106 |
+
stride = ((self.size[0] * depth + 15) // 16) * 2
|
| 107 |
+
|
| 108 |
+
# file type: Type is the version (or flavor) of the bitmap
|
| 109 |
+
# file. The following values are typically found in the Type
|
| 110 |
+
# field:
|
| 111 |
+
# 0000h Old
|
| 112 |
+
# 0001h Standard
|
| 113 |
+
# 0002h Byte-encoded
|
| 114 |
+
# 0003h RGB format
|
| 115 |
+
# 0004h TIFF format
|
| 116 |
+
# 0005h IFF format
|
| 117 |
+
# FFFFh Experimental
|
| 118 |
+
|
| 119 |
+
# Old and standard are the same, except for the length tag.
|
| 120 |
+
# byte-encoded is run-length-encoded
|
| 121 |
+
# RGB looks similar to standard, but RGB byte order
|
| 122 |
+
# TIFF and IFF mean that they were converted from T/IFF
|
| 123 |
+
# Experimental means that it's something else.
|
| 124 |
+
# (https://www.fileformat.info/format/sunraster/egff.htm)
|
| 125 |
+
|
| 126 |
+
if file_type in (0, 1, 3, 4, 5):
|
| 127 |
+
self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, stride))]
|
| 128 |
+
elif file_type == 2:
|
| 129 |
+
self.tile = [("sun_rle", (0, 0) + self.size, offset, rawmode)]
|
| 130 |
+
else:
|
| 131 |
+
msg = "Unsupported Sun Raster file type"
|
| 132 |
+
raise SyntaxError(msg)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
#
|
| 136 |
+
# registry
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
Image.register_open(SunImageFile.format, SunImageFile, _accept)
|
| 140 |
+
|
| 141 |
+
Image.register_extension(SunImageFile.format, ".ras")
|