Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .venv/lib/python3.11/site-packages/PIL/BdfFontFile.py +133 -0
- .venv/lib/python3.11/site-packages/PIL/BmpImagePlugin.py +489 -0
- .venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py +76 -0
- .venv/lib/python3.11/site-packages/PIL/ContainerIO.py +121 -0
- .venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py +75 -0
- .venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py +80 -0
- .venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py +575 -0
- .venv/lib/python3.11/site-packages/PIL/ExifTags.py +381 -0
- .venv/lib/python3.11/site-packages/PIL/FontFile.py +134 -0
- .venv/lib/python3.11/site-packages/PIL/FpxImagePlugin.py +255 -0
- .venv/lib/python3.11/site-packages/PIL/GifImagePlugin.py +1159 -0
- .venv/lib/python3.11/site-packages/PIL/IcnsImagePlugin.py +399 -0
- .venv/lib/python3.11/site-packages/PIL/Image.py +0 -0
- .venv/lib/python3.11/site-packages/PIL/ImageCms.py +1127 -0
- .venv/lib/python3.11/site-packages/PIL/ImageColor.py +320 -0
- .venv/lib/python3.11/site-packages/PIL/ImageEnhance.py +107 -0
- .venv/lib/python3.11/site-packages/PIL/ImageFile.py +810 -0
- .venv/lib/python3.11/site-packages/PIL/ImageFilter.py +604 -0
- .venv/lib/python3.11/site-packages/PIL/ImageFont.py +1290 -0
- .venv/lib/python3.11/site-packages/PIL/ImageMode.py +92 -0
- .venv/lib/python3.11/site-packages/PIL/ImagePath.py +20 -0
- .venv/lib/python3.11/site-packages/PIL/ImageShow.py +363 -0
- .venv/lib/python3.11/site-packages/PIL/ImageStat.py +160 -0
- .venv/lib/python3.11/site-packages/PIL/ImageTk.py +284 -0
- .venv/lib/python3.11/site-packages/PIL/ImageTransform.py +135 -0
- .venv/lib/python3.11/site-packages/PIL/ImageWin.py +238 -0
- .venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py +103 -0
- .venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py +408 -0
- .venv/lib/python3.11/site-packages/PIL/JpegPresets.py +242 -0
- .venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py +78 -0
- .venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py +180 -0
- .venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py +200 -0
- .venv/lib/python3.11/site-packages/PIL/PaletteFile.py +54 -0
- .venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py +229 -0
- .venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py +227 -0
- .venv/lib/python3.11/site-packages/PIL/PdfImagePlugin.py +304 -0
- .venv/lib/python3.11/site-packages/PIL/PdfParser.py +1003 -0
- .venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py +72 -0
- .venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py +1489 -0
- .venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py +371 -0
- .venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py +326 -0
- .venv/lib/python3.11/site-packages/PIL/PyAccess.py +381 -0
- .venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py +115 -0
- .venv/lib/python3.11/site-packages/PIL/SgiImagePlugin.py +238 -0
- .venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py +262 -0
- .venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py +2200 -0
- .venv/lib/python3.11/site-packages/PIL/TiffTags.py +555 -0
- .venv/lib/python3.11/site-packages/PIL/WalImageFile.py +124 -0
- .venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py +363 -0
- .venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py +181 -0
.venv/lib/python3.11/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
|
.venv/lib/python3.11/site-packages/PIL/BmpImagePlugin.py
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# BMP file handler
|
| 6 |
+
#
|
| 7 |
+
# Windows (and OS/2) native bitmap storage format.
|
| 8 |
+
#
|
| 9 |
+
# history:
|
| 10 |
+
# 1995-09-01 fl Created
|
| 11 |
+
# 1996-04-30 fl Added save
|
| 12 |
+
# 1997-08-27 fl Fixed save of 1-bit images
|
| 13 |
+
# 1998-03-06 fl Load P images as L where possible
|
| 14 |
+
# 1998-07-03 fl Load P images as 1 where possible
|
| 15 |
+
# 1998-12-29 fl Handle small palettes
|
| 16 |
+
# 2002-12-30 fl Fixed load of 1-bit palette images
|
| 17 |
+
# 2003-04-21 fl Fixed load of 1-bit monochrome images
|
| 18 |
+
# 2003-04-23 fl Added limited support for BI_BITFIELDS compression
|
| 19 |
+
#
|
| 20 |
+
# Copyright (c) 1997-2003 by Secret Labs AB
|
| 21 |
+
# Copyright (c) 1995-2003 by Fredrik Lundh
|
| 22 |
+
#
|
| 23 |
+
# See the README file for information on usage and redistribution.
|
| 24 |
+
#
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import os
|
| 28 |
+
from typing import IO
|
| 29 |
+
|
| 30 |
+
from . import Image, ImageFile, ImagePalette
|
| 31 |
+
from ._binary import i16le as i16
|
| 32 |
+
from ._binary import i32le as i32
|
| 33 |
+
from ._binary import o8
|
| 34 |
+
from ._binary import o16le as o16
|
| 35 |
+
from ._binary import o32le as o32
|
| 36 |
+
|
| 37 |
+
#
|
| 38 |
+
# --------------------------------------------------------------------
|
| 39 |
+
# Read BMP file
|
| 40 |
+
|
| 41 |
+
BIT2MODE = {
|
| 42 |
+
# bits => mode, rawmode
|
| 43 |
+
1: ("P", "P;1"),
|
| 44 |
+
4: ("P", "P;4"),
|
| 45 |
+
8: ("P", "P"),
|
| 46 |
+
16: ("RGB", "BGR;15"),
|
| 47 |
+
24: ("RGB", "BGR"),
|
| 48 |
+
32: ("RGB", "BGRX"),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _accept(prefix: bytes) -> bool:
|
| 53 |
+
return prefix[:2] == b"BM"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _dib_accept(prefix: bytes) -> bool:
|
| 57 |
+
return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# =============================================================================
|
| 61 |
+
# Image plugin for the Windows BMP format.
|
| 62 |
+
# =============================================================================
|
| 63 |
+
class BmpImageFile(ImageFile.ImageFile):
|
| 64 |
+
"""Image plugin for the Windows Bitmap format (BMP)"""
|
| 65 |
+
|
| 66 |
+
# ------------------------------------------------------------- Description
|
| 67 |
+
format_description = "Windows Bitmap"
|
| 68 |
+
format = "BMP"
|
| 69 |
+
|
| 70 |
+
# -------------------------------------------------- BMP Compression values
|
| 71 |
+
COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
|
| 72 |
+
for k, v in COMPRESSIONS.items():
|
| 73 |
+
vars()[k] = v
|
| 74 |
+
|
| 75 |
+
def _bitmap(self, header=0, offset=0):
|
| 76 |
+
"""Read relevant info about the BMP"""
|
| 77 |
+
read, seek = self.fp.read, self.fp.seek
|
| 78 |
+
if header:
|
| 79 |
+
seek(header)
|
| 80 |
+
# read bmp header size @offset 14 (this is part of the header size)
|
| 81 |
+
file_info = {"header_size": i32(read(4)), "direction": -1}
|
| 82 |
+
|
| 83 |
+
# -------------------- If requested, read header at a specific position
|
| 84 |
+
# read the rest of the bmp header, without its size
|
| 85 |
+
header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
|
| 86 |
+
|
| 87 |
+
# ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
|
| 88 |
+
# ----- This format has different offsets because of width/height types
|
| 89 |
+
# 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
|
| 90 |
+
if file_info["header_size"] == 12:
|
| 91 |
+
file_info["width"] = i16(header_data, 0)
|
| 92 |
+
file_info["height"] = i16(header_data, 2)
|
| 93 |
+
file_info["planes"] = i16(header_data, 4)
|
| 94 |
+
file_info["bits"] = i16(header_data, 6)
|
| 95 |
+
file_info["compression"] = self.RAW
|
| 96 |
+
file_info["palette_padding"] = 3
|
| 97 |
+
|
| 98 |
+
# --------------------------------------------- Windows Bitmap v3 to v5
|
| 99 |
+
# 40: BITMAPINFOHEADER
|
| 100 |
+
# 52: BITMAPV2HEADER
|
| 101 |
+
# 56: BITMAPV3HEADER
|
| 102 |
+
# 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
|
| 103 |
+
# 108: BITMAPV4HEADER
|
| 104 |
+
# 124: BITMAPV5HEADER
|
| 105 |
+
elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
|
| 106 |
+
file_info["y_flip"] = header_data[7] == 0xFF
|
| 107 |
+
file_info["direction"] = 1 if file_info["y_flip"] else -1
|
| 108 |
+
file_info["width"] = i32(header_data, 0)
|
| 109 |
+
file_info["height"] = (
|
| 110 |
+
i32(header_data, 4)
|
| 111 |
+
if not file_info["y_flip"]
|
| 112 |
+
else 2**32 - i32(header_data, 4)
|
| 113 |
+
)
|
| 114 |
+
file_info["planes"] = i16(header_data, 8)
|
| 115 |
+
file_info["bits"] = i16(header_data, 10)
|
| 116 |
+
file_info["compression"] = i32(header_data, 12)
|
| 117 |
+
# byte size of pixel data
|
| 118 |
+
file_info["data_size"] = i32(header_data, 16)
|
| 119 |
+
file_info["pixels_per_meter"] = (
|
| 120 |
+
i32(header_data, 20),
|
| 121 |
+
i32(header_data, 24),
|
| 122 |
+
)
|
| 123 |
+
file_info["colors"] = i32(header_data, 28)
|
| 124 |
+
file_info["palette_padding"] = 4
|
| 125 |
+
self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
|
| 126 |
+
if file_info["compression"] == self.BITFIELDS:
|
| 127 |
+
masks = ["r_mask", "g_mask", "b_mask"]
|
| 128 |
+
if len(header_data) >= 48:
|
| 129 |
+
if len(header_data) >= 52:
|
| 130 |
+
masks.append("a_mask")
|
| 131 |
+
else:
|
| 132 |
+
file_info["a_mask"] = 0x0
|
| 133 |
+
for idx, mask in enumerate(masks):
|
| 134 |
+
file_info[mask] = i32(header_data, 36 + idx * 4)
|
| 135 |
+
else:
|
| 136 |
+
# 40 byte headers only have the three components in the
|
| 137 |
+
# bitfields masks, ref:
|
| 138 |
+
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
|
| 139 |
+
# See also
|
| 140 |
+
# https://github.com/python-pillow/Pillow/issues/1293
|
| 141 |
+
# There is a 4th component in the RGBQuad, in the alpha
|
| 142 |
+
# location, but it is listed as a reserved component,
|
| 143 |
+
# and it is not generally an alpha channel
|
| 144 |
+
file_info["a_mask"] = 0x0
|
| 145 |
+
for mask in masks:
|
| 146 |
+
file_info[mask] = i32(read(4))
|
| 147 |
+
file_info["rgb_mask"] = (
|
| 148 |
+
file_info["r_mask"],
|
| 149 |
+
file_info["g_mask"],
|
| 150 |
+
file_info["b_mask"],
|
| 151 |
+
)
|
| 152 |
+
file_info["rgba_mask"] = (
|
| 153 |
+
file_info["r_mask"],
|
| 154 |
+
file_info["g_mask"],
|
| 155 |
+
file_info["b_mask"],
|
| 156 |
+
file_info["a_mask"],
|
| 157 |
+
)
|
| 158 |
+
else:
|
| 159 |
+
msg = f"Unsupported BMP header type ({file_info['header_size']})"
|
| 160 |
+
raise OSError(msg)
|
| 161 |
+
|
| 162 |
+
# ------------------ Special case : header is reported 40, which
|
| 163 |
+
# ---------------------- is shorter than real size for bpp >= 16
|
| 164 |
+
self._size = file_info["width"], file_info["height"]
|
| 165 |
+
|
| 166 |
+
# ------- If color count was not found in the header, compute from bits
|
| 167 |
+
file_info["colors"] = (
|
| 168 |
+
file_info["colors"]
|
| 169 |
+
if file_info.get("colors", 0)
|
| 170 |
+
else (1 << file_info["bits"])
|
| 171 |
+
)
|
| 172 |
+
if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
|
| 173 |
+
offset += 4 * file_info["colors"]
|
| 174 |
+
|
| 175 |
+
# ---------------------- Check bit depth for unusual unsupported values
|
| 176 |
+
self._mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
|
| 177 |
+
if self.mode is None:
|
| 178 |
+
msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
|
| 179 |
+
raise OSError(msg)
|
| 180 |
+
|
| 181 |
+
# ---------------- Process BMP with Bitfields compression (not palette)
|
| 182 |
+
decoder_name = "raw"
|
| 183 |
+
if file_info["compression"] == self.BITFIELDS:
|
| 184 |
+
SUPPORTED = {
|
| 185 |
+
32: [
|
| 186 |
+
(0xFF0000, 0xFF00, 0xFF, 0x0),
|
| 187 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0x0),
|
| 188 |
+
(0xFF000000, 0xFF00, 0xFF, 0x0),
|
| 189 |
+
(0xFF000000, 0xFF0000, 0xFF00, 0xFF),
|
| 190 |
+
(0xFF, 0xFF00, 0xFF0000, 0xFF000000),
|
| 191 |
+
(0xFF0000, 0xFF00, 0xFF, 0xFF000000),
|
| 192 |
+
(0xFF000000, 0xFF00, 0xFF, 0xFF0000),
|
| 193 |
+
(0x0, 0x0, 0x0, 0x0),
|
| 194 |
+
],
|
| 195 |
+
24: [(0xFF0000, 0xFF00, 0xFF)],
|
| 196 |
+
16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
|
| 197 |
+
}
|
| 198 |
+
MASK_MODES = {
|
| 199 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
|
| 200 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
|
| 201 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
|
| 202 |
+
(32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
|
| 203 |
+
(32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
|
| 204 |
+
(32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
|
| 205 |
+
(32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
|
| 206 |
+
(32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
|
| 207 |
+
(24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
|
| 208 |
+
(16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
|
| 209 |
+
(16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
|
| 210 |
+
}
|
| 211 |
+
if file_info["bits"] in SUPPORTED:
|
| 212 |
+
if (
|
| 213 |
+
file_info["bits"] == 32
|
| 214 |
+
and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
|
| 215 |
+
):
|
| 216 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
|
| 217 |
+
self._mode = "RGBA" if "A" in raw_mode else self.mode
|
| 218 |
+
elif (
|
| 219 |
+
file_info["bits"] in (24, 16)
|
| 220 |
+
and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
|
| 221 |
+
):
|
| 222 |
+
raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
|
| 223 |
+
else:
|
| 224 |
+
msg = "Unsupported BMP bitfields layout"
|
| 225 |
+
raise OSError(msg)
|
| 226 |
+
else:
|
| 227 |
+
msg = "Unsupported BMP bitfields layout"
|
| 228 |
+
raise OSError(msg)
|
| 229 |
+
elif file_info["compression"] == self.RAW:
|
| 230 |
+
if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
|
| 231 |
+
raw_mode, self._mode = "BGRA", "RGBA"
|
| 232 |
+
elif file_info["compression"] in (self.RLE8, self.RLE4):
|
| 233 |
+
decoder_name = "bmp_rle"
|
| 234 |
+
else:
|
| 235 |
+
msg = f"Unsupported BMP compression ({file_info['compression']})"
|
| 236 |
+
raise OSError(msg)
|
| 237 |
+
|
| 238 |
+
# --------------- Once the header is processed, process the palette/LUT
|
| 239 |
+
if self.mode == "P": # Paletted for 1, 4 and 8 bit images
|
| 240 |
+
# ---------------------------------------------------- 1-bit images
|
| 241 |
+
if not (0 < file_info["colors"] <= 65536):
|
| 242 |
+
msg = f"Unsupported BMP Palette size ({file_info['colors']})"
|
| 243 |
+
raise OSError(msg)
|
| 244 |
+
else:
|
| 245 |
+
padding = file_info["palette_padding"]
|
| 246 |
+
palette = read(padding * file_info["colors"])
|
| 247 |
+
grayscale = True
|
| 248 |
+
indices = (
|
| 249 |
+
(0, 255)
|
| 250 |
+
if file_info["colors"] == 2
|
| 251 |
+
else list(range(file_info["colors"]))
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# ----------------- Check if grayscale and ignore palette if so
|
| 255 |
+
for ind, val in enumerate(indices):
|
| 256 |
+
rgb = palette[ind * padding : ind * padding + 3]
|
| 257 |
+
if rgb != o8(val) * 3:
|
| 258 |
+
grayscale = False
|
| 259 |
+
|
| 260 |
+
# ------- If all colors are gray, white or black, ditch palette
|
| 261 |
+
if grayscale:
|
| 262 |
+
self._mode = "1" if file_info["colors"] == 2 else "L"
|
| 263 |
+
raw_mode = self.mode
|
| 264 |
+
else:
|
| 265 |
+
self._mode = "P"
|
| 266 |
+
self.palette = ImagePalette.raw(
|
| 267 |
+
"BGRX" if padding == 4 else "BGR", palette
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# ---------------------------- Finally set the tile data for the plugin
|
| 271 |
+
self.info["compression"] = file_info["compression"]
|
| 272 |
+
args = [raw_mode]
|
| 273 |
+
if decoder_name == "bmp_rle":
|
| 274 |
+
args.append(file_info["compression"] == self.RLE4)
|
| 275 |
+
else:
|
| 276 |
+
args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
|
| 277 |
+
args.append(file_info["direction"])
|
| 278 |
+
self.tile = [
|
| 279 |
+
(
|
| 280 |
+
decoder_name,
|
| 281 |
+
(0, 0, file_info["width"], file_info["height"]),
|
| 282 |
+
offset or self.fp.tell(),
|
| 283 |
+
tuple(args),
|
| 284 |
+
)
|
| 285 |
+
]
|
| 286 |
+
|
| 287 |
+
def _open(self) -> None:
|
| 288 |
+
"""Open file, check magic number and read header"""
|
| 289 |
+
# read 14 bytes: magic number, filesize, reserved, header final offset
|
| 290 |
+
head_data = self.fp.read(14)
|
| 291 |
+
# choke if the file does not have the required magic bytes
|
| 292 |
+
if not _accept(head_data):
|
| 293 |
+
msg = "Not a BMP file"
|
| 294 |
+
raise SyntaxError(msg)
|
| 295 |
+
# read the start position of the BMP image data (u32)
|
| 296 |
+
offset = i32(head_data, 10)
|
| 297 |
+
# load bitmap information (offset=raster info)
|
| 298 |
+
self._bitmap(offset=offset)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class BmpRleDecoder(ImageFile.PyDecoder):
|
| 302 |
+
_pulls_fd = True
|
| 303 |
+
|
| 304 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 305 |
+
assert self.fd is not None
|
| 306 |
+
rle4 = self.args[1]
|
| 307 |
+
data = bytearray()
|
| 308 |
+
x = 0
|
| 309 |
+
dest_length = self.state.xsize * self.state.ysize
|
| 310 |
+
while len(data) < dest_length:
|
| 311 |
+
pixels = self.fd.read(1)
|
| 312 |
+
byte = self.fd.read(1)
|
| 313 |
+
if not pixels or not byte:
|
| 314 |
+
break
|
| 315 |
+
num_pixels = pixels[0]
|
| 316 |
+
if num_pixels:
|
| 317 |
+
# encoded mode
|
| 318 |
+
if x + num_pixels > self.state.xsize:
|
| 319 |
+
# Too much data for row
|
| 320 |
+
num_pixels = max(0, self.state.xsize - x)
|
| 321 |
+
if rle4:
|
| 322 |
+
first_pixel = o8(byte[0] >> 4)
|
| 323 |
+
second_pixel = o8(byte[0] & 0x0F)
|
| 324 |
+
for index in range(num_pixels):
|
| 325 |
+
if index % 2 == 0:
|
| 326 |
+
data += first_pixel
|
| 327 |
+
else:
|
| 328 |
+
data += second_pixel
|
| 329 |
+
else:
|
| 330 |
+
data += byte * num_pixels
|
| 331 |
+
x += num_pixels
|
| 332 |
+
else:
|
| 333 |
+
if byte[0] == 0:
|
| 334 |
+
# end of line
|
| 335 |
+
while len(data) % self.state.xsize != 0:
|
| 336 |
+
data += b"\x00"
|
| 337 |
+
x = 0
|
| 338 |
+
elif byte[0] == 1:
|
| 339 |
+
# end of bitmap
|
| 340 |
+
break
|
| 341 |
+
elif byte[0] == 2:
|
| 342 |
+
# delta
|
| 343 |
+
bytes_read = self.fd.read(2)
|
| 344 |
+
if len(bytes_read) < 2:
|
| 345 |
+
break
|
| 346 |
+
right, up = self.fd.read(2)
|
| 347 |
+
data += b"\x00" * (right + up * self.state.xsize)
|
| 348 |
+
x = len(data) % self.state.xsize
|
| 349 |
+
else:
|
| 350 |
+
# absolute mode
|
| 351 |
+
if rle4:
|
| 352 |
+
# 2 pixels per byte
|
| 353 |
+
byte_count = byte[0] // 2
|
| 354 |
+
bytes_read = self.fd.read(byte_count)
|
| 355 |
+
for byte_read in bytes_read:
|
| 356 |
+
data += o8(byte_read >> 4)
|
| 357 |
+
data += o8(byte_read & 0x0F)
|
| 358 |
+
else:
|
| 359 |
+
byte_count = byte[0]
|
| 360 |
+
bytes_read = self.fd.read(byte_count)
|
| 361 |
+
data += bytes_read
|
| 362 |
+
if len(bytes_read) < byte_count:
|
| 363 |
+
break
|
| 364 |
+
x += byte[0]
|
| 365 |
+
|
| 366 |
+
# align to 16-bit word boundary
|
| 367 |
+
if self.fd.tell() % 2 != 0:
|
| 368 |
+
self.fd.seek(1, os.SEEK_CUR)
|
| 369 |
+
rawmode = "L" if self.mode == "L" else "P"
|
| 370 |
+
self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
|
| 371 |
+
return -1, 0
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# =============================================================================
|
| 375 |
+
# Image plugin for the DIB format (BMP alias)
|
| 376 |
+
# =============================================================================
|
| 377 |
+
class DibImageFile(BmpImageFile):
|
| 378 |
+
format = "DIB"
|
| 379 |
+
format_description = "Windows Bitmap"
|
| 380 |
+
|
| 381 |
+
def _open(self) -> None:
|
| 382 |
+
self._bitmap()
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
#
|
| 386 |
+
# --------------------------------------------------------------------
|
| 387 |
+
# Write BMP file
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
SAVE = {
|
| 391 |
+
"1": ("1", 1, 2),
|
| 392 |
+
"L": ("L", 8, 256),
|
| 393 |
+
"P": ("P", 8, 256),
|
| 394 |
+
"RGB": ("BGR", 24, 0),
|
| 395 |
+
"RGBA": ("BGRA", 32, 0),
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 400 |
+
_save(im, fp, filename, False)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def _save(
|
| 404 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
|
| 405 |
+
) -> None:
|
| 406 |
+
try:
|
| 407 |
+
rawmode, bits, colors = SAVE[im.mode]
|
| 408 |
+
except KeyError as e:
|
| 409 |
+
msg = f"cannot write mode {im.mode} as BMP"
|
| 410 |
+
raise OSError(msg) from e
|
| 411 |
+
|
| 412 |
+
info = im.encoderinfo
|
| 413 |
+
|
| 414 |
+
dpi = info.get("dpi", (96, 96))
|
| 415 |
+
|
| 416 |
+
# 1 meter == 39.3701 inches
|
| 417 |
+
ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
|
| 418 |
+
|
| 419 |
+
stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
|
| 420 |
+
header = 40 # or 64 for OS/2 version 2
|
| 421 |
+
image = stride * im.size[1]
|
| 422 |
+
|
| 423 |
+
if im.mode == "1":
|
| 424 |
+
palette = b"".join(o8(i) * 4 for i in (0, 255))
|
| 425 |
+
elif im.mode == "L":
|
| 426 |
+
palette = b"".join(o8(i) * 4 for i in range(256))
|
| 427 |
+
elif im.mode == "P":
|
| 428 |
+
palette = im.im.getpalette("RGB", "BGRX")
|
| 429 |
+
colors = len(palette) // 4
|
| 430 |
+
else:
|
| 431 |
+
palette = None
|
| 432 |
+
|
| 433 |
+
# bitmap header
|
| 434 |
+
if bitmap_header:
|
| 435 |
+
offset = 14 + header + colors * 4
|
| 436 |
+
file_size = offset + image
|
| 437 |
+
if file_size > 2**32 - 1:
|
| 438 |
+
msg = "File size is too large for the BMP format"
|
| 439 |
+
raise ValueError(msg)
|
| 440 |
+
fp.write(
|
| 441 |
+
b"BM" # file type (magic)
|
| 442 |
+
+ o32(file_size) # file size
|
| 443 |
+
+ o32(0) # reserved
|
| 444 |
+
+ o32(offset) # image data offset
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
# bitmap info header
|
| 448 |
+
fp.write(
|
| 449 |
+
o32(header) # info header size
|
| 450 |
+
+ o32(im.size[0]) # width
|
| 451 |
+
+ o32(im.size[1]) # height
|
| 452 |
+
+ o16(1) # planes
|
| 453 |
+
+ o16(bits) # depth
|
| 454 |
+
+ o32(0) # compression (0=uncompressed)
|
| 455 |
+
+ o32(image) # size of bitmap
|
| 456 |
+
+ o32(ppm[0]) # resolution
|
| 457 |
+
+ o32(ppm[1]) # resolution
|
| 458 |
+
+ o32(colors) # colors used
|
| 459 |
+
+ o32(colors) # colors important
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
|
| 463 |
+
|
| 464 |
+
if palette:
|
| 465 |
+
fp.write(palette)
|
| 466 |
+
|
| 467 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
#
|
| 471 |
+
# --------------------------------------------------------------------
|
| 472 |
+
# Registry
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
|
| 476 |
+
Image.register_save(BmpImageFile.format, _save)
|
| 477 |
+
|
| 478 |
+
Image.register_extension(BmpImageFile.format, ".bmp")
|
| 479 |
+
|
| 480 |
+
Image.register_mime(BmpImageFile.format, "image/bmp")
|
| 481 |
+
|
| 482 |
+
Image.register_decoder("bmp_rle", BmpRleDecoder)
|
| 483 |
+
|
| 484 |
+
Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
|
| 485 |
+
Image.register_save(DibImageFile.format, _dib_save)
|
| 486 |
+
|
| 487 |
+
Image.register_extension(DibImageFile.format, ".dib")
|
| 488 |
+
|
| 489 |
+
Image.register_mime(DibImageFile.format, "image/bmp")
|
.venv/lib/python3.11/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")
|
.venv/lib/python3.11/site-packages/PIL/ContainerIO.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# a class to read from a container file
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-06-18 fl Created
|
| 9 |
+
# 1995-09-07 fl Added readline(), readlines()
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 1997-2001 by Secret Labs AB
|
| 12 |
+
# Copyright (c) 1995 by Fredrik Lundh
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
from typing import IO, AnyStr, Generic, Literal
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ContainerIO(Generic[AnyStr]):
|
| 23 |
+
"""
|
| 24 |
+
A file object that provides read access to a part of an existing
|
| 25 |
+
file (for example a TAR file).
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
|
| 29 |
+
"""
|
| 30 |
+
Create file object.
|
| 31 |
+
|
| 32 |
+
:param file: Existing file.
|
| 33 |
+
:param offset: Start of region, in bytes.
|
| 34 |
+
:param length: Size of region, in bytes.
|
| 35 |
+
"""
|
| 36 |
+
self.fh: IO[AnyStr] = file
|
| 37 |
+
self.pos = 0
|
| 38 |
+
self.offset = offset
|
| 39 |
+
self.length = length
|
| 40 |
+
self.fh.seek(offset)
|
| 41 |
+
|
| 42 |
+
##
|
| 43 |
+
# Always false.
|
| 44 |
+
|
| 45 |
+
def isatty(self) -> bool:
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
def seek(self, offset: int, mode: Literal[0, 1, 2] = io.SEEK_SET) -> None:
|
| 49 |
+
"""
|
| 50 |
+
Move file pointer.
|
| 51 |
+
|
| 52 |
+
:param offset: Offset in bytes.
|
| 53 |
+
:param mode: Starting position. Use 0 for beginning of region, 1
|
| 54 |
+
for current offset, and 2 for end of region. You cannot move
|
| 55 |
+
the pointer outside the defined region.
|
| 56 |
+
"""
|
| 57 |
+
if mode == 1:
|
| 58 |
+
self.pos = self.pos + offset
|
| 59 |
+
elif mode == 2:
|
| 60 |
+
self.pos = self.length + offset
|
| 61 |
+
else:
|
| 62 |
+
self.pos = offset
|
| 63 |
+
# clamp
|
| 64 |
+
self.pos = max(0, min(self.pos, self.length))
|
| 65 |
+
self.fh.seek(self.offset + self.pos)
|
| 66 |
+
|
| 67 |
+
def tell(self) -> int:
|
| 68 |
+
"""
|
| 69 |
+
Get current file pointer.
|
| 70 |
+
|
| 71 |
+
:returns: Offset from start of region, in bytes.
|
| 72 |
+
"""
|
| 73 |
+
return self.pos
|
| 74 |
+
|
| 75 |
+
def read(self, n: int = 0) -> AnyStr:
|
| 76 |
+
"""
|
| 77 |
+
Read data.
|
| 78 |
+
|
| 79 |
+
:param n: Number of bytes to read. If omitted or zero,
|
| 80 |
+
read until end of region.
|
| 81 |
+
:returns: An 8-bit string.
|
| 82 |
+
"""
|
| 83 |
+
if n:
|
| 84 |
+
n = min(n, self.length - self.pos)
|
| 85 |
+
else:
|
| 86 |
+
n = self.length - self.pos
|
| 87 |
+
if not n: # EOF
|
| 88 |
+
return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
|
| 89 |
+
self.pos = self.pos + n
|
| 90 |
+
return self.fh.read(n)
|
| 91 |
+
|
| 92 |
+
def readline(self) -> AnyStr:
|
| 93 |
+
"""
|
| 94 |
+
Read a line of text.
|
| 95 |
+
|
| 96 |
+
:returns: An 8-bit string.
|
| 97 |
+
"""
|
| 98 |
+
s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
|
| 99 |
+
newline_character = b"\n" if "b" in self.fh.mode else "\n"
|
| 100 |
+
while True:
|
| 101 |
+
c = self.read(1)
|
| 102 |
+
if not c:
|
| 103 |
+
break
|
| 104 |
+
s = s + c
|
| 105 |
+
if c == newline_character:
|
| 106 |
+
break
|
| 107 |
+
return s
|
| 108 |
+
|
| 109 |
+
def readlines(self) -> list[AnyStr]:
|
| 110 |
+
"""
|
| 111 |
+
Read multiple lines of text.
|
| 112 |
+
|
| 113 |
+
:returns: A list of 8-bit strings.
|
| 114 |
+
"""
|
| 115 |
+
lines = []
|
| 116 |
+
while True:
|
| 117 |
+
s = self.readline()
|
| 118 |
+
if not s:
|
| 119 |
+
break
|
| 120 |
+
lines.append(s)
|
| 121 |
+
return lines
|
.venv/lib/python3.11/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")
|
.venv/lib/python3.11/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")
|
.venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ed 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")
|
.venv/lib/python3.11/site-packages/PIL/ExifTags.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# EXIF tags
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 2003 by Secret Labs AB
|
| 8 |
+
#
|
| 9 |
+
# See the README file for information on usage and redistribution.
|
| 10 |
+
#
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
This module provides constants and clear-text names for various
|
| 14 |
+
well-known EXIF tags.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from enum import IntEnum
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Base(IntEnum):
|
| 22 |
+
# possibly incomplete
|
| 23 |
+
InteropIndex = 0x0001
|
| 24 |
+
ProcessingSoftware = 0x000B
|
| 25 |
+
NewSubfileType = 0x00FE
|
| 26 |
+
SubfileType = 0x00FF
|
| 27 |
+
ImageWidth = 0x0100
|
| 28 |
+
ImageLength = 0x0101
|
| 29 |
+
BitsPerSample = 0x0102
|
| 30 |
+
Compression = 0x0103
|
| 31 |
+
PhotometricInterpretation = 0x0106
|
| 32 |
+
Thresholding = 0x0107
|
| 33 |
+
CellWidth = 0x0108
|
| 34 |
+
CellLength = 0x0109
|
| 35 |
+
FillOrder = 0x010A
|
| 36 |
+
DocumentName = 0x010D
|
| 37 |
+
ImageDescription = 0x010E
|
| 38 |
+
Make = 0x010F
|
| 39 |
+
Model = 0x0110
|
| 40 |
+
StripOffsets = 0x0111
|
| 41 |
+
Orientation = 0x0112
|
| 42 |
+
SamplesPerPixel = 0x0115
|
| 43 |
+
RowsPerStrip = 0x0116
|
| 44 |
+
StripByteCounts = 0x0117
|
| 45 |
+
MinSampleValue = 0x0118
|
| 46 |
+
MaxSampleValue = 0x0119
|
| 47 |
+
XResolution = 0x011A
|
| 48 |
+
YResolution = 0x011B
|
| 49 |
+
PlanarConfiguration = 0x011C
|
| 50 |
+
PageName = 0x011D
|
| 51 |
+
FreeOffsets = 0x0120
|
| 52 |
+
FreeByteCounts = 0x0121
|
| 53 |
+
GrayResponseUnit = 0x0122
|
| 54 |
+
GrayResponseCurve = 0x0123
|
| 55 |
+
T4Options = 0x0124
|
| 56 |
+
T6Options = 0x0125
|
| 57 |
+
ResolutionUnit = 0x0128
|
| 58 |
+
PageNumber = 0x0129
|
| 59 |
+
TransferFunction = 0x012D
|
| 60 |
+
Software = 0x0131
|
| 61 |
+
DateTime = 0x0132
|
| 62 |
+
Artist = 0x013B
|
| 63 |
+
HostComputer = 0x013C
|
| 64 |
+
Predictor = 0x013D
|
| 65 |
+
WhitePoint = 0x013E
|
| 66 |
+
PrimaryChromaticities = 0x013F
|
| 67 |
+
ColorMap = 0x0140
|
| 68 |
+
HalftoneHints = 0x0141
|
| 69 |
+
TileWidth = 0x0142
|
| 70 |
+
TileLength = 0x0143
|
| 71 |
+
TileOffsets = 0x0144
|
| 72 |
+
TileByteCounts = 0x0145
|
| 73 |
+
SubIFDs = 0x014A
|
| 74 |
+
InkSet = 0x014C
|
| 75 |
+
InkNames = 0x014D
|
| 76 |
+
NumberOfInks = 0x014E
|
| 77 |
+
DotRange = 0x0150
|
| 78 |
+
TargetPrinter = 0x0151
|
| 79 |
+
ExtraSamples = 0x0152
|
| 80 |
+
SampleFormat = 0x0153
|
| 81 |
+
SMinSampleValue = 0x0154
|
| 82 |
+
SMaxSampleValue = 0x0155
|
| 83 |
+
TransferRange = 0x0156
|
| 84 |
+
ClipPath = 0x0157
|
| 85 |
+
XClipPathUnits = 0x0158
|
| 86 |
+
YClipPathUnits = 0x0159
|
| 87 |
+
Indexed = 0x015A
|
| 88 |
+
JPEGTables = 0x015B
|
| 89 |
+
OPIProxy = 0x015F
|
| 90 |
+
JPEGProc = 0x0200
|
| 91 |
+
JpegIFOffset = 0x0201
|
| 92 |
+
JpegIFByteCount = 0x0202
|
| 93 |
+
JpegRestartInterval = 0x0203
|
| 94 |
+
JpegLosslessPredictors = 0x0205
|
| 95 |
+
JpegPointTransforms = 0x0206
|
| 96 |
+
JpegQTables = 0x0207
|
| 97 |
+
JpegDCTables = 0x0208
|
| 98 |
+
JpegACTables = 0x0209
|
| 99 |
+
YCbCrCoefficients = 0x0211
|
| 100 |
+
YCbCrSubSampling = 0x0212
|
| 101 |
+
YCbCrPositioning = 0x0213
|
| 102 |
+
ReferenceBlackWhite = 0x0214
|
| 103 |
+
XMLPacket = 0x02BC
|
| 104 |
+
RelatedImageFileFormat = 0x1000
|
| 105 |
+
RelatedImageWidth = 0x1001
|
| 106 |
+
RelatedImageLength = 0x1002
|
| 107 |
+
Rating = 0x4746
|
| 108 |
+
RatingPercent = 0x4749
|
| 109 |
+
ImageID = 0x800D
|
| 110 |
+
CFARepeatPatternDim = 0x828D
|
| 111 |
+
BatteryLevel = 0x828F
|
| 112 |
+
Copyright = 0x8298
|
| 113 |
+
ExposureTime = 0x829A
|
| 114 |
+
FNumber = 0x829D
|
| 115 |
+
IPTCNAA = 0x83BB
|
| 116 |
+
ImageResources = 0x8649
|
| 117 |
+
ExifOffset = 0x8769
|
| 118 |
+
InterColorProfile = 0x8773
|
| 119 |
+
ExposureProgram = 0x8822
|
| 120 |
+
SpectralSensitivity = 0x8824
|
| 121 |
+
GPSInfo = 0x8825
|
| 122 |
+
ISOSpeedRatings = 0x8827
|
| 123 |
+
OECF = 0x8828
|
| 124 |
+
Interlace = 0x8829
|
| 125 |
+
TimeZoneOffset = 0x882A
|
| 126 |
+
SelfTimerMode = 0x882B
|
| 127 |
+
SensitivityType = 0x8830
|
| 128 |
+
StandardOutputSensitivity = 0x8831
|
| 129 |
+
RecommendedExposureIndex = 0x8832
|
| 130 |
+
ISOSpeed = 0x8833
|
| 131 |
+
ISOSpeedLatitudeyyy = 0x8834
|
| 132 |
+
ISOSpeedLatitudezzz = 0x8835
|
| 133 |
+
ExifVersion = 0x9000
|
| 134 |
+
DateTimeOriginal = 0x9003
|
| 135 |
+
DateTimeDigitized = 0x9004
|
| 136 |
+
OffsetTime = 0x9010
|
| 137 |
+
OffsetTimeOriginal = 0x9011
|
| 138 |
+
OffsetTimeDigitized = 0x9012
|
| 139 |
+
ComponentsConfiguration = 0x9101
|
| 140 |
+
CompressedBitsPerPixel = 0x9102
|
| 141 |
+
ShutterSpeedValue = 0x9201
|
| 142 |
+
ApertureValue = 0x9202
|
| 143 |
+
BrightnessValue = 0x9203
|
| 144 |
+
ExposureBiasValue = 0x9204
|
| 145 |
+
MaxApertureValue = 0x9205
|
| 146 |
+
SubjectDistance = 0x9206
|
| 147 |
+
MeteringMode = 0x9207
|
| 148 |
+
LightSource = 0x9208
|
| 149 |
+
Flash = 0x9209
|
| 150 |
+
FocalLength = 0x920A
|
| 151 |
+
Noise = 0x920D
|
| 152 |
+
ImageNumber = 0x9211
|
| 153 |
+
SecurityClassification = 0x9212
|
| 154 |
+
ImageHistory = 0x9213
|
| 155 |
+
TIFFEPStandardID = 0x9216
|
| 156 |
+
MakerNote = 0x927C
|
| 157 |
+
UserComment = 0x9286
|
| 158 |
+
SubsecTime = 0x9290
|
| 159 |
+
SubsecTimeOriginal = 0x9291
|
| 160 |
+
SubsecTimeDigitized = 0x9292
|
| 161 |
+
AmbientTemperature = 0x9400
|
| 162 |
+
Humidity = 0x9401
|
| 163 |
+
Pressure = 0x9402
|
| 164 |
+
WaterDepth = 0x9403
|
| 165 |
+
Acceleration = 0x9404
|
| 166 |
+
CameraElevationAngle = 0x9405
|
| 167 |
+
XPTitle = 0x9C9B
|
| 168 |
+
XPComment = 0x9C9C
|
| 169 |
+
XPAuthor = 0x9C9D
|
| 170 |
+
XPKeywords = 0x9C9E
|
| 171 |
+
XPSubject = 0x9C9F
|
| 172 |
+
FlashPixVersion = 0xA000
|
| 173 |
+
ColorSpace = 0xA001
|
| 174 |
+
ExifImageWidth = 0xA002
|
| 175 |
+
ExifImageHeight = 0xA003
|
| 176 |
+
RelatedSoundFile = 0xA004
|
| 177 |
+
ExifInteroperabilityOffset = 0xA005
|
| 178 |
+
FlashEnergy = 0xA20B
|
| 179 |
+
SpatialFrequencyResponse = 0xA20C
|
| 180 |
+
FocalPlaneXResolution = 0xA20E
|
| 181 |
+
FocalPlaneYResolution = 0xA20F
|
| 182 |
+
FocalPlaneResolutionUnit = 0xA210
|
| 183 |
+
SubjectLocation = 0xA214
|
| 184 |
+
ExposureIndex = 0xA215
|
| 185 |
+
SensingMethod = 0xA217
|
| 186 |
+
FileSource = 0xA300
|
| 187 |
+
SceneType = 0xA301
|
| 188 |
+
CFAPattern = 0xA302
|
| 189 |
+
CustomRendered = 0xA401
|
| 190 |
+
ExposureMode = 0xA402
|
| 191 |
+
WhiteBalance = 0xA403
|
| 192 |
+
DigitalZoomRatio = 0xA404
|
| 193 |
+
FocalLengthIn35mmFilm = 0xA405
|
| 194 |
+
SceneCaptureType = 0xA406
|
| 195 |
+
GainControl = 0xA407
|
| 196 |
+
Contrast = 0xA408
|
| 197 |
+
Saturation = 0xA409
|
| 198 |
+
Sharpness = 0xA40A
|
| 199 |
+
DeviceSettingDescription = 0xA40B
|
| 200 |
+
SubjectDistanceRange = 0xA40C
|
| 201 |
+
ImageUniqueID = 0xA420
|
| 202 |
+
CameraOwnerName = 0xA430
|
| 203 |
+
BodySerialNumber = 0xA431
|
| 204 |
+
LensSpecification = 0xA432
|
| 205 |
+
LensMake = 0xA433
|
| 206 |
+
LensModel = 0xA434
|
| 207 |
+
LensSerialNumber = 0xA435
|
| 208 |
+
CompositeImage = 0xA460
|
| 209 |
+
CompositeImageCount = 0xA461
|
| 210 |
+
CompositeImageExposureTimes = 0xA462
|
| 211 |
+
Gamma = 0xA500
|
| 212 |
+
PrintImageMatching = 0xC4A5
|
| 213 |
+
DNGVersion = 0xC612
|
| 214 |
+
DNGBackwardVersion = 0xC613
|
| 215 |
+
UniqueCameraModel = 0xC614
|
| 216 |
+
LocalizedCameraModel = 0xC615
|
| 217 |
+
CFAPlaneColor = 0xC616
|
| 218 |
+
CFALayout = 0xC617
|
| 219 |
+
LinearizationTable = 0xC618
|
| 220 |
+
BlackLevelRepeatDim = 0xC619
|
| 221 |
+
BlackLevel = 0xC61A
|
| 222 |
+
BlackLevelDeltaH = 0xC61B
|
| 223 |
+
BlackLevelDeltaV = 0xC61C
|
| 224 |
+
WhiteLevel = 0xC61D
|
| 225 |
+
DefaultScale = 0xC61E
|
| 226 |
+
DefaultCropOrigin = 0xC61F
|
| 227 |
+
DefaultCropSize = 0xC620
|
| 228 |
+
ColorMatrix1 = 0xC621
|
| 229 |
+
ColorMatrix2 = 0xC622
|
| 230 |
+
CameraCalibration1 = 0xC623
|
| 231 |
+
CameraCalibration2 = 0xC624
|
| 232 |
+
ReductionMatrix1 = 0xC625
|
| 233 |
+
ReductionMatrix2 = 0xC626
|
| 234 |
+
AnalogBalance = 0xC627
|
| 235 |
+
AsShotNeutral = 0xC628
|
| 236 |
+
AsShotWhiteXY = 0xC629
|
| 237 |
+
BaselineExposure = 0xC62A
|
| 238 |
+
BaselineNoise = 0xC62B
|
| 239 |
+
BaselineSharpness = 0xC62C
|
| 240 |
+
BayerGreenSplit = 0xC62D
|
| 241 |
+
LinearResponseLimit = 0xC62E
|
| 242 |
+
CameraSerialNumber = 0xC62F
|
| 243 |
+
LensInfo = 0xC630
|
| 244 |
+
ChromaBlurRadius = 0xC631
|
| 245 |
+
AntiAliasStrength = 0xC632
|
| 246 |
+
ShadowScale = 0xC633
|
| 247 |
+
DNGPrivateData = 0xC634
|
| 248 |
+
MakerNoteSafety = 0xC635
|
| 249 |
+
CalibrationIlluminant1 = 0xC65A
|
| 250 |
+
CalibrationIlluminant2 = 0xC65B
|
| 251 |
+
BestQualityScale = 0xC65C
|
| 252 |
+
RawDataUniqueID = 0xC65D
|
| 253 |
+
OriginalRawFileName = 0xC68B
|
| 254 |
+
OriginalRawFileData = 0xC68C
|
| 255 |
+
ActiveArea = 0xC68D
|
| 256 |
+
MaskedAreas = 0xC68E
|
| 257 |
+
AsShotICCProfile = 0xC68F
|
| 258 |
+
AsShotPreProfileMatrix = 0xC690
|
| 259 |
+
CurrentICCProfile = 0xC691
|
| 260 |
+
CurrentPreProfileMatrix = 0xC692
|
| 261 |
+
ColorimetricReference = 0xC6BF
|
| 262 |
+
CameraCalibrationSignature = 0xC6F3
|
| 263 |
+
ProfileCalibrationSignature = 0xC6F4
|
| 264 |
+
AsShotProfileName = 0xC6F6
|
| 265 |
+
NoiseReductionApplied = 0xC6F7
|
| 266 |
+
ProfileName = 0xC6F8
|
| 267 |
+
ProfileHueSatMapDims = 0xC6F9
|
| 268 |
+
ProfileHueSatMapData1 = 0xC6FA
|
| 269 |
+
ProfileHueSatMapData2 = 0xC6FB
|
| 270 |
+
ProfileToneCurve = 0xC6FC
|
| 271 |
+
ProfileEmbedPolicy = 0xC6FD
|
| 272 |
+
ProfileCopyright = 0xC6FE
|
| 273 |
+
ForwardMatrix1 = 0xC714
|
| 274 |
+
ForwardMatrix2 = 0xC715
|
| 275 |
+
PreviewApplicationName = 0xC716
|
| 276 |
+
PreviewApplicationVersion = 0xC717
|
| 277 |
+
PreviewSettingsName = 0xC718
|
| 278 |
+
PreviewSettingsDigest = 0xC719
|
| 279 |
+
PreviewColorSpace = 0xC71A
|
| 280 |
+
PreviewDateTime = 0xC71B
|
| 281 |
+
RawImageDigest = 0xC71C
|
| 282 |
+
OriginalRawFileDigest = 0xC71D
|
| 283 |
+
SubTileBlockSize = 0xC71E
|
| 284 |
+
RowInterleaveFactor = 0xC71F
|
| 285 |
+
ProfileLookTableDims = 0xC725
|
| 286 |
+
ProfileLookTableData = 0xC726
|
| 287 |
+
OpcodeList1 = 0xC740
|
| 288 |
+
OpcodeList2 = 0xC741
|
| 289 |
+
OpcodeList3 = 0xC74E
|
| 290 |
+
NoiseProfile = 0xC761
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
"""Maps EXIF tags to tag names."""
|
| 294 |
+
TAGS = {
|
| 295 |
+
**{i.value: i.name for i in Base},
|
| 296 |
+
0x920C: "SpatialFrequencyResponse",
|
| 297 |
+
0x9214: "SubjectLocation",
|
| 298 |
+
0x9215: "ExposureIndex",
|
| 299 |
+
0x828E: "CFAPattern",
|
| 300 |
+
0x920B: "FlashEnergy",
|
| 301 |
+
0x9216: "TIFF/EPStandardID",
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class GPS(IntEnum):
|
| 306 |
+
GPSVersionID = 0
|
| 307 |
+
GPSLatitudeRef = 1
|
| 308 |
+
GPSLatitude = 2
|
| 309 |
+
GPSLongitudeRef = 3
|
| 310 |
+
GPSLongitude = 4
|
| 311 |
+
GPSAltitudeRef = 5
|
| 312 |
+
GPSAltitude = 6
|
| 313 |
+
GPSTimeStamp = 7
|
| 314 |
+
GPSSatellites = 8
|
| 315 |
+
GPSStatus = 9
|
| 316 |
+
GPSMeasureMode = 10
|
| 317 |
+
GPSDOP = 11
|
| 318 |
+
GPSSpeedRef = 12
|
| 319 |
+
GPSSpeed = 13
|
| 320 |
+
GPSTrackRef = 14
|
| 321 |
+
GPSTrack = 15
|
| 322 |
+
GPSImgDirectionRef = 16
|
| 323 |
+
GPSImgDirection = 17
|
| 324 |
+
GPSMapDatum = 18
|
| 325 |
+
GPSDestLatitudeRef = 19
|
| 326 |
+
GPSDestLatitude = 20
|
| 327 |
+
GPSDestLongitudeRef = 21
|
| 328 |
+
GPSDestLongitude = 22
|
| 329 |
+
GPSDestBearingRef = 23
|
| 330 |
+
GPSDestBearing = 24
|
| 331 |
+
GPSDestDistanceRef = 25
|
| 332 |
+
GPSDestDistance = 26
|
| 333 |
+
GPSProcessingMethod = 27
|
| 334 |
+
GPSAreaInformation = 28
|
| 335 |
+
GPSDateStamp = 29
|
| 336 |
+
GPSDifferential = 30
|
| 337 |
+
GPSHPositioningError = 31
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
"""Maps EXIF GPS tags to tag names."""
|
| 341 |
+
GPSTAGS = {i.value: i.name for i in GPS}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class Interop(IntEnum):
|
| 345 |
+
InteropIndex = 1
|
| 346 |
+
InteropVersion = 2
|
| 347 |
+
RelatedImageFileFormat = 4096
|
| 348 |
+
RelatedImageWidth = 4097
|
| 349 |
+
RelatedImageHeight = 4098
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class IFD(IntEnum):
|
| 353 |
+
Exif = 34665
|
| 354 |
+
GPSInfo = 34853
|
| 355 |
+
Makernote = 37500
|
| 356 |
+
Interop = 40965
|
| 357 |
+
IFD1 = -1
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class LightSource(IntEnum):
|
| 361 |
+
Unknown = 0
|
| 362 |
+
Daylight = 1
|
| 363 |
+
Fluorescent = 2
|
| 364 |
+
Tungsten = 3
|
| 365 |
+
Flash = 4
|
| 366 |
+
Fine = 9
|
| 367 |
+
Cloudy = 10
|
| 368 |
+
Shade = 11
|
| 369 |
+
DaylightFluorescent = 12
|
| 370 |
+
DayWhiteFluorescent = 13
|
| 371 |
+
CoolWhiteFluorescent = 14
|
| 372 |
+
WhiteFluorescent = 15
|
| 373 |
+
StandardLightA = 17
|
| 374 |
+
StandardLightB = 18
|
| 375 |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$
|
| 4 |
+
#
|
| 5 |
+
# base class for raster font file parsers
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1997-06-05 fl created
|
| 9 |
+
# 1997-08-19 fl restrict image width
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 1997-1998 by Secret Labs AB
|
| 12 |
+
# Copyright (c) 1997-1998 by Fredrik Lundh
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from typing import BinaryIO
|
| 20 |
+
|
| 21 |
+
from . import Image, _binary
|
| 22 |
+
|
| 23 |
+
WIDTH = 800
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def puti16(
|
| 27 |
+
fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
|
| 28 |
+
) -> None:
|
| 29 |
+
"""Write network order (big-endian) 16-bit sequence"""
|
| 30 |
+
for v in values:
|
| 31 |
+
if v < 0:
|
| 32 |
+
v += 65536
|
| 33 |
+
fp.write(_binary.o16be(v))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class FontFile:
|
| 37 |
+
"""Base class for raster font file handlers."""
|
| 38 |
+
|
| 39 |
+
bitmap: Image.Image | None = None
|
| 40 |
+
|
| 41 |
+
def __init__(self) -> None:
|
| 42 |
+
self.info: dict[bytes, bytes | int] = {}
|
| 43 |
+
self.glyph: list[
|
| 44 |
+
tuple[
|
| 45 |
+
tuple[int, int],
|
| 46 |
+
tuple[int, int, int, int],
|
| 47 |
+
tuple[int, int, int, int],
|
| 48 |
+
Image.Image,
|
| 49 |
+
]
|
| 50 |
+
| None
|
| 51 |
+
] = [None] * 256
|
| 52 |
+
|
| 53 |
+
def __getitem__(self, ix: int) -> (
|
| 54 |
+
tuple[
|
| 55 |
+
tuple[int, int],
|
| 56 |
+
tuple[int, int, int, int],
|
| 57 |
+
tuple[int, int, int, int],
|
| 58 |
+
Image.Image,
|
| 59 |
+
]
|
| 60 |
+
| None
|
| 61 |
+
):
|
| 62 |
+
return self.glyph[ix]
|
| 63 |
+
|
| 64 |
+
def compile(self) -> None:
|
| 65 |
+
"""Create metrics and bitmap"""
|
| 66 |
+
|
| 67 |
+
if self.bitmap:
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
# create bitmap large enough to hold all data
|
| 71 |
+
h = w = maxwidth = 0
|
| 72 |
+
lines = 1
|
| 73 |
+
for glyph in self.glyph:
|
| 74 |
+
if glyph:
|
| 75 |
+
d, dst, src, im = glyph
|
| 76 |
+
h = max(h, src[3] - src[1])
|
| 77 |
+
w = w + (src[2] - src[0])
|
| 78 |
+
if w > WIDTH:
|
| 79 |
+
lines += 1
|
| 80 |
+
w = src[2] - src[0]
|
| 81 |
+
maxwidth = max(maxwidth, w)
|
| 82 |
+
|
| 83 |
+
xsize = maxwidth
|
| 84 |
+
ysize = lines * h
|
| 85 |
+
|
| 86 |
+
if xsize == 0 and ysize == 0:
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
self.ysize = h
|
| 90 |
+
|
| 91 |
+
# paste glyphs into bitmap
|
| 92 |
+
self.bitmap = Image.new("1", (xsize, ysize))
|
| 93 |
+
self.metrics: list[
|
| 94 |
+
tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
|
| 95 |
+
| None
|
| 96 |
+
] = [None] * 256
|
| 97 |
+
x = y = 0
|
| 98 |
+
for i in range(256):
|
| 99 |
+
glyph = self[i]
|
| 100 |
+
if glyph:
|
| 101 |
+
d, dst, src, im = glyph
|
| 102 |
+
xx = src[2] - src[0]
|
| 103 |
+
x0, y0 = x, y
|
| 104 |
+
x = x + xx
|
| 105 |
+
if x > WIDTH:
|
| 106 |
+
x, y = 0, y + h
|
| 107 |
+
x0, y0 = x, y
|
| 108 |
+
x = xx
|
| 109 |
+
s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
|
| 110 |
+
self.bitmap.paste(im.crop(src), s)
|
| 111 |
+
self.metrics[i] = d, dst, s
|
| 112 |
+
|
| 113 |
+
def save(self, filename: str) -> None:
|
| 114 |
+
"""Save font"""
|
| 115 |
+
|
| 116 |
+
self.compile()
|
| 117 |
+
|
| 118 |
+
# font data
|
| 119 |
+
if not self.bitmap:
|
| 120 |
+
msg = "No bitmap created"
|
| 121 |
+
raise ValueError(msg)
|
| 122 |
+
self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
|
| 123 |
+
|
| 124 |
+
# font metrics
|
| 125 |
+
with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
|
| 126 |
+
fp.write(b"PILfont\n")
|
| 127 |
+
fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
|
| 128 |
+
fp.write(b"DATA\n")
|
| 129 |
+
for id in range(256):
|
| 130 |
+
m = self.metrics[id]
|
| 131 |
+
if not m:
|
| 132 |
+
puti16(fp, (0,) * 10)
|
| 133 |
+
else:
|
| 134 |
+
puti16(fp, m[0] + m[1] + m[2])
|
.venv/lib/python3.11/site-packages/PIL/FpxImagePlugin.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# THIS IS WORK IN PROGRESS
|
| 3 |
+
#
|
| 4 |
+
# The Python Imaging Library.
|
| 5 |
+
# $Id$
|
| 6 |
+
#
|
| 7 |
+
# FlashPix support for PIL
|
| 8 |
+
#
|
| 9 |
+
# History:
|
| 10 |
+
# 97-01-25 fl Created (reads uncompressed RGB images only)
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import olefile
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile
|
| 22 |
+
from ._binary import i32le as i32
|
| 23 |
+
|
| 24 |
+
# we map from colour field tuples to (mode, rawmode) descriptors
|
| 25 |
+
MODES = {
|
| 26 |
+
# opacity
|
| 27 |
+
(0x00007FFE,): ("A", "L"),
|
| 28 |
+
# monochrome
|
| 29 |
+
(0x00010000,): ("L", "L"),
|
| 30 |
+
(0x00018000, 0x00017FFE): ("RGBA", "LA"),
|
| 31 |
+
# photo YCC
|
| 32 |
+
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
|
| 33 |
+
(0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
|
| 34 |
+
# standard RGB (NIFRGB)
|
| 35 |
+
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
|
| 36 |
+
(0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
#
|
| 41 |
+
# --------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _accept(prefix: bytes) -> bool:
|
| 45 |
+
return prefix[:8] == olefile.MAGIC
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
##
|
| 49 |
+
# Image plugin for the FlashPix images.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FpxImageFile(ImageFile.ImageFile):
|
| 53 |
+
format = "FPX"
|
| 54 |
+
format_description = "FlashPix"
|
| 55 |
+
|
| 56 |
+
def _open(self):
|
| 57 |
+
#
|
| 58 |
+
# read the OLE directory and see if this is a likely
|
| 59 |
+
# to be a FlashPix file
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
self.ole = olefile.OleFileIO(self.fp)
|
| 63 |
+
except OSError as e:
|
| 64 |
+
msg = "not an FPX file; invalid OLE file"
|
| 65 |
+
raise SyntaxError(msg) from e
|
| 66 |
+
|
| 67 |
+
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
|
| 68 |
+
msg = "not an FPX file; bad root CLSID"
|
| 69 |
+
raise SyntaxError(msg)
|
| 70 |
+
|
| 71 |
+
self._open_index(1)
|
| 72 |
+
|
| 73 |
+
def _open_index(self, index: int = 1) -> None:
|
| 74 |
+
#
|
| 75 |
+
# get the Image Contents Property Set
|
| 76 |
+
|
| 77 |
+
prop = self.ole.getproperties(
|
| 78 |
+
[f"Data Object Store {index:06d}", "\005Image Contents"]
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# size (highest resolution)
|
| 82 |
+
|
| 83 |
+
self._size = prop[0x1000002], prop[0x1000003]
|
| 84 |
+
|
| 85 |
+
size = max(self.size)
|
| 86 |
+
i = 1
|
| 87 |
+
while size > 64:
|
| 88 |
+
size = size // 2
|
| 89 |
+
i += 1
|
| 90 |
+
self.maxid = i - 1
|
| 91 |
+
|
| 92 |
+
# mode. instead of using a single field for this, flashpix
|
| 93 |
+
# requires you to specify the mode for each channel in each
|
| 94 |
+
# resolution subimage, and leaves it to the decoder to make
|
| 95 |
+
# sure that they all match. for now, we'll cheat and assume
|
| 96 |
+
# that this is always the case.
|
| 97 |
+
|
| 98 |
+
id = self.maxid << 16
|
| 99 |
+
|
| 100 |
+
s = prop[0x2000002 | id]
|
| 101 |
+
|
| 102 |
+
bands = i32(s, 4)
|
| 103 |
+
if bands > 4:
|
| 104 |
+
msg = "Invalid number of bands"
|
| 105 |
+
raise OSError(msg)
|
| 106 |
+
|
| 107 |
+
# note: for now, we ignore the "uncalibrated" flag
|
| 108 |
+
colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
|
| 109 |
+
|
| 110 |
+
self._mode, self.rawmode = MODES[colors]
|
| 111 |
+
|
| 112 |
+
# load JPEG tables, if any
|
| 113 |
+
self.jpeg = {}
|
| 114 |
+
for i in range(256):
|
| 115 |
+
id = 0x3000001 | (i << 16)
|
| 116 |
+
if id in prop:
|
| 117 |
+
self.jpeg[i] = prop[id]
|
| 118 |
+
|
| 119 |
+
self._open_subimage(1, self.maxid)
|
| 120 |
+
|
| 121 |
+
def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
|
| 122 |
+
#
|
| 123 |
+
# setup tile descriptors for a given subimage
|
| 124 |
+
|
| 125 |
+
stream = [
|
| 126 |
+
f"Data Object Store {index:06d}",
|
| 127 |
+
f"Resolution {subimage:04d}",
|
| 128 |
+
"Subimage 0000 Header",
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
fp = self.ole.openstream(stream)
|
| 132 |
+
|
| 133 |
+
# skip prefix
|
| 134 |
+
fp.read(28)
|
| 135 |
+
|
| 136 |
+
# header stream
|
| 137 |
+
s = fp.read(36)
|
| 138 |
+
|
| 139 |
+
size = i32(s, 4), i32(s, 8)
|
| 140 |
+
# tilecount = i32(s, 12)
|
| 141 |
+
tilesize = i32(s, 16), i32(s, 20)
|
| 142 |
+
# channels = i32(s, 24)
|
| 143 |
+
offset = i32(s, 28)
|
| 144 |
+
length = i32(s, 32)
|
| 145 |
+
|
| 146 |
+
if size != self.size:
|
| 147 |
+
msg = "subimage mismatch"
|
| 148 |
+
raise OSError(msg)
|
| 149 |
+
|
| 150 |
+
# get tile descriptors
|
| 151 |
+
fp.seek(28 + offset)
|
| 152 |
+
s = fp.read(i32(s, 12) * length)
|
| 153 |
+
|
| 154 |
+
x = y = 0
|
| 155 |
+
xsize, ysize = size
|
| 156 |
+
xtile, ytile = tilesize
|
| 157 |
+
self.tile = []
|
| 158 |
+
|
| 159 |
+
for i in range(0, len(s), length):
|
| 160 |
+
x1 = min(xsize, x + xtile)
|
| 161 |
+
y1 = min(ysize, y + ytile)
|
| 162 |
+
|
| 163 |
+
compression = i32(s, i + 8)
|
| 164 |
+
|
| 165 |
+
if compression == 0:
|
| 166 |
+
self.tile.append(
|
| 167 |
+
(
|
| 168 |
+
"raw",
|
| 169 |
+
(x, y, x1, y1),
|
| 170 |
+
i32(s, i) + 28,
|
| 171 |
+
(self.rawmode,),
|
| 172 |
+
)
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
elif compression == 1:
|
| 176 |
+
# FIXME: the fill decoder is not implemented
|
| 177 |
+
self.tile.append(
|
| 178 |
+
(
|
| 179 |
+
"fill",
|
| 180 |
+
(x, y, x1, y1),
|
| 181 |
+
i32(s, i) + 28,
|
| 182 |
+
(self.rawmode, s[12:16]),
|
| 183 |
+
)
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
elif compression == 2:
|
| 187 |
+
internal_color_conversion = s[14]
|
| 188 |
+
jpeg_tables = s[15]
|
| 189 |
+
rawmode = self.rawmode
|
| 190 |
+
|
| 191 |
+
if internal_color_conversion:
|
| 192 |
+
# The image is stored as usual (usually YCbCr).
|
| 193 |
+
if rawmode == "RGBA":
|
| 194 |
+
# For "RGBA", data is stored as YCbCrA based on
|
| 195 |
+
# negative RGB. The following trick works around
|
| 196 |
+
# this problem :
|
| 197 |
+
jpegmode, rawmode = "YCbCrK", "CMYK"
|
| 198 |
+
else:
|
| 199 |
+
jpegmode = None # let the decoder decide
|
| 200 |
+
|
| 201 |
+
else:
|
| 202 |
+
# The image is stored as defined by rawmode
|
| 203 |
+
jpegmode = rawmode
|
| 204 |
+
|
| 205 |
+
self.tile.append(
|
| 206 |
+
(
|
| 207 |
+
"jpeg",
|
| 208 |
+
(x, y, x1, y1),
|
| 209 |
+
i32(s, i) + 28,
|
| 210 |
+
(rawmode, jpegmode),
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# FIXME: jpeg tables are tile dependent; the prefix
|
| 215 |
+
# data must be placed in the tile descriptor itself!
|
| 216 |
+
|
| 217 |
+
if jpeg_tables:
|
| 218 |
+
self.tile_prefix = self.jpeg[jpeg_tables]
|
| 219 |
+
|
| 220 |
+
else:
|
| 221 |
+
msg = "unknown/invalid compression"
|
| 222 |
+
raise OSError(msg)
|
| 223 |
+
|
| 224 |
+
x = x + xtile
|
| 225 |
+
if x >= xsize:
|
| 226 |
+
x, y = 0, y + ytile
|
| 227 |
+
if y >= ysize:
|
| 228 |
+
break # isn't really required
|
| 229 |
+
|
| 230 |
+
self.stream = stream
|
| 231 |
+
self._fp = self.fp
|
| 232 |
+
self.fp = None
|
| 233 |
+
|
| 234 |
+
def load(self):
|
| 235 |
+
if not self.fp:
|
| 236 |
+
self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
|
| 237 |
+
|
| 238 |
+
return ImageFile.ImageFile.load(self)
|
| 239 |
+
|
| 240 |
+
def close(self) -> None:
|
| 241 |
+
self.ole.close()
|
| 242 |
+
super().close()
|
| 243 |
+
|
| 244 |
+
def __exit__(self, *args: object) -> None:
|
| 245 |
+
self.ole.close()
|
| 246 |
+
super().__exit__()
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
#
|
| 250 |
+
# --------------------------------------------------------------------
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
|
| 254 |
+
|
| 255 |
+
Image.register_extension(FpxImageFile.format, ".fpx")
|
.venv/lib/python3.11/site-packages/PIL/G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-30 fl Added animation support
|
| 11 |
+
# 1997-01-05 fl Added write support, fixed local colour map bug
|
| 12 |
+
# 1997-02-23 fl Make sure to load raster data in getdata()
|
| 13 |
+
# 1997-07-05 fl Support external decoder (0.4)
|
| 14 |
+
# 1998-07-09 fl Handle all modes when saving (0.5)
|
| 15 |
+
# 1998-07-15 fl Renamed offset attribute to avoid name clash
|
| 16 |
+
# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
|
| 17 |
+
# 2001-04-17 fl Added palette optimization (0.7)
|
| 18 |
+
# 2002-06-06 fl Added transparency support for save (0.8)
|
| 19 |
+
# 2004-02-24 fl Disable interlacing for small images
|
| 20 |
+
#
|
| 21 |
+
# Copyright (c) 1997-2004 by Secret Labs AB
|
| 22 |
+
# Copyright (c) 1995-2004 by Fredrik Lundh
|
| 23 |
+
#
|
| 24 |
+
# See the README file for information on usage and redistribution.
|
| 25 |
+
#
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import itertools
|
| 29 |
+
import math
|
| 30 |
+
import os
|
| 31 |
+
import subprocess
|
| 32 |
+
import sys
|
| 33 |
+
from enum import IntEnum
|
| 34 |
+
from functools import cached_property
|
| 35 |
+
from typing import IO, TYPE_CHECKING, Any, List, Literal, NamedTuple, Union
|
| 36 |
+
|
| 37 |
+
from . import (
|
| 38 |
+
Image,
|
| 39 |
+
ImageChops,
|
| 40 |
+
ImageFile,
|
| 41 |
+
ImageMath,
|
| 42 |
+
ImageOps,
|
| 43 |
+
ImagePalette,
|
| 44 |
+
ImageSequence,
|
| 45 |
+
)
|
| 46 |
+
from ._binary import i16le as i16
|
| 47 |
+
from ._binary import o8
|
| 48 |
+
from ._binary import o16le as o16
|
| 49 |
+
|
| 50 |
+
if TYPE_CHECKING:
|
| 51 |
+
from . import _imaging
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class LoadingStrategy(IntEnum):
|
| 55 |
+
""".. versionadded:: 9.1.0"""
|
| 56 |
+
|
| 57 |
+
RGB_AFTER_FIRST = 0
|
| 58 |
+
RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
|
| 59 |
+
RGB_ALWAYS = 2
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
#: .. versionadded:: 9.1.0
|
| 63 |
+
LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
|
| 64 |
+
|
| 65 |
+
# --------------------------------------------------------------------
|
| 66 |
+
# Identify/read GIF files
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _accept(prefix: bytes) -> bool:
|
| 70 |
+
return prefix[:6] in [b"GIF87a", b"GIF89a"]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
##
|
| 74 |
+
# Image plugin for GIF images. This plugin supports both GIF87 and
|
| 75 |
+
# GIF89 images.
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class GifImageFile(ImageFile.ImageFile):
|
| 79 |
+
format = "GIF"
|
| 80 |
+
format_description = "Compuserve GIF"
|
| 81 |
+
_close_exclusive_fp_after_loading = False
|
| 82 |
+
|
| 83 |
+
global_palette = None
|
| 84 |
+
|
| 85 |
+
def data(self) -> bytes | None:
|
| 86 |
+
s = self.fp.read(1)
|
| 87 |
+
if s and s[0]:
|
| 88 |
+
return self.fp.read(s[0])
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
def _is_palette_needed(self, p: bytes) -> bool:
|
| 92 |
+
for i in range(0, len(p), 3):
|
| 93 |
+
if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
|
| 94 |
+
return True
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
def _open(self) -> None:
|
| 98 |
+
# Screen
|
| 99 |
+
s = self.fp.read(13)
|
| 100 |
+
if not _accept(s):
|
| 101 |
+
msg = "not a GIF file"
|
| 102 |
+
raise SyntaxError(msg)
|
| 103 |
+
|
| 104 |
+
self.info["version"] = s[:6]
|
| 105 |
+
self._size = i16(s, 6), i16(s, 8)
|
| 106 |
+
self.tile = []
|
| 107 |
+
flags = s[10]
|
| 108 |
+
bits = (flags & 7) + 1
|
| 109 |
+
|
| 110 |
+
if flags & 128:
|
| 111 |
+
# get global palette
|
| 112 |
+
self.info["background"] = s[11]
|
| 113 |
+
# check if palette contains colour indices
|
| 114 |
+
p = self.fp.read(3 << bits)
|
| 115 |
+
if self._is_palette_needed(p):
|
| 116 |
+
p = ImagePalette.raw("RGB", p)
|
| 117 |
+
self.global_palette = self.palette = p
|
| 118 |
+
|
| 119 |
+
self._fp = self.fp # FIXME: hack
|
| 120 |
+
self.__rewind = self.fp.tell()
|
| 121 |
+
self._n_frames: int | None = None
|
| 122 |
+
self._seek(0) # get ready to read first frame
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def n_frames(self) -> int:
|
| 126 |
+
if self._n_frames is None:
|
| 127 |
+
current = self.tell()
|
| 128 |
+
try:
|
| 129 |
+
while True:
|
| 130 |
+
self._seek(self.tell() + 1, False)
|
| 131 |
+
except EOFError:
|
| 132 |
+
self._n_frames = self.tell() + 1
|
| 133 |
+
self.seek(current)
|
| 134 |
+
return self._n_frames
|
| 135 |
+
|
| 136 |
+
@cached_property
|
| 137 |
+
def is_animated(self) -> bool:
|
| 138 |
+
if self._n_frames is not None:
|
| 139 |
+
return self._n_frames != 1
|
| 140 |
+
|
| 141 |
+
current = self.tell()
|
| 142 |
+
if current:
|
| 143 |
+
return True
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
self._seek(1, False)
|
| 147 |
+
is_animated = True
|
| 148 |
+
except EOFError:
|
| 149 |
+
is_animated = False
|
| 150 |
+
|
| 151 |
+
self.seek(current)
|
| 152 |
+
return is_animated
|
| 153 |
+
|
| 154 |
+
def seek(self, frame: int) -> None:
|
| 155 |
+
if not self._seek_check(frame):
|
| 156 |
+
return
|
| 157 |
+
if frame < self.__frame:
|
| 158 |
+
self.im = None
|
| 159 |
+
self._seek(0)
|
| 160 |
+
|
| 161 |
+
last_frame = self.__frame
|
| 162 |
+
for f in range(self.__frame + 1, frame + 1):
|
| 163 |
+
try:
|
| 164 |
+
self._seek(f)
|
| 165 |
+
except EOFError as e:
|
| 166 |
+
self.seek(last_frame)
|
| 167 |
+
msg = "no more images in GIF file"
|
| 168 |
+
raise EOFError(msg) from e
|
| 169 |
+
|
| 170 |
+
def _seek(self, frame: int, update_image: bool = True) -> None:
|
| 171 |
+
if frame == 0:
|
| 172 |
+
# rewind
|
| 173 |
+
self.__offset = 0
|
| 174 |
+
self.dispose: _imaging.ImagingCore | None = None
|
| 175 |
+
self.__frame = -1
|
| 176 |
+
self._fp.seek(self.__rewind)
|
| 177 |
+
self.disposal_method = 0
|
| 178 |
+
if "comment" in self.info:
|
| 179 |
+
del self.info["comment"]
|
| 180 |
+
else:
|
| 181 |
+
# ensure that the previous frame was loaded
|
| 182 |
+
if self.tile and update_image:
|
| 183 |
+
self.load()
|
| 184 |
+
|
| 185 |
+
if frame != self.__frame + 1:
|
| 186 |
+
msg = f"cannot seek to frame {frame}"
|
| 187 |
+
raise ValueError(msg)
|
| 188 |
+
|
| 189 |
+
self.fp = self._fp
|
| 190 |
+
if self.__offset:
|
| 191 |
+
# backup to last frame
|
| 192 |
+
self.fp.seek(self.__offset)
|
| 193 |
+
while self.data():
|
| 194 |
+
pass
|
| 195 |
+
self.__offset = 0
|
| 196 |
+
|
| 197 |
+
s = self.fp.read(1)
|
| 198 |
+
if not s or s == b";":
|
| 199 |
+
msg = "no more images in GIF file"
|
| 200 |
+
raise EOFError(msg)
|
| 201 |
+
|
| 202 |
+
palette: ImagePalette.ImagePalette | Literal[False] | None = None
|
| 203 |
+
|
| 204 |
+
info: dict[str, Any] = {}
|
| 205 |
+
frame_transparency = None
|
| 206 |
+
interlace = None
|
| 207 |
+
frame_dispose_extent = None
|
| 208 |
+
while True:
|
| 209 |
+
if not s:
|
| 210 |
+
s = self.fp.read(1)
|
| 211 |
+
if not s or s == b";":
|
| 212 |
+
break
|
| 213 |
+
|
| 214 |
+
elif s == b"!":
|
| 215 |
+
#
|
| 216 |
+
# extensions
|
| 217 |
+
#
|
| 218 |
+
s = self.fp.read(1)
|
| 219 |
+
block = self.data()
|
| 220 |
+
if s[0] == 249 and block is not None:
|
| 221 |
+
#
|
| 222 |
+
# graphic control extension
|
| 223 |
+
#
|
| 224 |
+
flags = block[0]
|
| 225 |
+
if flags & 1:
|
| 226 |
+
frame_transparency = block[3]
|
| 227 |
+
info["duration"] = i16(block, 1) * 10
|
| 228 |
+
|
| 229 |
+
# disposal method - find the value of bits 4 - 6
|
| 230 |
+
dispose_bits = 0b00011100 & flags
|
| 231 |
+
dispose_bits = dispose_bits >> 2
|
| 232 |
+
if dispose_bits:
|
| 233 |
+
# only set the dispose if it is not
|
| 234 |
+
# unspecified. I'm not sure if this is
|
| 235 |
+
# correct, but it seems to prevent the last
|
| 236 |
+
# frame from looking odd for some animations
|
| 237 |
+
self.disposal_method = dispose_bits
|
| 238 |
+
elif s[0] == 254:
|
| 239 |
+
#
|
| 240 |
+
# comment extension
|
| 241 |
+
#
|
| 242 |
+
comment = b""
|
| 243 |
+
|
| 244 |
+
# Read this comment block
|
| 245 |
+
while block:
|
| 246 |
+
comment += block
|
| 247 |
+
block = self.data()
|
| 248 |
+
|
| 249 |
+
if "comment" in info:
|
| 250 |
+
# If multiple comment blocks in frame, separate with \n
|
| 251 |
+
info["comment"] += b"\n" + comment
|
| 252 |
+
else:
|
| 253 |
+
info["comment"] = comment
|
| 254 |
+
s = None
|
| 255 |
+
continue
|
| 256 |
+
elif s[0] == 255 and frame == 0 and block is not None:
|
| 257 |
+
#
|
| 258 |
+
# application extension
|
| 259 |
+
#
|
| 260 |
+
info["extension"] = block, self.fp.tell()
|
| 261 |
+
if block[:11] == b"NETSCAPE2.0":
|
| 262 |
+
block = self.data()
|
| 263 |
+
if block and len(block) >= 3 and block[0] == 1:
|
| 264 |
+
self.info["loop"] = i16(block, 1)
|
| 265 |
+
while self.data():
|
| 266 |
+
pass
|
| 267 |
+
|
| 268 |
+
elif s == b",":
|
| 269 |
+
#
|
| 270 |
+
# local image
|
| 271 |
+
#
|
| 272 |
+
s = self.fp.read(9)
|
| 273 |
+
|
| 274 |
+
# extent
|
| 275 |
+
x0, y0 = i16(s, 0), i16(s, 2)
|
| 276 |
+
x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
|
| 277 |
+
if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
|
| 278 |
+
self._size = max(x1, self.size[0]), max(y1, self.size[1])
|
| 279 |
+
Image._decompression_bomb_check(self._size)
|
| 280 |
+
frame_dispose_extent = x0, y0, x1, y1
|
| 281 |
+
flags = s[8]
|
| 282 |
+
|
| 283 |
+
interlace = (flags & 64) != 0
|
| 284 |
+
|
| 285 |
+
if flags & 128:
|
| 286 |
+
bits = (flags & 7) + 1
|
| 287 |
+
p = self.fp.read(3 << bits)
|
| 288 |
+
if self._is_palette_needed(p):
|
| 289 |
+
palette = ImagePalette.raw("RGB", p)
|
| 290 |
+
else:
|
| 291 |
+
palette = False
|
| 292 |
+
|
| 293 |
+
# image data
|
| 294 |
+
bits = self.fp.read(1)[0]
|
| 295 |
+
self.__offset = self.fp.tell()
|
| 296 |
+
break
|
| 297 |
+
s = None
|
| 298 |
+
|
| 299 |
+
if interlace is None:
|
| 300 |
+
msg = "image not found in GIF frame"
|
| 301 |
+
raise EOFError(msg)
|
| 302 |
+
|
| 303 |
+
self.__frame = frame
|
| 304 |
+
if not update_image:
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
self.tile = []
|
| 308 |
+
|
| 309 |
+
if self.dispose:
|
| 310 |
+
self.im.paste(self.dispose, self.dispose_extent)
|
| 311 |
+
|
| 312 |
+
self._frame_palette = palette if palette is not None else self.global_palette
|
| 313 |
+
self._frame_transparency = frame_transparency
|
| 314 |
+
if frame == 0:
|
| 315 |
+
if self._frame_palette:
|
| 316 |
+
if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
| 317 |
+
self._mode = "RGBA" if frame_transparency is not None else "RGB"
|
| 318 |
+
else:
|
| 319 |
+
self._mode = "P"
|
| 320 |
+
else:
|
| 321 |
+
self._mode = "L"
|
| 322 |
+
|
| 323 |
+
if not palette and self.global_palette:
|
| 324 |
+
from copy import copy
|
| 325 |
+
|
| 326 |
+
palette = copy(self.global_palette)
|
| 327 |
+
self.palette = palette
|
| 328 |
+
else:
|
| 329 |
+
if self.mode == "P":
|
| 330 |
+
if (
|
| 331 |
+
LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
|
| 332 |
+
or palette
|
| 333 |
+
):
|
| 334 |
+
self.pyaccess = None
|
| 335 |
+
if "transparency" in self.info:
|
| 336 |
+
self.im.putpalettealpha(self.info["transparency"], 0)
|
| 337 |
+
self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
|
| 338 |
+
self._mode = "RGBA"
|
| 339 |
+
del self.info["transparency"]
|
| 340 |
+
else:
|
| 341 |
+
self._mode = "RGB"
|
| 342 |
+
self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
|
| 343 |
+
|
| 344 |
+
def _rgb(color: int) -> tuple[int, int, int]:
|
| 345 |
+
if self._frame_palette:
|
| 346 |
+
if color * 3 + 3 > len(self._frame_palette.palette):
|
| 347 |
+
color = 0
|
| 348 |
+
return tuple(self._frame_palette.palette[color * 3 : color * 3 + 3])
|
| 349 |
+
else:
|
| 350 |
+
return (color, color, color)
|
| 351 |
+
|
| 352 |
+
self.dispose = None
|
| 353 |
+
self.dispose_extent = frame_dispose_extent
|
| 354 |
+
if self.dispose_extent and self.disposal_method >= 2:
|
| 355 |
+
try:
|
| 356 |
+
if self.disposal_method == 2:
|
| 357 |
+
# replace with background colour
|
| 358 |
+
|
| 359 |
+
# only dispose the extent in this frame
|
| 360 |
+
x0, y0, x1, y1 = self.dispose_extent
|
| 361 |
+
dispose_size = (x1 - x0, y1 - y0)
|
| 362 |
+
|
| 363 |
+
Image._decompression_bomb_check(dispose_size)
|
| 364 |
+
|
| 365 |
+
# by convention, attempt to use transparency first
|
| 366 |
+
dispose_mode = "P"
|
| 367 |
+
color = self.info.get("transparency", frame_transparency)
|
| 368 |
+
if color is not None:
|
| 369 |
+
if self.mode in ("RGB", "RGBA"):
|
| 370 |
+
dispose_mode = "RGBA"
|
| 371 |
+
color = _rgb(color) + (0,)
|
| 372 |
+
else:
|
| 373 |
+
color = self.info.get("background", 0)
|
| 374 |
+
if self.mode in ("RGB", "RGBA"):
|
| 375 |
+
dispose_mode = "RGB"
|
| 376 |
+
color = _rgb(color)
|
| 377 |
+
self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
|
| 378 |
+
else:
|
| 379 |
+
# replace with previous contents
|
| 380 |
+
if self.im is not None:
|
| 381 |
+
# only dispose the extent in this frame
|
| 382 |
+
self.dispose = self._crop(self.im, self.dispose_extent)
|
| 383 |
+
elif frame_transparency is not None:
|
| 384 |
+
x0, y0, x1, y1 = self.dispose_extent
|
| 385 |
+
dispose_size = (x1 - x0, y1 - y0)
|
| 386 |
+
|
| 387 |
+
Image._decompression_bomb_check(dispose_size)
|
| 388 |
+
dispose_mode = "P"
|
| 389 |
+
color = frame_transparency
|
| 390 |
+
if self.mode in ("RGB", "RGBA"):
|
| 391 |
+
dispose_mode = "RGBA"
|
| 392 |
+
color = _rgb(frame_transparency) + (0,)
|
| 393 |
+
self.dispose = Image.core.fill(
|
| 394 |
+
dispose_mode, dispose_size, color
|
| 395 |
+
)
|
| 396 |
+
except AttributeError:
|
| 397 |
+
pass
|
| 398 |
+
|
| 399 |
+
if interlace is not None:
|
| 400 |
+
transparency = -1
|
| 401 |
+
if frame_transparency is not None:
|
| 402 |
+
if frame == 0:
|
| 403 |
+
if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
|
| 404 |
+
self.info["transparency"] = frame_transparency
|
| 405 |
+
elif self.mode not in ("RGB", "RGBA"):
|
| 406 |
+
transparency = frame_transparency
|
| 407 |
+
self.tile = [
|
| 408 |
+
(
|
| 409 |
+
"gif",
|
| 410 |
+
(x0, y0, x1, y1),
|
| 411 |
+
self.__offset,
|
| 412 |
+
(bits, interlace, transparency),
|
| 413 |
+
)
|
| 414 |
+
]
|
| 415 |
+
|
| 416 |
+
if info.get("comment"):
|
| 417 |
+
self.info["comment"] = info["comment"]
|
| 418 |
+
for k in ["duration", "extension"]:
|
| 419 |
+
if k in info:
|
| 420 |
+
self.info[k] = info[k]
|
| 421 |
+
elif k in self.info:
|
| 422 |
+
del self.info[k]
|
| 423 |
+
|
| 424 |
+
def load_prepare(self) -> None:
|
| 425 |
+
temp_mode = "P" if self._frame_palette else "L"
|
| 426 |
+
self._prev_im = None
|
| 427 |
+
if self.__frame == 0:
|
| 428 |
+
if self._frame_transparency is not None:
|
| 429 |
+
self.im = Image.core.fill(
|
| 430 |
+
temp_mode, self.size, self._frame_transparency
|
| 431 |
+
)
|
| 432 |
+
elif self.mode in ("RGB", "RGBA"):
|
| 433 |
+
self._prev_im = self.im
|
| 434 |
+
if self._frame_palette:
|
| 435 |
+
self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
|
| 436 |
+
self.im.putpalette("RGB", *self._frame_palette.getdata())
|
| 437 |
+
else:
|
| 438 |
+
self.im = None
|
| 439 |
+
self._mode = temp_mode
|
| 440 |
+
self._frame_palette = None
|
| 441 |
+
|
| 442 |
+
super().load_prepare()
|
| 443 |
+
|
| 444 |
+
def load_end(self) -> None:
|
| 445 |
+
if self.__frame == 0:
|
| 446 |
+
if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
|
| 447 |
+
if self._frame_transparency is not None:
|
| 448 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
| 449 |
+
self._mode = "RGBA"
|
| 450 |
+
else:
|
| 451 |
+
self._mode = "RGB"
|
| 452 |
+
self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
|
| 453 |
+
return
|
| 454 |
+
if not self._prev_im:
|
| 455 |
+
return
|
| 456 |
+
if self._frame_transparency is not None:
|
| 457 |
+
self.im.putpalettealpha(self._frame_transparency, 0)
|
| 458 |
+
frame_im = self.im.convert("RGBA")
|
| 459 |
+
else:
|
| 460 |
+
frame_im = self.im.convert("RGB")
|
| 461 |
+
|
| 462 |
+
assert self.dispose_extent is not None
|
| 463 |
+
frame_im = self._crop(frame_im, self.dispose_extent)
|
| 464 |
+
|
| 465 |
+
self.im = self._prev_im
|
| 466 |
+
self._mode = self.im.mode
|
| 467 |
+
if frame_im.mode == "RGBA":
|
| 468 |
+
self.im.paste(frame_im, self.dispose_extent, frame_im)
|
| 469 |
+
else:
|
| 470 |
+
self.im.paste(frame_im, self.dispose_extent)
|
| 471 |
+
|
| 472 |
+
def tell(self) -> int:
|
| 473 |
+
return self.__frame
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
# --------------------------------------------------------------------
|
| 477 |
+
# Write GIF files
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
RAWMODE = {"1": "L", "L": "L", "P": "P"}
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _normalize_mode(im: Image.Image) -> Image.Image:
|
| 484 |
+
"""
|
| 485 |
+
Takes an image (or frame), returns an image in a mode that is appropriate
|
| 486 |
+
for saving in a Gif.
|
| 487 |
+
|
| 488 |
+
It may return the original image, or it may return an image converted to
|
| 489 |
+
palette or 'L' mode.
|
| 490 |
+
|
| 491 |
+
:param im: Image object
|
| 492 |
+
:returns: Image object
|
| 493 |
+
"""
|
| 494 |
+
if im.mode in RAWMODE:
|
| 495 |
+
im.load()
|
| 496 |
+
return im
|
| 497 |
+
if Image.getmodebase(im.mode) == "RGB":
|
| 498 |
+
im = im.convert("P", palette=Image.Palette.ADAPTIVE)
|
| 499 |
+
if im.palette.mode == "RGBA":
|
| 500 |
+
for rgba in im.palette.colors:
|
| 501 |
+
if rgba[3] == 0:
|
| 502 |
+
im.info["transparency"] = im.palette.colors[rgba]
|
| 503 |
+
break
|
| 504 |
+
return im
|
| 505 |
+
return im.convert("L")
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
_Palette = Union[bytes, bytearray, List[int], ImagePalette.ImagePalette]
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _normalize_palette(
|
| 512 |
+
im: Image.Image, palette: _Palette | None, info: dict[str, Any]
|
| 513 |
+
) -> Image.Image:
|
| 514 |
+
"""
|
| 515 |
+
Normalizes the palette for image.
|
| 516 |
+
- Sets the palette to the incoming palette, if provided.
|
| 517 |
+
- Ensures that there's a palette for L mode images
|
| 518 |
+
- Optimizes the palette if necessary/desired.
|
| 519 |
+
|
| 520 |
+
:param im: Image object
|
| 521 |
+
:param palette: bytes object containing the source palette, or ....
|
| 522 |
+
:param info: encoderinfo
|
| 523 |
+
:returns: Image object
|
| 524 |
+
"""
|
| 525 |
+
source_palette = None
|
| 526 |
+
if palette:
|
| 527 |
+
# a bytes palette
|
| 528 |
+
if isinstance(palette, (bytes, bytearray, list)):
|
| 529 |
+
source_palette = bytearray(palette[:768])
|
| 530 |
+
if isinstance(palette, ImagePalette.ImagePalette):
|
| 531 |
+
source_palette = bytearray(palette.palette)
|
| 532 |
+
|
| 533 |
+
if im.mode == "P":
|
| 534 |
+
if not source_palette:
|
| 535 |
+
source_palette = im.im.getpalette("RGB")[:768]
|
| 536 |
+
else: # L-mode
|
| 537 |
+
if not source_palette:
|
| 538 |
+
source_palette = bytearray(i // 3 for i in range(768))
|
| 539 |
+
im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
|
| 540 |
+
|
| 541 |
+
used_palette_colors: list[int] | None
|
| 542 |
+
if palette:
|
| 543 |
+
used_palette_colors = []
|
| 544 |
+
assert source_palette is not None
|
| 545 |
+
for i in range(0, len(source_palette), 3):
|
| 546 |
+
source_color = tuple(source_palette[i : i + 3])
|
| 547 |
+
index = im.palette.colors.get(source_color)
|
| 548 |
+
if index in used_palette_colors:
|
| 549 |
+
index = None
|
| 550 |
+
used_palette_colors.append(index)
|
| 551 |
+
for i, index in enumerate(used_palette_colors):
|
| 552 |
+
if index is None:
|
| 553 |
+
for j in range(len(used_palette_colors)):
|
| 554 |
+
if j not in used_palette_colors:
|
| 555 |
+
used_palette_colors[i] = j
|
| 556 |
+
break
|
| 557 |
+
im = im.remap_palette(used_palette_colors)
|
| 558 |
+
else:
|
| 559 |
+
used_palette_colors = _get_optimize(im, info)
|
| 560 |
+
if used_palette_colors is not None:
|
| 561 |
+
im = im.remap_palette(used_palette_colors, source_palette)
|
| 562 |
+
if "transparency" in info:
|
| 563 |
+
try:
|
| 564 |
+
info["transparency"] = used_palette_colors.index(
|
| 565 |
+
info["transparency"]
|
| 566 |
+
)
|
| 567 |
+
except ValueError:
|
| 568 |
+
del info["transparency"]
|
| 569 |
+
return im
|
| 570 |
+
|
| 571 |
+
im.palette.palette = source_palette
|
| 572 |
+
return im
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _write_single_frame(
|
| 576 |
+
im: Image.Image,
|
| 577 |
+
fp: IO[bytes],
|
| 578 |
+
palette: _Palette | None,
|
| 579 |
+
) -> None:
|
| 580 |
+
im_out = _normalize_mode(im)
|
| 581 |
+
for k, v in im_out.info.items():
|
| 582 |
+
im.encoderinfo.setdefault(k, v)
|
| 583 |
+
im_out = _normalize_palette(im_out, palette, im.encoderinfo)
|
| 584 |
+
|
| 585 |
+
for s in _get_global_header(im_out, im.encoderinfo):
|
| 586 |
+
fp.write(s)
|
| 587 |
+
|
| 588 |
+
# local image header
|
| 589 |
+
flags = 0
|
| 590 |
+
if get_interlace(im):
|
| 591 |
+
flags = flags | 64
|
| 592 |
+
_write_local_header(fp, im, (0, 0), flags)
|
| 593 |
+
|
| 594 |
+
im_out.encoderconfig = (8, get_interlace(im))
|
| 595 |
+
ImageFile._save(im_out, fp, [("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])])
|
| 596 |
+
|
| 597 |
+
fp.write(b"\0") # end of image data
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def _getbbox(
|
| 601 |
+
base_im: Image.Image, im_frame: Image.Image
|
| 602 |
+
) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
|
| 603 |
+
if _get_palette_bytes(im_frame) != _get_palette_bytes(base_im):
|
| 604 |
+
im_frame = im_frame.convert("RGBA")
|
| 605 |
+
base_im = base_im.convert("RGBA")
|
| 606 |
+
delta = ImageChops.subtract_modulo(im_frame, base_im)
|
| 607 |
+
return delta, delta.getbbox(alpha_only=False)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
class _Frame(NamedTuple):
|
| 611 |
+
im: Image.Image
|
| 612 |
+
bbox: tuple[int, int, int, int] | None
|
| 613 |
+
encoderinfo: dict[str, Any]
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_multiple_frames(
|
| 617 |
+
im: Image.Image, fp: IO[bytes], palette: _Palette | None
|
| 618 |
+
) -> bool:
|
| 619 |
+
duration = im.encoderinfo.get("duration")
|
| 620 |
+
disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
|
| 621 |
+
|
| 622 |
+
im_frames: list[_Frame] = []
|
| 623 |
+
previous_im: Image.Image | None = None
|
| 624 |
+
frame_count = 0
|
| 625 |
+
background_im = None
|
| 626 |
+
for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
|
| 627 |
+
for im_frame in ImageSequence.Iterator(imSequence):
|
| 628 |
+
# a copy is required here since seek can still mutate the image
|
| 629 |
+
im_frame = _normalize_mode(im_frame.copy())
|
| 630 |
+
if frame_count == 0:
|
| 631 |
+
for k, v in im_frame.info.items():
|
| 632 |
+
if k == "transparency":
|
| 633 |
+
continue
|
| 634 |
+
im.encoderinfo.setdefault(k, v)
|
| 635 |
+
|
| 636 |
+
encoderinfo = im.encoderinfo.copy()
|
| 637 |
+
if "transparency" in im_frame.info:
|
| 638 |
+
encoderinfo.setdefault("transparency", im_frame.info["transparency"])
|
| 639 |
+
im_frame = _normalize_palette(im_frame, palette, encoderinfo)
|
| 640 |
+
if isinstance(duration, (list, tuple)):
|
| 641 |
+
encoderinfo["duration"] = duration[frame_count]
|
| 642 |
+
elif duration is None and "duration" in im_frame.info:
|
| 643 |
+
encoderinfo["duration"] = im_frame.info["duration"]
|
| 644 |
+
if isinstance(disposal, (list, tuple)):
|
| 645 |
+
encoderinfo["disposal"] = disposal[frame_count]
|
| 646 |
+
frame_count += 1
|
| 647 |
+
|
| 648 |
+
diff_frame = None
|
| 649 |
+
if im_frames and previous_im:
|
| 650 |
+
# delta frame
|
| 651 |
+
delta, bbox = _getbbox(previous_im, im_frame)
|
| 652 |
+
if not bbox:
|
| 653 |
+
# This frame is identical to the previous frame
|
| 654 |
+
if encoderinfo.get("duration"):
|
| 655 |
+
im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"]
|
| 656 |
+
continue
|
| 657 |
+
if im_frames[-1].encoderinfo.get("disposal") == 2:
|
| 658 |
+
if background_im is None:
|
| 659 |
+
color = im.encoderinfo.get(
|
| 660 |
+
"transparency", im.info.get("transparency", (0, 0, 0))
|
| 661 |
+
)
|
| 662 |
+
background = _get_background(im_frame, color)
|
| 663 |
+
background_im = Image.new("P", im_frame.size, background)
|
| 664 |
+
background_im.putpalette(im_frames[0].im.palette)
|
| 665 |
+
bbox = _getbbox(background_im, im_frame)[1]
|
| 666 |
+
elif encoderinfo.get("optimize") and im_frame.mode != "1":
|
| 667 |
+
if "transparency" not in encoderinfo:
|
| 668 |
+
try:
|
| 669 |
+
encoderinfo["transparency"] = (
|
| 670 |
+
im_frame.palette._new_color_index(im_frame)
|
| 671 |
+
)
|
| 672 |
+
except ValueError:
|
| 673 |
+
pass
|
| 674 |
+
if "transparency" in encoderinfo:
|
| 675 |
+
# When the delta is zero, fill the image with transparency
|
| 676 |
+
diff_frame = im_frame.copy()
|
| 677 |
+
fill = Image.new("P", delta.size, encoderinfo["transparency"])
|
| 678 |
+
if delta.mode == "RGBA":
|
| 679 |
+
r, g, b, a = delta.split()
|
| 680 |
+
mask = ImageMath.lambda_eval(
|
| 681 |
+
lambda args: args["convert"](
|
| 682 |
+
args["max"](
|
| 683 |
+
args["max"](
|
| 684 |
+
args["max"](args["r"], args["g"]), args["b"]
|
| 685 |
+
),
|
| 686 |
+
args["a"],
|
| 687 |
+
)
|
| 688 |
+
* 255,
|
| 689 |
+
"1",
|
| 690 |
+
),
|
| 691 |
+
r=r,
|
| 692 |
+
g=g,
|
| 693 |
+
b=b,
|
| 694 |
+
a=a,
|
| 695 |
+
)
|
| 696 |
+
else:
|
| 697 |
+
if delta.mode == "P":
|
| 698 |
+
# Convert to L without considering palette
|
| 699 |
+
delta_l = Image.new("L", delta.size)
|
| 700 |
+
delta_l.putdata(delta.getdata())
|
| 701 |
+
delta = delta_l
|
| 702 |
+
mask = ImageMath.lambda_eval(
|
| 703 |
+
lambda args: args["convert"](args["im"] * 255, "1"),
|
| 704 |
+
im=delta,
|
| 705 |
+
)
|
| 706 |
+
diff_frame.paste(fill, mask=ImageOps.invert(mask))
|
| 707 |
+
else:
|
| 708 |
+
bbox = None
|
| 709 |
+
previous_im = im_frame
|
| 710 |
+
im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
|
| 711 |
+
|
| 712 |
+
if len(im_frames) == 1:
|
| 713 |
+
if "duration" in im.encoderinfo:
|
| 714 |
+
# Since multiple frames will not be written, use the combined duration
|
| 715 |
+
im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
|
| 716 |
+
return False
|
| 717 |
+
|
| 718 |
+
for frame_data in im_frames:
|
| 719 |
+
im_frame = frame_data.im
|
| 720 |
+
if not frame_data.bbox:
|
| 721 |
+
# global header
|
| 722 |
+
for s in _get_global_header(im_frame, frame_data.encoderinfo):
|
| 723 |
+
fp.write(s)
|
| 724 |
+
offset = (0, 0)
|
| 725 |
+
else:
|
| 726 |
+
# compress difference
|
| 727 |
+
if not palette:
|
| 728 |
+
frame_data.encoderinfo["include_color_table"] = True
|
| 729 |
+
|
| 730 |
+
im_frame = im_frame.crop(frame_data.bbox)
|
| 731 |
+
offset = frame_data.bbox[:2]
|
| 732 |
+
_write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
|
| 733 |
+
return True
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 737 |
+
_save(im, fp, filename, save_all=True)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _save(
|
| 741 |
+
im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
|
| 742 |
+
) -> None:
|
| 743 |
+
# header
|
| 744 |
+
if "palette" in im.encoderinfo or "palette" in im.info:
|
| 745 |
+
palette = im.encoderinfo.get("palette", im.info.get("palette"))
|
| 746 |
+
else:
|
| 747 |
+
palette = None
|
| 748 |
+
im.encoderinfo.setdefault("optimize", True)
|
| 749 |
+
|
| 750 |
+
if not save_all or not _write_multiple_frames(im, fp, palette):
|
| 751 |
+
_write_single_frame(im, fp, palette)
|
| 752 |
+
|
| 753 |
+
fp.write(b";") # end of file
|
| 754 |
+
|
| 755 |
+
if hasattr(fp, "flush"):
|
| 756 |
+
fp.flush()
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def get_interlace(im: Image.Image) -> int:
|
| 760 |
+
interlace = im.encoderinfo.get("interlace", 1)
|
| 761 |
+
|
| 762 |
+
# workaround for @PIL153
|
| 763 |
+
if min(im.size) < 16:
|
| 764 |
+
interlace = 0
|
| 765 |
+
|
| 766 |
+
return interlace
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def _write_local_header(
|
| 770 |
+
fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
|
| 771 |
+
) -> None:
|
| 772 |
+
try:
|
| 773 |
+
transparency = im.encoderinfo["transparency"]
|
| 774 |
+
except KeyError:
|
| 775 |
+
transparency = None
|
| 776 |
+
|
| 777 |
+
if "duration" in im.encoderinfo:
|
| 778 |
+
duration = int(im.encoderinfo["duration"] / 10)
|
| 779 |
+
else:
|
| 780 |
+
duration = 0
|
| 781 |
+
|
| 782 |
+
disposal = int(im.encoderinfo.get("disposal", 0))
|
| 783 |
+
|
| 784 |
+
if transparency is not None or duration != 0 or disposal:
|
| 785 |
+
packed_flag = 1 if transparency is not None else 0
|
| 786 |
+
packed_flag |= disposal << 2
|
| 787 |
+
|
| 788 |
+
fp.write(
|
| 789 |
+
b"!"
|
| 790 |
+
+ o8(249) # extension intro
|
| 791 |
+
+ o8(4) # length
|
| 792 |
+
+ o8(packed_flag) # packed fields
|
| 793 |
+
+ o16(duration) # duration
|
| 794 |
+
+ o8(transparency or 0) # transparency index
|
| 795 |
+
+ o8(0)
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
include_color_table = im.encoderinfo.get("include_color_table")
|
| 799 |
+
if include_color_table:
|
| 800 |
+
palette_bytes = _get_palette_bytes(im)
|
| 801 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 802 |
+
if color_table_size:
|
| 803 |
+
flags = flags | 128 # local color table flag
|
| 804 |
+
flags = flags | color_table_size
|
| 805 |
+
|
| 806 |
+
fp.write(
|
| 807 |
+
b","
|
| 808 |
+
+ o16(offset[0]) # offset
|
| 809 |
+
+ o16(offset[1])
|
| 810 |
+
+ o16(im.size[0]) # size
|
| 811 |
+
+ o16(im.size[1])
|
| 812 |
+
+ o8(flags) # flags
|
| 813 |
+
)
|
| 814 |
+
if include_color_table and color_table_size:
|
| 815 |
+
fp.write(_get_header_palette(palette_bytes))
|
| 816 |
+
fp.write(o8(8)) # bits
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 820 |
+
# Unused by default.
|
| 821 |
+
# To use, uncomment the register_save call at the end of the file.
|
| 822 |
+
#
|
| 823 |
+
# If you need real GIF compression and/or RGB quantization, you
|
| 824 |
+
# can use the external NETPBM/PBMPLUS utilities. See comments
|
| 825 |
+
# below for information on how to enable this.
|
| 826 |
+
tempfile = im._dump()
|
| 827 |
+
|
| 828 |
+
try:
|
| 829 |
+
with open(filename, "wb") as f:
|
| 830 |
+
if im.mode != "RGB":
|
| 831 |
+
subprocess.check_call(
|
| 832 |
+
["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
|
| 833 |
+
)
|
| 834 |
+
else:
|
| 835 |
+
# Pipe ppmquant output into ppmtogif
|
| 836 |
+
# "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
|
| 837 |
+
quant_cmd = ["ppmquant", "256", tempfile]
|
| 838 |
+
togif_cmd = ["ppmtogif"]
|
| 839 |
+
quant_proc = subprocess.Popen(
|
| 840 |
+
quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
|
| 841 |
+
)
|
| 842 |
+
togif_proc = subprocess.Popen(
|
| 843 |
+
togif_cmd,
|
| 844 |
+
stdin=quant_proc.stdout,
|
| 845 |
+
stdout=f,
|
| 846 |
+
stderr=subprocess.DEVNULL,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
# Allow ppmquant to receive SIGPIPE if ppmtogif exits
|
| 850 |
+
assert quant_proc.stdout is not None
|
| 851 |
+
quant_proc.stdout.close()
|
| 852 |
+
|
| 853 |
+
retcode = quant_proc.wait()
|
| 854 |
+
if retcode:
|
| 855 |
+
raise subprocess.CalledProcessError(retcode, quant_cmd)
|
| 856 |
+
|
| 857 |
+
retcode = togif_proc.wait()
|
| 858 |
+
if retcode:
|
| 859 |
+
raise subprocess.CalledProcessError(retcode, togif_cmd)
|
| 860 |
+
finally:
|
| 861 |
+
try:
|
| 862 |
+
os.unlink(tempfile)
|
| 863 |
+
except OSError:
|
| 864 |
+
pass
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
# Force optimization so that we can test performance against
|
| 868 |
+
# cases where it took lots of memory and time previously.
|
| 869 |
+
_FORCE_OPTIMIZE = False
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
|
| 873 |
+
"""
|
| 874 |
+
Palette optimization is a potentially expensive operation.
|
| 875 |
+
|
| 876 |
+
This function determines if the palette should be optimized using
|
| 877 |
+
some heuristics, then returns the list of palette entries in use.
|
| 878 |
+
|
| 879 |
+
:param im: Image object
|
| 880 |
+
:param info: encoderinfo
|
| 881 |
+
:returns: list of indexes of palette entries in use, or None
|
| 882 |
+
"""
|
| 883 |
+
if im.mode in ("P", "L") and info and info.get("optimize"):
|
| 884 |
+
# Potentially expensive operation.
|
| 885 |
+
|
| 886 |
+
# The palette saves 3 bytes per color not used, but palette
|
| 887 |
+
# lengths are restricted to 3*(2**N) bytes. Max saving would
|
| 888 |
+
# be 768 -> 6 bytes if we went all the way down to 2 colors.
|
| 889 |
+
# * If we're over 128 colors, we can't save any space.
|
| 890 |
+
# * If there aren't any holes, it's not worth collapsing.
|
| 891 |
+
# * If we have a 'large' image, the palette is in the noise.
|
| 892 |
+
|
| 893 |
+
# create the new palette if not every color is used
|
| 894 |
+
optimise = _FORCE_OPTIMIZE or im.mode == "L"
|
| 895 |
+
if optimise or im.width * im.height < 512 * 512:
|
| 896 |
+
# check which colors are used
|
| 897 |
+
used_palette_colors = []
|
| 898 |
+
for i, count in enumerate(im.histogram()):
|
| 899 |
+
if count:
|
| 900 |
+
used_palette_colors.append(i)
|
| 901 |
+
|
| 902 |
+
if optimise or max(used_palette_colors) >= len(used_palette_colors):
|
| 903 |
+
return used_palette_colors
|
| 904 |
+
|
| 905 |
+
num_palette_colors = len(im.palette.palette) // Image.getmodebands(
|
| 906 |
+
im.palette.mode
|
| 907 |
+
)
|
| 908 |
+
current_palette_size = 1 << (num_palette_colors - 1).bit_length()
|
| 909 |
+
if (
|
| 910 |
+
# check that the palette would become smaller when saved
|
| 911 |
+
len(used_palette_colors) <= current_palette_size // 2
|
| 912 |
+
# check that the palette is not already the smallest possible size
|
| 913 |
+
and current_palette_size > 2
|
| 914 |
+
):
|
| 915 |
+
return used_palette_colors
|
| 916 |
+
return None
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def _get_color_table_size(palette_bytes: bytes) -> int:
|
| 920 |
+
# calculate the palette size for the header
|
| 921 |
+
if not palette_bytes:
|
| 922 |
+
return 0
|
| 923 |
+
elif len(palette_bytes) < 9:
|
| 924 |
+
return 1
|
| 925 |
+
else:
|
| 926 |
+
return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def _get_header_palette(palette_bytes: bytes) -> bytes:
|
| 930 |
+
"""
|
| 931 |
+
Returns the palette, null padded to the next power of 2 (*3) bytes
|
| 932 |
+
suitable for direct inclusion in the GIF header
|
| 933 |
+
|
| 934 |
+
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
|
| 935 |
+
:returns: Null padded palette
|
| 936 |
+
"""
|
| 937 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 938 |
+
|
| 939 |
+
# add the missing amount of bytes
|
| 940 |
+
# the palette has to be 2<<n in size
|
| 941 |
+
actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
|
| 942 |
+
if actual_target_size_diff > 0:
|
| 943 |
+
palette_bytes += o8(0) * 3 * actual_target_size_diff
|
| 944 |
+
return palette_bytes
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
def _get_palette_bytes(im: Image.Image) -> bytes:
|
| 948 |
+
"""
|
| 949 |
+
Gets the palette for inclusion in the gif header
|
| 950 |
+
|
| 951 |
+
:param im: Image object
|
| 952 |
+
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
| 953 |
+
"""
|
| 954 |
+
return im.palette.palette if im.palette else b""
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def _get_background(
|
| 958 |
+
im: Image.Image,
|
| 959 |
+
info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
|
| 960 |
+
) -> int:
|
| 961 |
+
background = 0
|
| 962 |
+
if info_background:
|
| 963 |
+
if isinstance(info_background, tuple):
|
| 964 |
+
# WebPImagePlugin stores an RGBA value in info["background"]
|
| 965 |
+
# So it must be converted to the same format as GifImagePlugin's
|
| 966 |
+
# info["background"] - a global color table index
|
| 967 |
+
try:
|
| 968 |
+
background = im.palette.getcolor(info_background, im)
|
| 969 |
+
except ValueError as e:
|
| 970 |
+
if str(e) not in (
|
| 971 |
+
# If all 256 colors are in use,
|
| 972 |
+
# then there is no need for the background color
|
| 973 |
+
"cannot allocate more than 256 colors",
|
| 974 |
+
# Ignore non-opaque WebP background
|
| 975 |
+
"cannot add non-opaque RGBA color to RGB palette",
|
| 976 |
+
):
|
| 977 |
+
raise
|
| 978 |
+
else:
|
| 979 |
+
background = info_background
|
| 980 |
+
return background
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
|
| 984 |
+
"""Return a list of strings representing a GIF header"""
|
| 985 |
+
|
| 986 |
+
# Header Block
|
| 987 |
+
# https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
|
| 988 |
+
|
| 989 |
+
version = b"87a"
|
| 990 |
+
if im.info.get("version") == b"89a" or (
|
| 991 |
+
info
|
| 992 |
+
and (
|
| 993 |
+
"transparency" in info
|
| 994 |
+
or info.get("loop") is not None
|
| 995 |
+
or info.get("duration")
|
| 996 |
+
or info.get("comment")
|
| 997 |
+
)
|
| 998 |
+
):
|
| 999 |
+
version = b"89a"
|
| 1000 |
+
|
| 1001 |
+
background = _get_background(im, info.get("background"))
|
| 1002 |
+
|
| 1003 |
+
palette_bytes = _get_palette_bytes(im)
|
| 1004 |
+
color_table_size = _get_color_table_size(palette_bytes)
|
| 1005 |
+
|
| 1006 |
+
header = [
|
| 1007 |
+
b"GIF" # signature
|
| 1008 |
+
+ version # version
|
| 1009 |
+
+ o16(im.size[0]) # canvas width
|
| 1010 |
+
+ o16(im.size[1]), # canvas height
|
| 1011 |
+
# Logical Screen Descriptor
|
| 1012 |
+
# size of global color table + global color table flag
|
| 1013 |
+
o8(color_table_size + 128), # packed fields
|
| 1014 |
+
# background + reserved/aspect
|
| 1015 |
+
o8(background) + o8(0),
|
| 1016 |
+
# Global Color Table
|
| 1017 |
+
_get_header_palette(palette_bytes),
|
| 1018 |
+
]
|
| 1019 |
+
if info.get("loop") is not None:
|
| 1020 |
+
header.append(
|
| 1021 |
+
b"!"
|
| 1022 |
+
+ o8(255) # extension intro
|
| 1023 |
+
+ o8(11)
|
| 1024 |
+
+ b"NETSCAPE2.0"
|
| 1025 |
+
+ o8(3)
|
| 1026 |
+
+ o8(1)
|
| 1027 |
+
+ o16(info["loop"]) # number of loops
|
| 1028 |
+
+ o8(0)
|
| 1029 |
+
)
|
| 1030 |
+
if info.get("comment"):
|
| 1031 |
+
comment_block = b"!" + o8(254) # extension intro
|
| 1032 |
+
|
| 1033 |
+
comment = info["comment"]
|
| 1034 |
+
if isinstance(comment, str):
|
| 1035 |
+
comment = comment.encode()
|
| 1036 |
+
for i in range(0, len(comment), 255):
|
| 1037 |
+
subblock = comment[i : i + 255]
|
| 1038 |
+
comment_block += o8(len(subblock)) + subblock
|
| 1039 |
+
|
| 1040 |
+
comment_block += o8(0)
|
| 1041 |
+
header.append(comment_block)
|
| 1042 |
+
return header
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def _write_frame_data(
|
| 1046 |
+
fp: IO[bytes],
|
| 1047 |
+
im_frame: Image.Image,
|
| 1048 |
+
offset: tuple[int, int],
|
| 1049 |
+
params: dict[str, Any],
|
| 1050 |
+
) -> None:
|
| 1051 |
+
try:
|
| 1052 |
+
im_frame.encoderinfo = params
|
| 1053 |
+
|
| 1054 |
+
# local image header
|
| 1055 |
+
_write_local_header(fp, im_frame, offset, 0)
|
| 1056 |
+
|
| 1057 |
+
ImageFile._save(
|
| 1058 |
+
im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])]
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
fp.write(b"\0") # end of image data
|
| 1062 |
+
finally:
|
| 1063 |
+
del im_frame.encoderinfo
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
# --------------------------------------------------------------------
|
| 1067 |
+
# Legacy GIF utilities
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
def getheader(
|
| 1071 |
+
im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
|
| 1072 |
+
) -> tuple[list[bytes], list[int] | None]:
|
| 1073 |
+
"""
|
| 1074 |
+
Legacy Method to get Gif data from image.
|
| 1075 |
+
|
| 1076 |
+
Warning:: May modify image data.
|
| 1077 |
+
|
| 1078 |
+
:param im: Image object
|
| 1079 |
+
:param palette: bytes object containing the source palette, or ....
|
| 1080 |
+
:param info: encoderinfo
|
| 1081 |
+
:returns: tuple of(list of header items, optimized palette)
|
| 1082 |
+
|
| 1083 |
+
"""
|
| 1084 |
+
if info is None:
|
| 1085 |
+
info = {}
|
| 1086 |
+
|
| 1087 |
+
used_palette_colors = _get_optimize(im, info)
|
| 1088 |
+
|
| 1089 |
+
if "background" not in info and "background" in im.info:
|
| 1090 |
+
info["background"] = im.info["background"]
|
| 1091 |
+
|
| 1092 |
+
im_mod = _normalize_palette(im, palette, info)
|
| 1093 |
+
im.palette = im_mod.palette
|
| 1094 |
+
im.im = im_mod.im
|
| 1095 |
+
header = _get_global_header(im, info)
|
| 1096 |
+
|
| 1097 |
+
return header, used_palette_colors
|
| 1098 |
+
|
| 1099 |
+
|
| 1100 |
+
def getdata(
|
| 1101 |
+
im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
|
| 1102 |
+
) -> list[bytes]:
|
| 1103 |
+
"""
|
| 1104 |
+
Legacy Method
|
| 1105 |
+
|
| 1106 |
+
Return a list of strings representing this image.
|
| 1107 |
+
The first string is a local image header, the rest contains
|
| 1108 |
+
encoded image data.
|
| 1109 |
+
|
| 1110 |
+
To specify duration, add the time in milliseconds,
|
| 1111 |
+
e.g. ``getdata(im_frame, duration=1000)``
|
| 1112 |
+
|
| 1113 |
+
:param im: Image object
|
| 1114 |
+
:param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
|
| 1115 |
+
:param \\**params: e.g. duration or other encoder info parameters
|
| 1116 |
+
:returns: List of bytes containing GIF encoded frame data
|
| 1117 |
+
|
| 1118 |
+
"""
|
| 1119 |
+
from io import BytesIO
|
| 1120 |
+
|
| 1121 |
+
class Collector(BytesIO):
|
| 1122 |
+
data = []
|
| 1123 |
+
|
| 1124 |
+
if sys.version_info >= (3, 12):
|
| 1125 |
+
from collections.abc import Buffer
|
| 1126 |
+
|
| 1127 |
+
def write(self, data: Buffer) -> int:
|
| 1128 |
+
self.data.append(data)
|
| 1129 |
+
return len(data)
|
| 1130 |
+
|
| 1131 |
+
else:
|
| 1132 |
+
|
| 1133 |
+
def write(self, data: Any) -> int:
|
| 1134 |
+
self.data.append(data)
|
| 1135 |
+
return len(data)
|
| 1136 |
+
|
| 1137 |
+
im.load() # make sure raster data is available
|
| 1138 |
+
|
| 1139 |
+
fp = Collector()
|
| 1140 |
+
|
| 1141 |
+
_write_frame_data(fp, im, offset, params)
|
| 1142 |
+
|
| 1143 |
+
return fp.data
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
# --------------------------------------------------------------------
|
| 1147 |
+
# Registry
|
| 1148 |
+
|
| 1149 |
+
Image.register_open(GifImageFile.format, GifImageFile, _accept)
|
| 1150 |
+
Image.register_save(GifImageFile.format, _save)
|
| 1151 |
+
Image.register_save_all(GifImageFile.format, _save_all)
|
| 1152 |
+
Image.register_extension(GifImageFile.format, ".gif")
|
| 1153 |
+
Image.register_mime(GifImageFile.format, "image/gif")
|
| 1154 |
+
|
| 1155 |
+
#
|
| 1156 |
+
# Uncomment the following line if you wish to use NETPBM/PBMPLUS
|
| 1157 |
+
# instead of the built-in "uncompressed" GIF encoder
|
| 1158 |
+
|
| 1159 |
+
# Image.register_save(GifImageFile.format, _save_netpbm)
|
.venv/lib/python3.11/site-packages/PIL/IcnsImagePlugin.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# macOS icns file decoder, based on icns.py by Bob Ippolito.
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
|
| 9 |
+
# 2020-04-04 Allow saving on all operating systems.
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2004 by Bob Ippolito.
|
| 12 |
+
# Copyright (c) 2004 by Secret Labs.
|
| 13 |
+
# Copyright (c) 2004 by Fredrik Lundh.
|
| 14 |
+
# Copyright (c) 2014 by Alastair Houghton.
|
| 15 |
+
# Copyright (c) 2020 by Pan Jing.
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import io
|
| 22 |
+
import os
|
| 23 |
+
import struct
|
| 24 |
+
import sys
|
| 25 |
+
from typing import IO
|
| 26 |
+
|
| 27 |
+
from . import Image, ImageFile, PngImagePlugin, features
|
| 28 |
+
|
| 29 |
+
enable_jpeg2k = features.check_codec("jpg_2000")
|
| 30 |
+
if enable_jpeg2k:
|
| 31 |
+
from . import Jpeg2KImagePlugin
|
| 32 |
+
|
| 33 |
+
MAGIC = b"icns"
|
| 34 |
+
HEADERSIZE = 8
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def nextheader(fobj):
|
| 38 |
+
return struct.unpack(">4sI", fobj.read(HEADERSIZE))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def read_32t(fobj, start_length, size):
|
| 42 |
+
# The 128x128 icon seems to have an extra header for some reason.
|
| 43 |
+
(start, length) = start_length
|
| 44 |
+
fobj.seek(start)
|
| 45 |
+
sig = fobj.read(4)
|
| 46 |
+
if sig != b"\x00\x00\x00\x00":
|
| 47 |
+
msg = "Unknown signature, expecting 0x00000000"
|
| 48 |
+
raise SyntaxError(msg)
|
| 49 |
+
return read_32(fobj, (start + 4, length - 4), size)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def read_32(fobj, start_length, size):
|
| 53 |
+
"""
|
| 54 |
+
Read a 32bit RGB icon resource. Seems to be either uncompressed or
|
| 55 |
+
an RLE packbits-like scheme.
|
| 56 |
+
"""
|
| 57 |
+
(start, length) = start_length
|
| 58 |
+
fobj.seek(start)
|
| 59 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 60 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 61 |
+
if length == sizesq * 3:
|
| 62 |
+
# uncompressed ("RGBRGBGB")
|
| 63 |
+
indata = fobj.read(length)
|
| 64 |
+
im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
|
| 65 |
+
else:
|
| 66 |
+
# decode image
|
| 67 |
+
im = Image.new("RGB", pixel_size, None)
|
| 68 |
+
for band_ix in range(3):
|
| 69 |
+
data = []
|
| 70 |
+
bytesleft = sizesq
|
| 71 |
+
while bytesleft > 0:
|
| 72 |
+
byte = fobj.read(1)
|
| 73 |
+
if not byte:
|
| 74 |
+
break
|
| 75 |
+
byte = byte[0]
|
| 76 |
+
if byte & 0x80:
|
| 77 |
+
blocksize = byte - 125
|
| 78 |
+
byte = fobj.read(1)
|
| 79 |
+
for i in range(blocksize):
|
| 80 |
+
data.append(byte)
|
| 81 |
+
else:
|
| 82 |
+
blocksize = byte + 1
|
| 83 |
+
data.append(fobj.read(blocksize))
|
| 84 |
+
bytesleft -= blocksize
|
| 85 |
+
if bytesleft <= 0:
|
| 86 |
+
break
|
| 87 |
+
if bytesleft != 0:
|
| 88 |
+
msg = f"Error reading channel [{repr(bytesleft)} left]"
|
| 89 |
+
raise SyntaxError(msg)
|
| 90 |
+
band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
|
| 91 |
+
im.im.putband(band.im, band_ix)
|
| 92 |
+
return {"RGB": im}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def read_mk(fobj, start_length, size):
|
| 96 |
+
# Alpha masks seem to be uncompressed
|
| 97 |
+
start = start_length[0]
|
| 98 |
+
fobj.seek(start)
|
| 99 |
+
pixel_size = (size[0] * size[2], size[1] * size[2])
|
| 100 |
+
sizesq = pixel_size[0] * pixel_size[1]
|
| 101 |
+
band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
|
| 102 |
+
return {"A": band}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def read_png_or_jpeg2000(fobj, start_length, size):
|
| 106 |
+
(start, length) = start_length
|
| 107 |
+
fobj.seek(start)
|
| 108 |
+
sig = fobj.read(12)
|
| 109 |
+
if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
|
| 110 |
+
fobj.seek(start)
|
| 111 |
+
im = PngImagePlugin.PngImageFile(fobj)
|
| 112 |
+
Image._decompression_bomb_check(im.size)
|
| 113 |
+
return {"RGBA": im}
|
| 114 |
+
elif (
|
| 115 |
+
sig[:4] == b"\xff\x4f\xff\x51"
|
| 116 |
+
or sig[:4] == b"\x0d\x0a\x87\x0a"
|
| 117 |
+
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
|
| 118 |
+
):
|
| 119 |
+
if not enable_jpeg2k:
|
| 120 |
+
msg = (
|
| 121 |
+
"Unsupported icon subimage format (rebuild PIL "
|
| 122 |
+
"with JPEG 2000 support to fix this)"
|
| 123 |
+
)
|
| 124 |
+
raise ValueError(msg)
|
| 125 |
+
# j2k, jpc or j2c
|
| 126 |
+
fobj.seek(start)
|
| 127 |
+
jp2kstream = fobj.read(length)
|
| 128 |
+
f = io.BytesIO(jp2kstream)
|
| 129 |
+
im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
|
| 130 |
+
Image._decompression_bomb_check(im.size)
|
| 131 |
+
if im.mode != "RGBA":
|
| 132 |
+
im = im.convert("RGBA")
|
| 133 |
+
return {"RGBA": im}
|
| 134 |
+
else:
|
| 135 |
+
msg = "Unsupported icon subimage format"
|
| 136 |
+
raise ValueError(msg)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class IcnsFile:
|
| 140 |
+
SIZES = {
|
| 141 |
+
(512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
|
| 142 |
+
(512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
|
| 143 |
+
(256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
|
| 144 |
+
(256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
|
| 145 |
+
(128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
|
| 146 |
+
(128, 128, 1): [
|
| 147 |
+
(b"ic07", read_png_or_jpeg2000),
|
| 148 |
+
(b"it32", read_32t),
|
| 149 |
+
(b"t8mk", read_mk),
|
| 150 |
+
],
|
| 151 |
+
(64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
|
| 152 |
+
(32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
|
| 153 |
+
(48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
|
| 154 |
+
(32, 32, 1): [
|
| 155 |
+
(b"icp5", read_png_or_jpeg2000),
|
| 156 |
+
(b"il32", read_32),
|
| 157 |
+
(b"l8mk", read_mk),
|
| 158 |
+
],
|
| 159 |
+
(16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
|
| 160 |
+
(16, 16, 1): [
|
| 161 |
+
(b"icp4", read_png_or_jpeg2000),
|
| 162 |
+
(b"is32", read_32),
|
| 163 |
+
(b"s8mk", read_mk),
|
| 164 |
+
],
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
def __init__(self, fobj):
|
| 168 |
+
"""
|
| 169 |
+
fobj is a file-like object as an icns resource
|
| 170 |
+
"""
|
| 171 |
+
# signature : (start, length)
|
| 172 |
+
self.dct = dct = {}
|
| 173 |
+
self.fobj = fobj
|
| 174 |
+
sig, filesize = nextheader(fobj)
|
| 175 |
+
if not _accept(sig):
|
| 176 |
+
msg = "not an icns file"
|
| 177 |
+
raise SyntaxError(msg)
|
| 178 |
+
i = HEADERSIZE
|
| 179 |
+
while i < filesize:
|
| 180 |
+
sig, blocksize = nextheader(fobj)
|
| 181 |
+
if blocksize <= 0:
|
| 182 |
+
msg = "invalid block header"
|
| 183 |
+
raise SyntaxError(msg)
|
| 184 |
+
i += HEADERSIZE
|
| 185 |
+
blocksize -= HEADERSIZE
|
| 186 |
+
dct[sig] = (i, blocksize)
|
| 187 |
+
fobj.seek(blocksize, io.SEEK_CUR)
|
| 188 |
+
i += blocksize
|
| 189 |
+
|
| 190 |
+
def itersizes(self):
|
| 191 |
+
sizes = []
|
| 192 |
+
for size, fmts in self.SIZES.items():
|
| 193 |
+
for fmt, reader in fmts:
|
| 194 |
+
if fmt in self.dct:
|
| 195 |
+
sizes.append(size)
|
| 196 |
+
break
|
| 197 |
+
return sizes
|
| 198 |
+
|
| 199 |
+
def bestsize(self):
|
| 200 |
+
sizes = self.itersizes()
|
| 201 |
+
if not sizes:
|
| 202 |
+
msg = "No 32bit icon resources found"
|
| 203 |
+
raise SyntaxError(msg)
|
| 204 |
+
return max(sizes)
|
| 205 |
+
|
| 206 |
+
def dataforsize(self, size):
|
| 207 |
+
"""
|
| 208 |
+
Get an icon resource as {channel: array}. Note that
|
| 209 |
+
the arrays are bottom-up like windows bitmaps and will likely
|
| 210 |
+
need to be flipped or transposed in some way.
|
| 211 |
+
"""
|
| 212 |
+
dct = {}
|
| 213 |
+
for code, reader in self.SIZES[size]:
|
| 214 |
+
desc = self.dct.get(code)
|
| 215 |
+
if desc is not None:
|
| 216 |
+
dct.update(reader(self.fobj, desc, size))
|
| 217 |
+
return dct
|
| 218 |
+
|
| 219 |
+
def getimage(self, size=None):
|
| 220 |
+
if size is None:
|
| 221 |
+
size = self.bestsize()
|
| 222 |
+
if len(size) == 2:
|
| 223 |
+
size = (size[0], size[1], 1)
|
| 224 |
+
channels = self.dataforsize(size)
|
| 225 |
+
|
| 226 |
+
im = channels.get("RGBA", None)
|
| 227 |
+
if im:
|
| 228 |
+
return im
|
| 229 |
+
|
| 230 |
+
im = channels.get("RGB").copy()
|
| 231 |
+
try:
|
| 232 |
+
im.putalpha(channels["A"])
|
| 233 |
+
except KeyError:
|
| 234 |
+
pass
|
| 235 |
+
return im
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
##
|
| 239 |
+
# Image plugin for Mac OS icons.
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class IcnsImageFile(ImageFile.ImageFile):
|
| 243 |
+
"""
|
| 244 |
+
PIL image support for Mac OS .icns files.
|
| 245 |
+
Chooses the best resolution, but will possibly load
|
| 246 |
+
a different size image if you mutate the size attribute
|
| 247 |
+
before calling 'load'.
|
| 248 |
+
|
| 249 |
+
The info dictionary has a key 'sizes' that is a list
|
| 250 |
+
of sizes that the icns file has.
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
format = "ICNS"
|
| 254 |
+
format_description = "Mac OS icns resource"
|
| 255 |
+
|
| 256 |
+
def _open(self) -> None:
|
| 257 |
+
self.icns = IcnsFile(self.fp)
|
| 258 |
+
self._mode = "RGBA"
|
| 259 |
+
self.info["sizes"] = self.icns.itersizes()
|
| 260 |
+
self.best_size = self.icns.bestsize()
|
| 261 |
+
self.size = (
|
| 262 |
+
self.best_size[0] * self.best_size[2],
|
| 263 |
+
self.best_size[1] * self.best_size[2],
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def size(self):
|
| 268 |
+
return self._size
|
| 269 |
+
|
| 270 |
+
@size.setter
|
| 271 |
+
def size(self, value):
|
| 272 |
+
info_size = value
|
| 273 |
+
if info_size not in self.info["sizes"] and len(info_size) == 2:
|
| 274 |
+
info_size = (info_size[0], info_size[1], 1)
|
| 275 |
+
if (
|
| 276 |
+
info_size not in self.info["sizes"]
|
| 277 |
+
and len(info_size) == 3
|
| 278 |
+
and info_size[2] == 1
|
| 279 |
+
):
|
| 280 |
+
simple_sizes = [
|
| 281 |
+
(size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
|
| 282 |
+
]
|
| 283 |
+
if value in simple_sizes:
|
| 284 |
+
info_size = self.info["sizes"][simple_sizes.index(value)]
|
| 285 |
+
if info_size not in self.info["sizes"]:
|
| 286 |
+
msg = "This is not one of the allowed sizes of this image"
|
| 287 |
+
raise ValueError(msg)
|
| 288 |
+
self._size = value
|
| 289 |
+
|
| 290 |
+
def load(self):
|
| 291 |
+
if len(self.size) == 3:
|
| 292 |
+
self.best_size = self.size
|
| 293 |
+
self.size = (
|
| 294 |
+
self.best_size[0] * self.best_size[2],
|
| 295 |
+
self.best_size[1] * self.best_size[2],
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
px = Image.Image.load(self)
|
| 299 |
+
if self.im is not None and self.im.size == self.size:
|
| 300 |
+
# Already loaded
|
| 301 |
+
return px
|
| 302 |
+
self.load_prepare()
|
| 303 |
+
# This is likely NOT the best way to do it, but whatever.
|
| 304 |
+
im = self.icns.getimage(self.best_size)
|
| 305 |
+
|
| 306 |
+
# If this is a PNG or JPEG 2000, it won't be loaded yet
|
| 307 |
+
px = im.load()
|
| 308 |
+
|
| 309 |
+
self.im = im.im
|
| 310 |
+
self._mode = im.mode
|
| 311 |
+
self.size = im.size
|
| 312 |
+
|
| 313 |
+
return px
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 317 |
+
"""
|
| 318 |
+
Saves the image as a series of PNG files,
|
| 319 |
+
that are then combined into a .icns file.
|
| 320 |
+
"""
|
| 321 |
+
if hasattr(fp, "flush"):
|
| 322 |
+
fp.flush()
|
| 323 |
+
|
| 324 |
+
sizes = {
|
| 325 |
+
b"ic07": 128,
|
| 326 |
+
b"ic08": 256,
|
| 327 |
+
b"ic09": 512,
|
| 328 |
+
b"ic10": 1024,
|
| 329 |
+
b"ic11": 32,
|
| 330 |
+
b"ic12": 64,
|
| 331 |
+
b"ic13": 256,
|
| 332 |
+
b"ic14": 512,
|
| 333 |
+
}
|
| 334 |
+
provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
|
| 335 |
+
size_streams = {}
|
| 336 |
+
for size in set(sizes.values()):
|
| 337 |
+
image = (
|
| 338 |
+
provided_images[size]
|
| 339 |
+
if size in provided_images
|
| 340 |
+
else im.resize((size, size))
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
temp = io.BytesIO()
|
| 344 |
+
image.save(temp, "png")
|
| 345 |
+
size_streams[size] = temp.getvalue()
|
| 346 |
+
|
| 347 |
+
entries = []
|
| 348 |
+
for type, size in sizes.items():
|
| 349 |
+
stream = size_streams[size]
|
| 350 |
+
entries.append((type, HEADERSIZE + len(stream), stream))
|
| 351 |
+
|
| 352 |
+
# Header
|
| 353 |
+
fp.write(MAGIC)
|
| 354 |
+
file_length = HEADERSIZE # Header
|
| 355 |
+
file_length += HEADERSIZE + 8 * len(entries) # TOC
|
| 356 |
+
file_length += sum(entry[1] for entry in entries)
|
| 357 |
+
fp.write(struct.pack(">i", file_length))
|
| 358 |
+
|
| 359 |
+
# TOC
|
| 360 |
+
fp.write(b"TOC ")
|
| 361 |
+
fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
|
| 362 |
+
for entry in entries:
|
| 363 |
+
fp.write(entry[0])
|
| 364 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 365 |
+
|
| 366 |
+
# Data
|
| 367 |
+
for entry in entries:
|
| 368 |
+
fp.write(entry[0])
|
| 369 |
+
fp.write(struct.pack(">i", entry[1]))
|
| 370 |
+
fp.write(entry[2])
|
| 371 |
+
|
| 372 |
+
if hasattr(fp, "flush"):
|
| 373 |
+
fp.flush()
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _accept(prefix: bytes) -> bool:
|
| 377 |
+
return prefix[:4] == MAGIC
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
|
| 381 |
+
Image.register_extension(IcnsImageFile.format, ".icns")
|
| 382 |
+
|
| 383 |
+
Image.register_save(IcnsImageFile.format, _save)
|
| 384 |
+
Image.register_mime(IcnsImageFile.format, "image/icns")
|
| 385 |
+
|
| 386 |
+
if __name__ == "__main__":
|
| 387 |
+
if len(sys.argv) < 2:
|
| 388 |
+
print("Syntax: python3 IcnsImagePlugin.py [file]")
|
| 389 |
+
sys.exit()
|
| 390 |
+
|
| 391 |
+
with open(sys.argv[1], "rb") as fp:
|
| 392 |
+
imf = IcnsImageFile(fp)
|
| 393 |
+
for size in imf.info["sizes"]:
|
| 394 |
+
width, height, scale = imf.size = size
|
| 395 |
+
imf.save(f"out-{width}-{height}-{scale}.png")
|
| 396 |
+
with Image.open(sys.argv[1]) as im:
|
| 397 |
+
im.save("out.png")
|
| 398 |
+
if sys.platform == "windows":
|
| 399 |
+
os.startfile("out.png")
|
.venv/lib/python3.11/site-packages/PIL/Image.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.11/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__
|
.venv/lib/python3.11/site-packages/PIL/ImageColor.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# map CSS3-style colour description strings to RGB
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2002-10-24 fl Added support for CSS-style color strings
|
| 9 |
+
# 2002-12-15 fl Added RGBA support
|
| 10 |
+
# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
|
| 11 |
+
# 2004-07-19 fl Fixed gray/grey spelling issues
|
| 12 |
+
# 2009-03-05 fl Fixed rounding error in grayscale calculation
|
| 13 |
+
#
|
| 14 |
+
# Copyright (c) 2002-2004 by Secret Labs AB
|
| 15 |
+
# Copyright (c) 2002-2004 by Fredrik Lundh
|
| 16 |
+
#
|
| 17 |
+
# See the README file for information on usage and redistribution.
|
| 18 |
+
#
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import re
|
| 22 |
+
from functools import lru_cache
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@lru_cache
|
| 28 |
+
def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
|
| 29 |
+
"""
|
| 30 |
+
Convert a color string to an RGB or RGBA tuple. If the string cannot be
|
| 31 |
+
parsed, this function raises a :py:exc:`ValueError` exception.
|
| 32 |
+
|
| 33 |
+
.. versionadded:: 1.1.4
|
| 34 |
+
|
| 35 |
+
:param color: A color string
|
| 36 |
+
:return: ``(red, green, blue[, alpha])``
|
| 37 |
+
"""
|
| 38 |
+
if len(color) > 100:
|
| 39 |
+
msg = "color specifier is too long"
|
| 40 |
+
raise ValueError(msg)
|
| 41 |
+
color = color.lower()
|
| 42 |
+
|
| 43 |
+
rgb = colormap.get(color, None)
|
| 44 |
+
if rgb:
|
| 45 |
+
if isinstance(rgb, tuple):
|
| 46 |
+
return rgb
|
| 47 |
+
rgb_tuple = getrgb(rgb)
|
| 48 |
+
assert len(rgb_tuple) == 3
|
| 49 |
+
colormap[color] = rgb_tuple
|
| 50 |
+
return rgb_tuple
|
| 51 |
+
|
| 52 |
+
# check for known string formats
|
| 53 |
+
if re.match("#[a-f0-9]{3}$", color):
|
| 54 |
+
return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
|
| 55 |
+
|
| 56 |
+
if re.match("#[a-f0-9]{4}$", color):
|
| 57 |
+
return (
|
| 58 |
+
int(color[1] * 2, 16),
|
| 59 |
+
int(color[2] * 2, 16),
|
| 60 |
+
int(color[3] * 2, 16),
|
| 61 |
+
int(color[4] * 2, 16),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
if re.match("#[a-f0-9]{6}$", color):
|
| 65 |
+
return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
|
| 66 |
+
|
| 67 |
+
if re.match("#[a-f0-9]{8}$", color):
|
| 68 |
+
return (
|
| 69 |
+
int(color[1:3], 16),
|
| 70 |
+
int(color[3:5], 16),
|
| 71 |
+
int(color[5:7], 16),
|
| 72 |
+
int(color[7:9], 16),
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
| 76 |
+
if m:
|
| 77 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3))
|
| 78 |
+
|
| 79 |
+
m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
|
| 80 |
+
if m:
|
| 81 |
+
return (
|
| 82 |
+
int((int(m.group(1)) * 255) / 100.0 + 0.5),
|
| 83 |
+
int((int(m.group(2)) * 255) / 100.0 + 0.5),
|
| 84 |
+
int((int(m.group(3)) * 255) / 100.0 + 0.5),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
m = re.match(
|
| 88 |
+
r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
| 89 |
+
)
|
| 90 |
+
if m:
|
| 91 |
+
from colorsys import hls_to_rgb
|
| 92 |
+
|
| 93 |
+
rgb_floats = hls_to_rgb(
|
| 94 |
+
float(m.group(1)) / 360.0,
|
| 95 |
+
float(m.group(3)) / 100.0,
|
| 96 |
+
float(m.group(2)) / 100.0,
|
| 97 |
+
)
|
| 98 |
+
return (
|
| 99 |
+
int(rgb_floats[0] * 255 + 0.5),
|
| 100 |
+
int(rgb_floats[1] * 255 + 0.5),
|
| 101 |
+
int(rgb_floats[2] * 255 + 0.5),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
m = re.match(
|
| 105 |
+
r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
|
| 106 |
+
)
|
| 107 |
+
if m:
|
| 108 |
+
from colorsys import hsv_to_rgb
|
| 109 |
+
|
| 110 |
+
rgb_floats = hsv_to_rgb(
|
| 111 |
+
float(m.group(1)) / 360.0,
|
| 112 |
+
float(m.group(2)) / 100.0,
|
| 113 |
+
float(m.group(3)) / 100.0,
|
| 114 |
+
)
|
| 115 |
+
return (
|
| 116 |
+
int(rgb_floats[0] * 255 + 0.5),
|
| 117 |
+
int(rgb_floats[1] * 255 + 0.5),
|
| 118 |
+
int(rgb_floats[2] * 255 + 0.5),
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
|
| 122 |
+
if m:
|
| 123 |
+
return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
|
| 124 |
+
msg = f"unknown color specifier: {repr(color)}"
|
| 125 |
+
raise ValueError(msg)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@lru_cache
|
| 129 |
+
def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
|
| 130 |
+
"""
|
| 131 |
+
Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
|
| 132 |
+
``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
|
| 133 |
+
not color or a palette image, converts the RGB value to a grayscale value.
|
| 134 |
+
If the string cannot be parsed, this function raises a :py:exc:`ValueError`
|
| 135 |
+
exception.
|
| 136 |
+
|
| 137 |
+
.. versionadded:: 1.1.4
|
| 138 |
+
|
| 139 |
+
:param color: A color string
|
| 140 |
+
:param mode: Convert result to this mode
|
| 141 |
+
:return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
|
| 142 |
+
"""
|
| 143 |
+
# same as getrgb, but converts the result to the given mode
|
| 144 |
+
rgb, alpha = getrgb(color), 255
|
| 145 |
+
if len(rgb) == 4:
|
| 146 |
+
alpha = rgb[3]
|
| 147 |
+
rgb = rgb[:3]
|
| 148 |
+
|
| 149 |
+
if mode == "HSV":
|
| 150 |
+
from colorsys import rgb_to_hsv
|
| 151 |
+
|
| 152 |
+
r, g, b = rgb
|
| 153 |
+
h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
|
| 154 |
+
return int(h * 255), int(s * 255), int(v * 255)
|
| 155 |
+
elif Image.getmodebase(mode) == "L":
|
| 156 |
+
r, g, b = rgb
|
| 157 |
+
# ITU-R Recommendation 601-2 for nonlinear RGB
|
| 158 |
+
# scaled to 24 bits to match the convert's implementation.
|
| 159 |
+
graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
|
| 160 |
+
if mode[-1] == "A":
|
| 161 |
+
return graylevel, alpha
|
| 162 |
+
return graylevel
|
| 163 |
+
elif mode[-1] == "A":
|
| 164 |
+
return rgb + (alpha,)
|
| 165 |
+
return rgb
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
colormap: dict[str, str | tuple[int, int, int]] = {
|
| 169 |
+
# X11 colour table from https://drafts.csswg.org/css-color-4/, with
|
| 170 |
+
# gray/grey spelling issues fixed. This is a superset of HTML 4.0
|
| 171 |
+
# colour names used in CSS 1.
|
| 172 |
+
"aliceblue": "#f0f8ff",
|
| 173 |
+
"antiquewhite": "#faebd7",
|
| 174 |
+
"aqua": "#00ffff",
|
| 175 |
+
"aquamarine": "#7fffd4",
|
| 176 |
+
"azure": "#f0ffff",
|
| 177 |
+
"beige": "#f5f5dc",
|
| 178 |
+
"bisque": "#ffe4c4",
|
| 179 |
+
"black": "#000000",
|
| 180 |
+
"blanchedalmond": "#ffebcd",
|
| 181 |
+
"blue": "#0000ff",
|
| 182 |
+
"blueviolet": "#8a2be2",
|
| 183 |
+
"brown": "#a52a2a",
|
| 184 |
+
"burlywood": "#deb887",
|
| 185 |
+
"cadetblue": "#5f9ea0",
|
| 186 |
+
"chartreuse": "#7fff00",
|
| 187 |
+
"chocolate": "#d2691e",
|
| 188 |
+
"coral": "#ff7f50",
|
| 189 |
+
"cornflowerblue": "#6495ed",
|
| 190 |
+
"cornsilk": "#fff8dc",
|
| 191 |
+
"crimson": "#dc143c",
|
| 192 |
+
"cyan": "#00ffff",
|
| 193 |
+
"darkblue": "#00008b",
|
| 194 |
+
"darkcyan": "#008b8b",
|
| 195 |
+
"darkgoldenrod": "#b8860b",
|
| 196 |
+
"darkgray": "#a9a9a9",
|
| 197 |
+
"darkgrey": "#a9a9a9",
|
| 198 |
+
"darkgreen": "#006400",
|
| 199 |
+
"darkkhaki": "#bdb76b",
|
| 200 |
+
"darkmagenta": "#8b008b",
|
| 201 |
+
"darkolivegreen": "#556b2f",
|
| 202 |
+
"darkorange": "#ff8c00",
|
| 203 |
+
"darkorchid": "#9932cc",
|
| 204 |
+
"darkred": "#8b0000",
|
| 205 |
+
"darksalmon": "#e9967a",
|
| 206 |
+
"darkseagreen": "#8fbc8f",
|
| 207 |
+
"darkslateblue": "#483d8b",
|
| 208 |
+
"darkslategray": "#2f4f4f",
|
| 209 |
+
"darkslategrey": "#2f4f4f",
|
| 210 |
+
"darkturquoise": "#00ced1",
|
| 211 |
+
"darkviolet": "#9400d3",
|
| 212 |
+
"deeppink": "#ff1493",
|
| 213 |
+
"deepskyblue": "#00bfff",
|
| 214 |
+
"dimgray": "#696969",
|
| 215 |
+
"dimgrey": "#696969",
|
| 216 |
+
"dodgerblue": "#1e90ff",
|
| 217 |
+
"firebrick": "#b22222",
|
| 218 |
+
"floralwhite": "#fffaf0",
|
| 219 |
+
"forestgreen": "#228b22",
|
| 220 |
+
"fuchsia": "#ff00ff",
|
| 221 |
+
"gainsboro": "#dcdcdc",
|
| 222 |
+
"ghostwhite": "#f8f8ff",
|
| 223 |
+
"gold": "#ffd700",
|
| 224 |
+
"goldenrod": "#daa520",
|
| 225 |
+
"gray": "#808080",
|
| 226 |
+
"grey": "#808080",
|
| 227 |
+
"green": "#008000",
|
| 228 |
+
"greenyellow": "#adff2f",
|
| 229 |
+
"honeydew": "#f0fff0",
|
| 230 |
+
"hotpink": "#ff69b4",
|
| 231 |
+
"indianred": "#cd5c5c",
|
| 232 |
+
"indigo": "#4b0082",
|
| 233 |
+
"ivory": "#fffff0",
|
| 234 |
+
"khaki": "#f0e68c",
|
| 235 |
+
"lavender": "#e6e6fa",
|
| 236 |
+
"lavenderblush": "#fff0f5",
|
| 237 |
+
"lawngreen": "#7cfc00",
|
| 238 |
+
"lemonchiffon": "#fffacd",
|
| 239 |
+
"lightblue": "#add8e6",
|
| 240 |
+
"lightcoral": "#f08080",
|
| 241 |
+
"lightcyan": "#e0ffff",
|
| 242 |
+
"lightgoldenrodyellow": "#fafad2",
|
| 243 |
+
"lightgreen": "#90ee90",
|
| 244 |
+
"lightgray": "#d3d3d3",
|
| 245 |
+
"lightgrey": "#d3d3d3",
|
| 246 |
+
"lightpink": "#ffb6c1",
|
| 247 |
+
"lightsalmon": "#ffa07a",
|
| 248 |
+
"lightseagreen": "#20b2aa",
|
| 249 |
+
"lightskyblue": "#87cefa",
|
| 250 |
+
"lightslategray": "#778899",
|
| 251 |
+
"lightslategrey": "#778899",
|
| 252 |
+
"lightsteelblue": "#b0c4de",
|
| 253 |
+
"lightyellow": "#ffffe0",
|
| 254 |
+
"lime": "#00ff00",
|
| 255 |
+
"limegreen": "#32cd32",
|
| 256 |
+
"linen": "#faf0e6",
|
| 257 |
+
"magenta": "#ff00ff",
|
| 258 |
+
"maroon": "#800000",
|
| 259 |
+
"mediumaquamarine": "#66cdaa",
|
| 260 |
+
"mediumblue": "#0000cd",
|
| 261 |
+
"mediumorchid": "#ba55d3",
|
| 262 |
+
"mediumpurple": "#9370db",
|
| 263 |
+
"mediumseagreen": "#3cb371",
|
| 264 |
+
"mediumslateblue": "#7b68ee",
|
| 265 |
+
"mediumspringgreen": "#00fa9a",
|
| 266 |
+
"mediumturquoise": "#48d1cc",
|
| 267 |
+
"mediumvioletred": "#c71585",
|
| 268 |
+
"midnightblue": "#191970",
|
| 269 |
+
"mintcream": "#f5fffa",
|
| 270 |
+
"mistyrose": "#ffe4e1",
|
| 271 |
+
"moccasin": "#ffe4b5",
|
| 272 |
+
"navajowhite": "#ffdead",
|
| 273 |
+
"navy": "#000080",
|
| 274 |
+
"oldlace": "#fdf5e6",
|
| 275 |
+
"olive": "#808000",
|
| 276 |
+
"olivedrab": "#6b8e23",
|
| 277 |
+
"orange": "#ffa500",
|
| 278 |
+
"orangered": "#ff4500",
|
| 279 |
+
"orchid": "#da70d6",
|
| 280 |
+
"palegoldenrod": "#eee8aa",
|
| 281 |
+
"palegreen": "#98fb98",
|
| 282 |
+
"paleturquoise": "#afeeee",
|
| 283 |
+
"palevioletred": "#db7093",
|
| 284 |
+
"papayawhip": "#ffefd5",
|
| 285 |
+
"peachpuff": "#ffdab9",
|
| 286 |
+
"peru": "#cd853f",
|
| 287 |
+
"pink": "#ffc0cb",
|
| 288 |
+
"plum": "#dda0dd",
|
| 289 |
+
"powderblue": "#b0e0e6",
|
| 290 |
+
"purple": "#800080",
|
| 291 |
+
"rebeccapurple": "#663399",
|
| 292 |
+
"red": "#ff0000",
|
| 293 |
+
"rosybrown": "#bc8f8f",
|
| 294 |
+
"royalblue": "#4169e1",
|
| 295 |
+
"saddlebrown": "#8b4513",
|
| 296 |
+
"salmon": "#fa8072",
|
| 297 |
+
"sandybrown": "#f4a460",
|
| 298 |
+
"seagreen": "#2e8b57",
|
| 299 |
+
"seashell": "#fff5ee",
|
| 300 |
+
"sienna": "#a0522d",
|
| 301 |
+
"silver": "#c0c0c0",
|
| 302 |
+
"skyblue": "#87ceeb",
|
| 303 |
+
"slateblue": "#6a5acd",
|
| 304 |
+
"slategray": "#708090",
|
| 305 |
+
"slategrey": "#708090",
|
| 306 |
+
"snow": "#fffafa",
|
| 307 |
+
"springgreen": "#00ff7f",
|
| 308 |
+
"steelblue": "#4682b4",
|
| 309 |
+
"tan": "#d2b48c",
|
| 310 |
+
"teal": "#008080",
|
| 311 |
+
"thistle": "#d8bfd8",
|
| 312 |
+
"tomato": "#ff6347",
|
| 313 |
+
"turquoise": "#40e0d0",
|
| 314 |
+
"violet": "#ee82ee",
|
| 315 |
+
"wheat": "#f5deb3",
|
| 316 |
+
"white": "#ffffff",
|
| 317 |
+
"whitesmoke": "#f5f5f5",
|
| 318 |
+
"yellow": "#ffff00",
|
| 319 |
+
"yellowgreen": "#9acd32",
|
| 320 |
+
}
|
.venv/lib/python3.11/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"))
|
.venv/lib/python3.11/site-packages/PIL/ImageFile.py
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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
|
.venv/lib/python3.11/site-packages/PIL/ImageFilter.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# standard filters
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1995-11-27 fl Created
|
| 9 |
+
# 2002-06-08 fl Added rank and mode filters
|
| 10 |
+
# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) 1997-2003 by Secret Labs AB.
|
| 13 |
+
# Copyright (c) 1995-2002 by Fredrik Lundh.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import abc
|
| 20 |
+
import functools
|
| 21 |
+
from types import ModuleType
|
| 22 |
+
from typing import TYPE_CHECKING, Any, Callable, Sequence, cast
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from . import _imaging
|
| 26 |
+
from ._typing import NumpyArray
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Filter:
|
| 30 |
+
@abc.abstractmethod
|
| 31 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class MultibandFilter(Filter):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BuiltinFilter(MultibandFilter):
|
| 40 |
+
filterargs: tuple[Any, ...]
|
| 41 |
+
|
| 42 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 43 |
+
if image.mode == "P":
|
| 44 |
+
msg = "cannot filter palette images"
|
| 45 |
+
raise ValueError(msg)
|
| 46 |
+
return image.filter(*self.filterargs)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Kernel(BuiltinFilter):
|
| 50 |
+
"""
|
| 51 |
+
Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
|
| 52 |
+
point kernels.
|
| 53 |
+
|
| 54 |
+
Kernels can only be applied to "L" and "RGB" images.
|
| 55 |
+
|
| 56 |
+
:param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
|
| 57 |
+
:param kernel: A sequence containing kernel weights. The kernel will be flipped
|
| 58 |
+
vertically before being applied to the image.
|
| 59 |
+
:param scale: Scale factor. If given, the result for each pixel is divided by this
|
| 60 |
+
value. The default is the sum of the kernel weights.
|
| 61 |
+
:param offset: Offset. If given, this value is added to the result, after it has
|
| 62 |
+
been divided by the scale factor.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
name = "Kernel"
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
size: tuple[int, int],
|
| 70 |
+
kernel: Sequence[float],
|
| 71 |
+
scale: float | None = None,
|
| 72 |
+
offset: float = 0,
|
| 73 |
+
) -> None:
|
| 74 |
+
if scale is None:
|
| 75 |
+
# default scale is sum of kernel
|
| 76 |
+
scale = functools.reduce(lambda a, b: a + b, kernel)
|
| 77 |
+
if size[0] * size[1] != len(kernel):
|
| 78 |
+
msg = "not enough coefficients in kernel"
|
| 79 |
+
raise ValueError(msg)
|
| 80 |
+
self.filterargs = size, scale, offset, kernel
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class RankFilter(Filter):
|
| 84 |
+
"""
|
| 85 |
+
Create a rank filter. The rank filter sorts all pixels in
|
| 86 |
+
a window of the given size, and returns the ``rank``'th value.
|
| 87 |
+
|
| 88 |
+
:param size: The kernel size, in pixels.
|
| 89 |
+
:param rank: What pixel value to pick. Use 0 for a min filter,
|
| 90 |
+
``size * size / 2`` for a median filter, ``size * size - 1``
|
| 91 |
+
for a max filter, etc.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
name = "Rank"
|
| 95 |
+
|
| 96 |
+
def __init__(self, size: int, rank: int) -> None:
|
| 97 |
+
self.size = size
|
| 98 |
+
self.rank = rank
|
| 99 |
+
|
| 100 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 101 |
+
if image.mode == "P":
|
| 102 |
+
msg = "cannot filter palette images"
|
| 103 |
+
raise ValueError(msg)
|
| 104 |
+
image = image.expand(self.size // 2, self.size // 2)
|
| 105 |
+
return image.rankfilter(self.size, self.rank)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class MedianFilter(RankFilter):
|
| 109 |
+
"""
|
| 110 |
+
Create a median filter. Picks the median pixel value in a window with the
|
| 111 |
+
given size.
|
| 112 |
+
|
| 113 |
+
:param size: The kernel size, in pixels.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
name = "Median"
|
| 117 |
+
|
| 118 |
+
def __init__(self, size: int = 3) -> None:
|
| 119 |
+
self.size = size
|
| 120 |
+
self.rank = size * size // 2
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class MinFilter(RankFilter):
|
| 124 |
+
"""
|
| 125 |
+
Create a min filter. Picks the lowest pixel value in a window with the
|
| 126 |
+
given size.
|
| 127 |
+
|
| 128 |
+
:param size: The kernel size, in pixels.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
name = "Min"
|
| 132 |
+
|
| 133 |
+
def __init__(self, size: int = 3) -> None:
|
| 134 |
+
self.size = size
|
| 135 |
+
self.rank = 0
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class MaxFilter(RankFilter):
|
| 139 |
+
"""
|
| 140 |
+
Create a max filter. Picks the largest pixel value in a window with the
|
| 141 |
+
given size.
|
| 142 |
+
|
| 143 |
+
:param size: The kernel size, in pixels.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
name = "Max"
|
| 147 |
+
|
| 148 |
+
def __init__(self, size: int = 3) -> None:
|
| 149 |
+
self.size = size
|
| 150 |
+
self.rank = size * size - 1
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class ModeFilter(Filter):
|
| 154 |
+
"""
|
| 155 |
+
Create a mode filter. Picks the most frequent pixel value in a box with the
|
| 156 |
+
given size. Pixel values that occur only once or twice are ignored; if no
|
| 157 |
+
pixel value occurs more than twice, the original pixel value is preserved.
|
| 158 |
+
|
| 159 |
+
:param size: The kernel size, in pixels.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
name = "Mode"
|
| 163 |
+
|
| 164 |
+
def __init__(self, size: int = 3) -> None:
|
| 165 |
+
self.size = size
|
| 166 |
+
|
| 167 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 168 |
+
return image.modefilter(self.size)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class GaussianBlur(MultibandFilter):
|
| 172 |
+
"""Blurs the image with a sequence of extended box filters, which
|
| 173 |
+
approximates a Gaussian kernel. For details on accuracy see
|
| 174 |
+
<https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
|
| 175 |
+
|
| 176 |
+
:param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
|
| 177 |
+
numbers for x and y, or a single number for both.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
name = "GaussianBlur"
|
| 181 |
+
|
| 182 |
+
def __init__(self, radius: float | Sequence[float] = 2) -> None:
|
| 183 |
+
self.radius = radius
|
| 184 |
+
|
| 185 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 186 |
+
xy = self.radius
|
| 187 |
+
if isinstance(xy, (int, float)):
|
| 188 |
+
xy = (xy, xy)
|
| 189 |
+
if xy == (0, 0):
|
| 190 |
+
return image.copy()
|
| 191 |
+
return image.gaussian_blur(xy)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class BoxBlur(MultibandFilter):
|
| 195 |
+
"""Blurs the image by setting each pixel to the average value of the pixels
|
| 196 |
+
in a square box extending radius pixels in each direction.
|
| 197 |
+
Supports float radius of arbitrary size. Uses an optimized implementation
|
| 198 |
+
which runs in linear time relative to the size of the image
|
| 199 |
+
for any radius value.
|
| 200 |
+
|
| 201 |
+
:param radius: Size of the box in a direction. Either a sequence of two numbers for
|
| 202 |
+
x and y, or a single number for both.
|
| 203 |
+
|
| 204 |
+
Radius 0 does not blur, returns an identical image.
|
| 205 |
+
Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
name = "BoxBlur"
|
| 209 |
+
|
| 210 |
+
def __init__(self, radius: float | Sequence[float]) -> None:
|
| 211 |
+
xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
|
| 212 |
+
if xy[0] < 0 or xy[1] < 0:
|
| 213 |
+
msg = "radius must be >= 0"
|
| 214 |
+
raise ValueError(msg)
|
| 215 |
+
self.radius = radius
|
| 216 |
+
|
| 217 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 218 |
+
xy = self.radius
|
| 219 |
+
if isinstance(xy, (int, float)):
|
| 220 |
+
xy = (xy, xy)
|
| 221 |
+
if xy == (0, 0):
|
| 222 |
+
return image.copy()
|
| 223 |
+
return image.box_blur(xy)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class UnsharpMask(MultibandFilter):
|
| 227 |
+
"""Unsharp mask filter.
|
| 228 |
+
|
| 229 |
+
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
|
| 230 |
+
the parameters.
|
| 231 |
+
|
| 232 |
+
:param radius: Blur Radius
|
| 233 |
+
:param percent: Unsharp strength, in percent
|
| 234 |
+
:param threshold: Threshold controls the minimum brightness change that
|
| 235 |
+
will be sharpened
|
| 236 |
+
|
| 237 |
+
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
|
| 238 |
+
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
name = "UnsharpMask"
|
| 242 |
+
|
| 243 |
+
def __init__(
|
| 244 |
+
self, radius: float = 2, percent: int = 150, threshold: int = 3
|
| 245 |
+
) -> None:
|
| 246 |
+
self.radius = radius
|
| 247 |
+
self.percent = percent
|
| 248 |
+
self.threshold = threshold
|
| 249 |
+
|
| 250 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 251 |
+
return image.unsharp_mask(self.radius, self.percent, self.threshold)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class BLUR(BuiltinFilter):
|
| 255 |
+
name = "Blur"
|
| 256 |
+
# fmt: off
|
| 257 |
+
filterargs = (5, 5), 16, 0, (
|
| 258 |
+
1, 1, 1, 1, 1,
|
| 259 |
+
1, 0, 0, 0, 1,
|
| 260 |
+
1, 0, 0, 0, 1,
|
| 261 |
+
1, 0, 0, 0, 1,
|
| 262 |
+
1, 1, 1, 1, 1,
|
| 263 |
+
)
|
| 264 |
+
# fmt: on
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class CONTOUR(BuiltinFilter):
|
| 268 |
+
name = "Contour"
|
| 269 |
+
# fmt: off
|
| 270 |
+
filterargs = (3, 3), 1, 255, (
|
| 271 |
+
-1, -1, -1,
|
| 272 |
+
-1, 8, -1,
|
| 273 |
+
-1, -1, -1,
|
| 274 |
+
)
|
| 275 |
+
# fmt: on
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class DETAIL(BuiltinFilter):
|
| 279 |
+
name = "Detail"
|
| 280 |
+
# fmt: off
|
| 281 |
+
filterargs = (3, 3), 6, 0, (
|
| 282 |
+
0, -1, 0,
|
| 283 |
+
-1, 10, -1,
|
| 284 |
+
0, -1, 0,
|
| 285 |
+
)
|
| 286 |
+
# fmt: on
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class EDGE_ENHANCE(BuiltinFilter):
|
| 290 |
+
name = "Edge-enhance"
|
| 291 |
+
# fmt: off
|
| 292 |
+
filterargs = (3, 3), 2, 0, (
|
| 293 |
+
-1, -1, -1,
|
| 294 |
+
-1, 10, -1,
|
| 295 |
+
-1, -1, -1,
|
| 296 |
+
)
|
| 297 |
+
# fmt: on
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class EDGE_ENHANCE_MORE(BuiltinFilter):
|
| 301 |
+
name = "Edge-enhance More"
|
| 302 |
+
# fmt: off
|
| 303 |
+
filterargs = (3, 3), 1, 0, (
|
| 304 |
+
-1, -1, -1,
|
| 305 |
+
-1, 9, -1,
|
| 306 |
+
-1, -1, -1,
|
| 307 |
+
)
|
| 308 |
+
# fmt: on
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class EMBOSS(BuiltinFilter):
|
| 312 |
+
name = "Emboss"
|
| 313 |
+
# fmt: off
|
| 314 |
+
filterargs = (3, 3), 1, 128, (
|
| 315 |
+
-1, 0, 0,
|
| 316 |
+
0, 1, 0,
|
| 317 |
+
0, 0, 0,
|
| 318 |
+
)
|
| 319 |
+
# fmt: on
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class FIND_EDGES(BuiltinFilter):
|
| 323 |
+
name = "Find Edges"
|
| 324 |
+
# fmt: off
|
| 325 |
+
filterargs = (3, 3), 1, 0, (
|
| 326 |
+
-1, -1, -1,
|
| 327 |
+
-1, 8, -1,
|
| 328 |
+
-1, -1, -1,
|
| 329 |
+
)
|
| 330 |
+
# fmt: on
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class SHARPEN(BuiltinFilter):
|
| 334 |
+
name = "Sharpen"
|
| 335 |
+
# fmt: off
|
| 336 |
+
filterargs = (3, 3), 16, 0, (
|
| 337 |
+
-2, -2, -2,
|
| 338 |
+
-2, 32, -2,
|
| 339 |
+
-2, -2, -2,
|
| 340 |
+
)
|
| 341 |
+
# fmt: on
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class SMOOTH(BuiltinFilter):
|
| 345 |
+
name = "Smooth"
|
| 346 |
+
# fmt: off
|
| 347 |
+
filterargs = (3, 3), 13, 0, (
|
| 348 |
+
1, 1, 1,
|
| 349 |
+
1, 5, 1,
|
| 350 |
+
1, 1, 1,
|
| 351 |
+
)
|
| 352 |
+
# fmt: on
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class SMOOTH_MORE(BuiltinFilter):
|
| 356 |
+
name = "Smooth More"
|
| 357 |
+
# fmt: off
|
| 358 |
+
filterargs = (5, 5), 100, 0, (
|
| 359 |
+
1, 1, 1, 1, 1,
|
| 360 |
+
1, 5, 5, 5, 1,
|
| 361 |
+
1, 5, 44, 5, 1,
|
| 362 |
+
1, 5, 5, 5, 1,
|
| 363 |
+
1, 1, 1, 1, 1,
|
| 364 |
+
)
|
| 365 |
+
# fmt: on
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class Color3DLUT(MultibandFilter):
|
| 369 |
+
"""Three-dimensional color lookup table.
|
| 370 |
+
|
| 371 |
+
Transforms 3-channel pixels using the values of the channels as coordinates
|
| 372 |
+
in the 3D lookup table and interpolating the nearest elements.
|
| 373 |
+
|
| 374 |
+
This method allows you to apply almost any color transformation
|
| 375 |
+
in constant time by using pre-calculated decimated tables.
|
| 376 |
+
|
| 377 |
+
.. versionadded:: 5.2.0
|
| 378 |
+
|
| 379 |
+
:param size: Size of the table. One int or tuple of (int, int, int).
|
| 380 |
+
Minimal size in any dimension is 2, maximum is 65.
|
| 381 |
+
:param table: Flat lookup table. A list of ``channels * size**3``
|
| 382 |
+
float elements or a list of ``size**3`` channels-sized
|
| 383 |
+
tuples with floats. Channels are changed first,
|
| 384 |
+
then first dimension, then second, then third.
|
| 385 |
+
Value 0.0 corresponds lowest value of output, 1.0 highest.
|
| 386 |
+
:param channels: Number of channels in the table. Could be 3 or 4.
|
| 387 |
+
Default is 3.
|
| 388 |
+
:param target_mode: A mode for the result image. Should have not less
|
| 389 |
+
than ``channels`` channels. Default is ``None``,
|
| 390 |
+
which means that mode wouldn't be changed.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
name = "Color 3D LUT"
|
| 394 |
+
|
| 395 |
+
def __init__(
|
| 396 |
+
self,
|
| 397 |
+
size: int | tuple[int, int, int],
|
| 398 |
+
table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
|
| 399 |
+
channels: int = 3,
|
| 400 |
+
target_mode: str | None = None,
|
| 401 |
+
**kwargs: bool,
|
| 402 |
+
) -> None:
|
| 403 |
+
if channels not in (3, 4):
|
| 404 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 405 |
+
raise ValueError(msg)
|
| 406 |
+
self.size = size = self._check_size(size)
|
| 407 |
+
self.channels = channels
|
| 408 |
+
self.mode = target_mode
|
| 409 |
+
|
| 410 |
+
# Hidden flag `_copy_table=False` could be used to avoid extra copying
|
| 411 |
+
# of the table if the table is specially made for the constructor.
|
| 412 |
+
copy_table = kwargs.get("_copy_table", True)
|
| 413 |
+
items = size[0] * size[1] * size[2]
|
| 414 |
+
wrong_size = False
|
| 415 |
+
|
| 416 |
+
numpy: ModuleType | None = None
|
| 417 |
+
if hasattr(table, "shape"):
|
| 418 |
+
try:
|
| 419 |
+
import numpy
|
| 420 |
+
except ImportError:
|
| 421 |
+
pass
|
| 422 |
+
|
| 423 |
+
if numpy and isinstance(table, numpy.ndarray):
|
| 424 |
+
numpy_table: NumpyArray = table
|
| 425 |
+
if copy_table:
|
| 426 |
+
numpy_table = numpy_table.copy()
|
| 427 |
+
|
| 428 |
+
if numpy_table.shape in [
|
| 429 |
+
(items * channels,),
|
| 430 |
+
(items, channels),
|
| 431 |
+
(size[2], size[1], size[0], channels),
|
| 432 |
+
]:
|
| 433 |
+
table = numpy_table.reshape(items * channels)
|
| 434 |
+
else:
|
| 435 |
+
wrong_size = True
|
| 436 |
+
|
| 437 |
+
else:
|
| 438 |
+
if copy_table:
|
| 439 |
+
table = list(table)
|
| 440 |
+
|
| 441 |
+
# Convert to a flat list
|
| 442 |
+
if table and isinstance(table[0], (list, tuple)):
|
| 443 |
+
raw_table = cast(Sequence[Sequence[int]], table)
|
| 444 |
+
flat_table: list[int] = []
|
| 445 |
+
for pixel in raw_table:
|
| 446 |
+
if len(pixel) != channels:
|
| 447 |
+
msg = (
|
| 448 |
+
"The elements of the table should "
|
| 449 |
+
f"have a length of {channels}."
|
| 450 |
+
)
|
| 451 |
+
raise ValueError(msg)
|
| 452 |
+
flat_table.extend(pixel)
|
| 453 |
+
table = flat_table
|
| 454 |
+
|
| 455 |
+
if wrong_size or len(table) != items * channels:
|
| 456 |
+
msg = (
|
| 457 |
+
"The table should have either channels * size**3 float items "
|
| 458 |
+
"or size**3 items of channels-sized tuples with floats. "
|
| 459 |
+
f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
|
| 460 |
+
f"Actual length: {len(table)}"
|
| 461 |
+
)
|
| 462 |
+
raise ValueError(msg)
|
| 463 |
+
self.table = table
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
def _check_size(size: Any) -> tuple[int, int, int]:
|
| 467 |
+
try:
|
| 468 |
+
_, _, _ = size
|
| 469 |
+
except ValueError as e:
|
| 470 |
+
msg = "Size should be either an integer or a tuple of three integers."
|
| 471 |
+
raise ValueError(msg) from e
|
| 472 |
+
except TypeError:
|
| 473 |
+
size = (size, size, size)
|
| 474 |
+
size = tuple(int(x) for x in size)
|
| 475 |
+
for size_1d in size:
|
| 476 |
+
if not 2 <= size_1d <= 65:
|
| 477 |
+
msg = "Size should be in [2, 65] range."
|
| 478 |
+
raise ValueError(msg)
|
| 479 |
+
return size
|
| 480 |
+
|
| 481 |
+
@classmethod
|
| 482 |
+
def generate(
|
| 483 |
+
cls,
|
| 484 |
+
size: int | tuple[int, int, int],
|
| 485 |
+
callback: Callable[[float, float, float], tuple[float, ...]],
|
| 486 |
+
channels: int = 3,
|
| 487 |
+
target_mode: str | None = None,
|
| 488 |
+
) -> Color3DLUT:
|
| 489 |
+
"""Generates new LUT using provided callback.
|
| 490 |
+
|
| 491 |
+
:param size: Size of the table. Passed to the constructor.
|
| 492 |
+
:param callback: Function with three parameters which correspond
|
| 493 |
+
three color channels. Will be called ``size**3``
|
| 494 |
+
times with values from 0.0 to 1.0 and should return
|
| 495 |
+
a tuple with ``channels`` elements.
|
| 496 |
+
:param channels: The number of channels which should return callback.
|
| 497 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 498 |
+
lookup table.
|
| 499 |
+
"""
|
| 500 |
+
size_1d, size_2d, size_3d = cls._check_size(size)
|
| 501 |
+
if channels not in (3, 4):
|
| 502 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 503 |
+
raise ValueError(msg)
|
| 504 |
+
|
| 505 |
+
table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
|
| 506 |
+
idx_out = 0
|
| 507 |
+
for b in range(size_3d):
|
| 508 |
+
for g in range(size_2d):
|
| 509 |
+
for r in range(size_1d):
|
| 510 |
+
table[idx_out : idx_out + channels] = callback(
|
| 511 |
+
r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
|
| 512 |
+
)
|
| 513 |
+
idx_out += channels
|
| 514 |
+
|
| 515 |
+
return cls(
|
| 516 |
+
(size_1d, size_2d, size_3d),
|
| 517 |
+
table,
|
| 518 |
+
channels=channels,
|
| 519 |
+
target_mode=target_mode,
|
| 520 |
+
_copy_table=False,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
def transform(
|
| 524 |
+
self,
|
| 525 |
+
callback: Callable[..., tuple[float, ...]],
|
| 526 |
+
with_normals: bool = False,
|
| 527 |
+
channels: int | None = None,
|
| 528 |
+
target_mode: str | None = None,
|
| 529 |
+
) -> Color3DLUT:
|
| 530 |
+
"""Transforms the table values using provided callback and returns
|
| 531 |
+
a new LUT with altered values.
|
| 532 |
+
|
| 533 |
+
:param callback: A function which takes old lookup table values
|
| 534 |
+
and returns a new set of values. The number
|
| 535 |
+
of arguments which function should take is
|
| 536 |
+
``self.channels`` or ``3 + self.channels``
|
| 537 |
+
if ``with_normals`` flag is set.
|
| 538 |
+
Should return a tuple of ``self.channels`` or
|
| 539 |
+
``channels`` elements if it is set.
|
| 540 |
+
:param with_normals: If true, ``callback`` will be called with
|
| 541 |
+
coordinates in the color cube as the first
|
| 542 |
+
three arguments. Otherwise, ``callback``
|
| 543 |
+
will be called only with actual color values.
|
| 544 |
+
:param channels: The number of channels in the resulting lookup table.
|
| 545 |
+
:param target_mode: Passed to the constructor of the resulting
|
| 546 |
+
lookup table.
|
| 547 |
+
"""
|
| 548 |
+
if channels not in (None, 3, 4):
|
| 549 |
+
msg = "Only 3 or 4 output channels are supported"
|
| 550 |
+
raise ValueError(msg)
|
| 551 |
+
ch_in = self.channels
|
| 552 |
+
ch_out = channels or ch_in
|
| 553 |
+
size_1d, size_2d, size_3d = self.size
|
| 554 |
+
|
| 555 |
+
table = [0] * (size_1d * size_2d * size_3d * ch_out)
|
| 556 |
+
idx_in = 0
|
| 557 |
+
idx_out = 0
|
| 558 |
+
for b in range(size_3d):
|
| 559 |
+
for g in range(size_2d):
|
| 560 |
+
for r in range(size_1d):
|
| 561 |
+
values = self.table[idx_in : idx_in + ch_in]
|
| 562 |
+
if with_normals:
|
| 563 |
+
values = callback(
|
| 564 |
+
r / (size_1d - 1),
|
| 565 |
+
g / (size_2d - 1),
|
| 566 |
+
b / (size_3d - 1),
|
| 567 |
+
*values,
|
| 568 |
+
)
|
| 569 |
+
else:
|
| 570 |
+
values = callback(*values)
|
| 571 |
+
table[idx_out : idx_out + ch_out] = values
|
| 572 |
+
idx_in += ch_in
|
| 573 |
+
idx_out += ch_out
|
| 574 |
+
|
| 575 |
+
return type(self)(
|
| 576 |
+
self.size,
|
| 577 |
+
table,
|
| 578 |
+
channels=ch_out,
|
| 579 |
+
target_mode=target_mode or self.mode,
|
| 580 |
+
_copy_table=False,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
def __repr__(self) -> str:
|
| 584 |
+
r = [
|
| 585 |
+
f"{self.__class__.__name__} from {self.table.__class__.__name__}",
|
| 586 |
+
"size={:d}x{:d}x{:d}".format(*self.size),
|
| 587 |
+
f"channels={self.channels:d}",
|
| 588 |
+
]
|
| 589 |
+
if self.mode:
|
| 590 |
+
r.append(f"target_mode={self.mode}")
|
| 591 |
+
return "<{}>".format(" ".join(r))
|
| 592 |
+
|
| 593 |
+
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
|
| 594 |
+
from . import Image
|
| 595 |
+
|
| 596 |
+
return image.color_lut_3d(
|
| 597 |
+
self.mode or image.mode,
|
| 598 |
+
Image.Resampling.BILINEAR,
|
| 599 |
+
self.channels,
|
| 600 |
+
self.size[0],
|
| 601 |
+
self.size[1],
|
| 602 |
+
self.size[2],
|
| 603 |
+
self.table,
|
| 604 |
+
)
|
.venv/lib/python3.11/site-packages/PIL/ImageFont.py
ADDED
|
@@ -0,0 +1,1290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PIL raster font management
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-08-07 fl created (experimental)
|
| 9 |
+
# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
|
| 10 |
+
# 1999-02-06 fl rewrote most font management stuff in C
|
| 11 |
+
# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
|
| 12 |
+
# 2001-02-17 fl added freetype support
|
| 13 |
+
# 2001-05-09 fl added TransposedFont wrapper class
|
| 14 |
+
# 2002-03-04 fl make sure we have a "L" or "1" font
|
| 15 |
+
# 2002-12-04 fl skip non-directory entries in the system path
|
| 16 |
+
# 2003-04-29 fl add embedded default font
|
| 17 |
+
# 2003-09-27 fl added support for truetype charmap encodings
|
| 18 |
+
#
|
| 19 |
+
# Todo:
|
| 20 |
+
# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
|
| 21 |
+
#
|
| 22 |
+
# Copyright (c) 1997-2003 by Secret Labs AB
|
| 23 |
+
# Copyright (c) 1996-2003 by Fredrik Lundh
|
| 24 |
+
#
|
| 25 |
+
# See the README file for information on usage and redistribution.
|
| 26 |
+
#
|
| 27 |
+
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
|
| 30 |
+
import base64
|
| 31 |
+
import os
|
| 32 |
+
import sys
|
| 33 |
+
import warnings
|
| 34 |
+
from enum import IntEnum
|
| 35 |
+
from io import BytesIO
|
| 36 |
+
from types import ModuleType
|
| 37 |
+
from typing import IO, TYPE_CHECKING, Any, BinaryIO
|
| 38 |
+
|
| 39 |
+
from . import Image
|
| 40 |
+
from ._typing import StrOrBytesPath
|
| 41 |
+
from ._util import DeferredError, is_path
|
| 42 |
+
|
| 43 |
+
if TYPE_CHECKING:
|
| 44 |
+
from . import ImageFile
|
| 45 |
+
from ._imaging import ImagingFont
|
| 46 |
+
from ._imagingft import Font
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Layout(IntEnum):
|
| 50 |
+
BASIC = 0
|
| 51 |
+
RAQM = 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
MAX_STRING_LENGTH = 1_000_000
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
core: ModuleType | DeferredError
|
| 58 |
+
try:
|
| 59 |
+
from . import _imagingft as core
|
| 60 |
+
except ImportError as ex:
|
| 61 |
+
core = DeferredError.new(ex)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _string_length_check(text: str | bytes | bytearray) -> None:
|
| 65 |
+
if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
|
| 66 |
+
msg = "too many characters in string"
|
| 67 |
+
raise ValueError(msg)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# FIXME: add support for pilfont2 format (see FontFile.py)
|
| 71 |
+
|
| 72 |
+
# --------------------------------------------------------------------
|
| 73 |
+
# Font metrics format:
|
| 74 |
+
# "PILfont" LF
|
| 75 |
+
# fontdescriptor LF
|
| 76 |
+
# (optional) key=value... LF
|
| 77 |
+
# "DATA" LF
|
| 78 |
+
# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
|
| 79 |
+
#
|
| 80 |
+
# To place a character, cut out srcbox and paste at dstbox,
|
| 81 |
+
# relative to the character position. Then move the character
|
| 82 |
+
# position according to dx, dy.
|
| 83 |
+
# --------------------------------------------------------------------
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ImageFont:
|
| 87 |
+
"""PIL font wrapper"""
|
| 88 |
+
|
| 89 |
+
font: ImagingFont
|
| 90 |
+
|
| 91 |
+
def _load_pilfont(self, filename: str) -> None:
|
| 92 |
+
with open(filename, "rb") as fp:
|
| 93 |
+
image: ImageFile.ImageFile | None = None
|
| 94 |
+
for ext in (".png", ".gif", ".pbm"):
|
| 95 |
+
if image:
|
| 96 |
+
image.close()
|
| 97 |
+
try:
|
| 98 |
+
fullname = os.path.splitext(filename)[0] + ext
|
| 99 |
+
image = Image.open(fullname)
|
| 100 |
+
except Exception:
|
| 101 |
+
pass
|
| 102 |
+
else:
|
| 103 |
+
if image and image.mode in ("1", "L"):
|
| 104 |
+
break
|
| 105 |
+
else:
|
| 106 |
+
if image:
|
| 107 |
+
image.close()
|
| 108 |
+
msg = "cannot find glyph data file"
|
| 109 |
+
raise OSError(msg)
|
| 110 |
+
|
| 111 |
+
self.file = fullname
|
| 112 |
+
|
| 113 |
+
self._load_pilfont_data(fp, image)
|
| 114 |
+
image.close()
|
| 115 |
+
|
| 116 |
+
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
|
| 117 |
+
# read PILfont header
|
| 118 |
+
if file.readline() != b"PILfont\n":
|
| 119 |
+
msg = "Not a PILfont file"
|
| 120 |
+
raise SyntaxError(msg)
|
| 121 |
+
file.readline().split(b";")
|
| 122 |
+
self.info = [] # FIXME: should be a dictionary
|
| 123 |
+
while True:
|
| 124 |
+
s = file.readline()
|
| 125 |
+
if not s or s == b"DATA\n":
|
| 126 |
+
break
|
| 127 |
+
self.info.append(s)
|
| 128 |
+
|
| 129 |
+
# read PILfont metrics
|
| 130 |
+
data = file.read(256 * 20)
|
| 131 |
+
|
| 132 |
+
# check image
|
| 133 |
+
if image.mode not in ("1", "L"):
|
| 134 |
+
msg = "invalid font image mode"
|
| 135 |
+
raise TypeError(msg)
|
| 136 |
+
|
| 137 |
+
image.load()
|
| 138 |
+
|
| 139 |
+
self.font = Image.core.font(image.im, data)
|
| 140 |
+
|
| 141 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
| 142 |
+
"""
|
| 143 |
+
Create a bitmap for the text.
|
| 144 |
+
|
| 145 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 146 |
+
maximum value of 255. Otherwise, it should have mode ``1``.
|
| 147 |
+
|
| 148 |
+
:param text: Text to render.
|
| 149 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 150 |
+
driver prefers; if empty, the renderer may return either
|
| 151 |
+
mode. Note that the mode is always a string, to simplify
|
| 152 |
+
C-level implementations.
|
| 153 |
+
|
| 154 |
+
.. versionadded:: 1.1.5
|
| 155 |
+
|
| 156 |
+
:return: An internal PIL storage memory instance as defined by the
|
| 157 |
+
:py:mod:`PIL.Image.core` interface module.
|
| 158 |
+
"""
|
| 159 |
+
_string_length_check(text)
|
| 160 |
+
Image._decompression_bomb_check(self.font.getsize(text))
|
| 161 |
+
return self.font.getmask(text, mode)
|
| 162 |
+
|
| 163 |
+
def getbbox(
|
| 164 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
| 165 |
+
) -> tuple[int, int, int, int]:
|
| 166 |
+
"""
|
| 167 |
+
Returns bounding box (in pixels) of given text.
|
| 168 |
+
|
| 169 |
+
.. versionadded:: 9.2.0
|
| 170 |
+
|
| 171 |
+
:param text: Text to render.
|
| 172 |
+
|
| 173 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 174 |
+
"""
|
| 175 |
+
_string_length_check(text)
|
| 176 |
+
width, height = self.font.getsize(text)
|
| 177 |
+
return 0, 0, width, height
|
| 178 |
+
|
| 179 |
+
def getlength(
|
| 180 |
+
self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
|
| 181 |
+
) -> int:
|
| 182 |
+
"""
|
| 183 |
+
Returns length (in pixels) of given text.
|
| 184 |
+
This is the amount by which following text should be offset.
|
| 185 |
+
|
| 186 |
+
.. versionadded:: 9.2.0
|
| 187 |
+
"""
|
| 188 |
+
_string_length_check(text)
|
| 189 |
+
width, height = self.font.getsize(text)
|
| 190 |
+
return width
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
##
|
| 194 |
+
# Wrapper for FreeType fonts. Application code should use the
|
| 195 |
+
# <b>truetype</b> factory function to create font objects.
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class FreeTypeFont:
|
| 199 |
+
"""FreeType font wrapper (requires _imagingft service)"""
|
| 200 |
+
|
| 201 |
+
font: Font
|
| 202 |
+
font_bytes: bytes
|
| 203 |
+
|
| 204 |
+
def __init__(
|
| 205 |
+
self,
|
| 206 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
| 207 |
+
size: float = 10,
|
| 208 |
+
index: int = 0,
|
| 209 |
+
encoding: str = "",
|
| 210 |
+
layout_engine: Layout | None = None,
|
| 211 |
+
) -> None:
|
| 212 |
+
# FIXME: use service provider instead
|
| 213 |
+
|
| 214 |
+
if isinstance(core, DeferredError):
|
| 215 |
+
raise core.ex
|
| 216 |
+
|
| 217 |
+
if size <= 0:
|
| 218 |
+
msg = "font size must be greater than 0"
|
| 219 |
+
raise ValueError(msg)
|
| 220 |
+
|
| 221 |
+
self.path = font
|
| 222 |
+
self.size = size
|
| 223 |
+
self.index = index
|
| 224 |
+
self.encoding = encoding
|
| 225 |
+
|
| 226 |
+
if layout_engine not in (Layout.BASIC, Layout.RAQM):
|
| 227 |
+
layout_engine = Layout.BASIC
|
| 228 |
+
if core.HAVE_RAQM:
|
| 229 |
+
layout_engine = Layout.RAQM
|
| 230 |
+
elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
|
| 231 |
+
warnings.warn(
|
| 232 |
+
"Raqm layout was requested, but Raqm is not available. "
|
| 233 |
+
"Falling back to basic layout."
|
| 234 |
+
)
|
| 235 |
+
layout_engine = Layout.BASIC
|
| 236 |
+
|
| 237 |
+
self.layout_engine = layout_engine
|
| 238 |
+
|
| 239 |
+
def load_from_bytes(f):
|
| 240 |
+
self.font_bytes = f.read()
|
| 241 |
+
self.font = core.getfont(
|
| 242 |
+
"", size, index, encoding, self.font_bytes, layout_engine
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
if is_path(font):
|
| 246 |
+
font = os.path.realpath(os.fspath(font))
|
| 247 |
+
if sys.platform == "win32":
|
| 248 |
+
font_bytes_path = font if isinstance(font, bytes) else font.encode()
|
| 249 |
+
try:
|
| 250 |
+
font_bytes_path.decode("ascii")
|
| 251 |
+
except UnicodeDecodeError:
|
| 252 |
+
# FreeType cannot load fonts with non-ASCII characters on Windows
|
| 253 |
+
# So load it into memory first
|
| 254 |
+
with open(font, "rb") as f:
|
| 255 |
+
load_from_bytes(f)
|
| 256 |
+
return
|
| 257 |
+
self.font = core.getfont(
|
| 258 |
+
font, size, index, encoding, layout_engine=layout_engine
|
| 259 |
+
)
|
| 260 |
+
else:
|
| 261 |
+
load_from_bytes(font)
|
| 262 |
+
|
| 263 |
+
def __getstate__(self):
|
| 264 |
+
return [self.path, self.size, self.index, self.encoding, self.layout_engine]
|
| 265 |
+
|
| 266 |
+
def __setstate__(self, state):
|
| 267 |
+
path, size, index, encoding, layout_engine = state
|
| 268 |
+
self.__init__(path, size, index, encoding, layout_engine)
|
| 269 |
+
|
| 270 |
+
def getname(self) -> tuple[str | None, str | None]:
|
| 271 |
+
"""
|
| 272 |
+
:return: A tuple of the font family (e.g. Helvetica) and the font style
|
| 273 |
+
(e.g. Bold)
|
| 274 |
+
"""
|
| 275 |
+
return self.font.family, self.font.style
|
| 276 |
+
|
| 277 |
+
def getmetrics(self) -> tuple[int, int]:
|
| 278 |
+
"""
|
| 279 |
+
:return: A tuple of the font ascent (the distance from the baseline to
|
| 280 |
+
the highest outline point) and descent (the distance from the
|
| 281 |
+
baseline to the lowest outline point, a negative value)
|
| 282 |
+
"""
|
| 283 |
+
return self.font.ascent, self.font.descent
|
| 284 |
+
|
| 285 |
+
def getlength(
|
| 286 |
+
self, text: str | bytes, mode="", direction=None, features=None, language=None
|
| 287 |
+
) -> float:
|
| 288 |
+
"""
|
| 289 |
+
Returns length (in pixels with 1/64 precision) of given text when rendered
|
| 290 |
+
in font with provided direction, features, and language.
|
| 291 |
+
|
| 292 |
+
This is the amount by which following text should be offset.
|
| 293 |
+
Text bounding box may extend past the length in some fonts,
|
| 294 |
+
e.g. when using italics or accents.
|
| 295 |
+
|
| 296 |
+
The result is returned as a float; it is a whole number if using basic layout.
|
| 297 |
+
|
| 298 |
+
Note that the sum of two lengths may not equal the length of a concatenated
|
| 299 |
+
string due to kerning. If you need to adjust for kerning, include the following
|
| 300 |
+
character and subtract its length.
|
| 301 |
+
|
| 302 |
+
For example, instead of ::
|
| 303 |
+
|
| 304 |
+
hello = font.getlength("Hello")
|
| 305 |
+
world = font.getlength("World")
|
| 306 |
+
hello_world = hello + world # not adjusted for kerning
|
| 307 |
+
assert hello_world == font.getlength("HelloWorld") # may fail
|
| 308 |
+
|
| 309 |
+
use ::
|
| 310 |
+
|
| 311 |
+
hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
|
| 312 |
+
world = font.getlength("World")
|
| 313 |
+
hello_world = hello + world # adjusted for kerning
|
| 314 |
+
assert hello_world == font.getlength("HelloWorld") # True
|
| 315 |
+
|
| 316 |
+
or disable kerning with (requires libraqm) ::
|
| 317 |
+
|
| 318 |
+
hello = draw.textlength("Hello", font, features=["-kern"])
|
| 319 |
+
world = draw.textlength("World", font, features=["-kern"])
|
| 320 |
+
hello_world = hello + world # kerning is disabled, no need to adjust
|
| 321 |
+
assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
|
| 322 |
+
|
| 323 |
+
.. versionadded:: 8.0.0
|
| 324 |
+
|
| 325 |
+
:param text: Text to measure.
|
| 326 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 327 |
+
driver prefers; if empty, the renderer may return either
|
| 328 |
+
mode. Note that the mode is always a string, to simplify
|
| 329 |
+
C-level implementations.
|
| 330 |
+
|
| 331 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 332 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 333 |
+
Requires libraqm.
|
| 334 |
+
|
| 335 |
+
:param features: A list of OpenType font features to be used during text
|
| 336 |
+
layout. This is usually used to turn on optional
|
| 337 |
+
font features that are not enabled by default,
|
| 338 |
+
for example 'dlig' or 'ss01', but can be also
|
| 339 |
+
used to turn off default font features for
|
| 340 |
+
example '-liga' to disable ligatures or '-kern'
|
| 341 |
+
to disable kerning. To get all supported
|
| 342 |
+
features, see
|
| 343 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 344 |
+
Requires libraqm.
|
| 345 |
+
|
| 346 |
+
:param language: Language of the text. Different languages may use
|
| 347 |
+
different glyph shapes or ligatures. This parameter tells
|
| 348 |
+
the font which language the text is in, and to apply the
|
| 349 |
+
correct substitutions as appropriate, if available.
|
| 350 |
+
It should be a `BCP 47 language code
|
| 351 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 352 |
+
Requires libraqm.
|
| 353 |
+
|
| 354 |
+
:return: Either width for horizontal text, or height for vertical text.
|
| 355 |
+
"""
|
| 356 |
+
_string_length_check(text)
|
| 357 |
+
return self.font.getlength(text, mode, direction, features, language) / 64
|
| 358 |
+
|
| 359 |
+
def getbbox(
|
| 360 |
+
self,
|
| 361 |
+
text: str | bytes,
|
| 362 |
+
mode: str = "",
|
| 363 |
+
direction: str | None = None,
|
| 364 |
+
features: list[str] | None = None,
|
| 365 |
+
language: str | None = None,
|
| 366 |
+
stroke_width: float = 0,
|
| 367 |
+
anchor: str | None = None,
|
| 368 |
+
) -> tuple[float, float, float, float]:
|
| 369 |
+
"""
|
| 370 |
+
Returns bounding box (in pixels) of given text relative to given anchor
|
| 371 |
+
when rendered in font with provided direction, features, and language.
|
| 372 |
+
|
| 373 |
+
Use :py:meth:`getlength()` to get the offset of following text with
|
| 374 |
+
1/64 pixel precision. The bounding box includes extra margins for
|
| 375 |
+
some fonts, e.g. italics or accents.
|
| 376 |
+
|
| 377 |
+
.. versionadded:: 8.0.0
|
| 378 |
+
|
| 379 |
+
:param text: Text to render.
|
| 380 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 381 |
+
driver prefers; if empty, the renderer may return either
|
| 382 |
+
mode. Note that the mode is always a string, to simplify
|
| 383 |
+
C-level implementations.
|
| 384 |
+
|
| 385 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 386 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 387 |
+
Requires libraqm.
|
| 388 |
+
|
| 389 |
+
:param features: A list of OpenType font features to be used during text
|
| 390 |
+
layout. This is usually used to turn on optional
|
| 391 |
+
font features that are not enabled by default,
|
| 392 |
+
for example 'dlig' or 'ss01', but can be also
|
| 393 |
+
used to turn off default font features for
|
| 394 |
+
example '-liga' to disable ligatures or '-kern'
|
| 395 |
+
to disable kerning. To get all supported
|
| 396 |
+
features, see
|
| 397 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 398 |
+
Requires libraqm.
|
| 399 |
+
|
| 400 |
+
:param language: Language of the text. Different languages may use
|
| 401 |
+
different glyph shapes or ligatures. This parameter tells
|
| 402 |
+
the font which language the text is in, and to apply the
|
| 403 |
+
correct substitutions as appropriate, if available.
|
| 404 |
+
It should be a `BCP 47 language code
|
| 405 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 406 |
+
Requires libraqm.
|
| 407 |
+
|
| 408 |
+
:param stroke_width: The width of the text stroke.
|
| 409 |
+
|
| 410 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 411 |
+
the anchor to the text. The default alignment is top left,
|
| 412 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 413 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 414 |
+
|
| 415 |
+
:return: ``(left, top, right, bottom)`` bounding box
|
| 416 |
+
"""
|
| 417 |
+
_string_length_check(text)
|
| 418 |
+
size, offset = self.font.getsize(
|
| 419 |
+
text, mode, direction, features, language, anchor
|
| 420 |
+
)
|
| 421 |
+
left, top = offset[0] - stroke_width, offset[1] - stroke_width
|
| 422 |
+
width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
|
| 423 |
+
return left, top, left + width, top + height
|
| 424 |
+
|
| 425 |
+
def getmask(
|
| 426 |
+
self,
|
| 427 |
+
text,
|
| 428 |
+
mode="",
|
| 429 |
+
direction=None,
|
| 430 |
+
features=None,
|
| 431 |
+
language=None,
|
| 432 |
+
stroke_width=0,
|
| 433 |
+
anchor=None,
|
| 434 |
+
ink=0,
|
| 435 |
+
start=None,
|
| 436 |
+
):
|
| 437 |
+
"""
|
| 438 |
+
Create a bitmap for the text.
|
| 439 |
+
|
| 440 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 441 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
| 442 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
| 443 |
+
|
| 444 |
+
:param text: Text to render.
|
| 445 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 446 |
+
driver prefers; if empty, the renderer may return either
|
| 447 |
+
mode. Note that the mode is always a string, to simplify
|
| 448 |
+
C-level implementations.
|
| 449 |
+
|
| 450 |
+
.. versionadded:: 1.1.5
|
| 451 |
+
|
| 452 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 453 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 454 |
+
Requires libraqm.
|
| 455 |
+
|
| 456 |
+
.. versionadded:: 4.2.0
|
| 457 |
+
|
| 458 |
+
:param features: A list of OpenType font features to be used during text
|
| 459 |
+
layout. This is usually used to turn on optional
|
| 460 |
+
font features that are not enabled by default,
|
| 461 |
+
for example 'dlig' or 'ss01', but can be also
|
| 462 |
+
used to turn off default font features for
|
| 463 |
+
example '-liga' to disable ligatures or '-kern'
|
| 464 |
+
to disable kerning. To get all supported
|
| 465 |
+
features, see
|
| 466 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 467 |
+
Requires libraqm.
|
| 468 |
+
|
| 469 |
+
.. versionadded:: 4.2.0
|
| 470 |
+
|
| 471 |
+
:param language: Language of the text. Different languages may use
|
| 472 |
+
different glyph shapes or ligatures. This parameter tells
|
| 473 |
+
the font which language the text is in, and to apply the
|
| 474 |
+
correct substitutions as appropriate, if available.
|
| 475 |
+
It should be a `BCP 47 language code
|
| 476 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 477 |
+
Requires libraqm.
|
| 478 |
+
|
| 479 |
+
.. versionadded:: 6.0.0
|
| 480 |
+
|
| 481 |
+
:param stroke_width: The width of the text stroke.
|
| 482 |
+
|
| 483 |
+
.. versionadded:: 6.2.0
|
| 484 |
+
|
| 485 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 486 |
+
the anchor to the text. The default alignment is top left,
|
| 487 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 488 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 489 |
+
|
| 490 |
+
.. versionadded:: 8.0.0
|
| 491 |
+
|
| 492 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
| 493 |
+
|
| 494 |
+
.. versionadded:: 8.0.0
|
| 495 |
+
|
| 496 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
| 497 |
+
differently when starting at fractional coordinates.
|
| 498 |
+
|
| 499 |
+
.. versionadded:: 9.4.0
|
| 500 |
+
|
| 501 |
+
:return: An internal PIL storage memory instance as defined by the
|
| 502 |
+
:py:mod:`PIL.Image.core` interface module.
|
| 503 |
+
"""
|
| 504 |
+
return self.getmask2(
|
| 505 |
+
text,
|
| 506 |
+
mode,
|
| 507 |
+
direction=direction,
|
| 508 |
+
features=features,
|
| 509 |
+
language=language,
|
| 510 |
+
stroke_width=stroke_width,
|
| 511 |
+
anchor=anchor,
|
| 512 |
+
ink=ink,
|
| 513 |
+
start=start,
|
| 514 |
+
)[0]
|
| 515 |
+
|
| 516 |
+
def getmask2(
|
| 517 |
+
self,
|
| 518 |
+
text: str | bytes,
|
| 519 |
+
mode="",
|
| 520 |
+
direction=None,
|
| 521 |
+
features=None,
|
| 522 |
+
language=None,
|
| 523 |
+
stroke_width=0,
|
| 524 |
+
anchor=None,
|
| 525 |
+
ink=0,
|
| 526 |
+
start=None,
|
| 527 |
+
*args,
|
| 528 |
+
**kwargs,
|
| 529 |
+
):
|
| 530 |
+
"""
|
| 531 |
+
Create a bitmap for the text.
|
| 532 |
+
|
| 533 |
+
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
|
| 534 |
+
maximum value of 255. If the font has embedded color data, the bitmap
|
| 535 |
+
should have mode ``RGBA``. Otherwise, it should have mode ``1``.
|
| 536 |
+
|
| 537 |
+
:param text: Text to render.
|
| 538 |
+
:param mode: Used by some graphics drivers to indicate what mode the
|
| 539 |
+
driver prefers; if empty, the renderer may return either
|
| 540 |
+
mode. Note that the mode is always a string, to simplify
|
| 541 |
+
C-level implementations.
|
| 542 |
+
|
| 543 |
+
.. versionadded:: 1.1.5
|
| 544 |
+
|
| 545 |
+
:param direction: Direction of the text. It can be 'rtl' (right to
|
| 546 |
+
left), 'ltr' (left to right) or 'ttb' (top to bottom).
|
| 547 |
+
Requires libraqm.
|
| 548 |
+
|
| 549 |
+
.. versionadded:: 4.2.0
|
| 550 |
+
|
| 551 |
+
:param features: A list of OpenType font features to be used during text
|
| 552 |
+
layout. This is usually used to turn on optional
|
| 553 |
+
font features that are not enabled by default,
|
| 554 |
+
for example 'dlig' or 'ss01', but can be also
|
| 555 |
+
used to turn off default font features for
|
| 556 |
+
example '-liga' to disable ligatures or '-kern'
|
| 557 |
+
to disable kerning. To get all supported
|
| 558 |
+
features, see
|
| 559 |
+
https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
|
| 560 |
+
Requires libraqm.
|
| 561 |
+
|
| 562 |
+
.. versionadded:: 4.2.0
|
| 563 |
+
|
| 564 |
+
:param language: Language of the text. Different languages may use
|
| 565 |
+
different glyph shapes or ligatures. This parameter tells
|
| 566 |
+
the font which language the text is in, and to apply the
|
| 567 |
+
correct substitutions as appropriate, if available.
|
| 568 |
+
It should be a `BCP 47 language code
|
| 569 |
+
<https://www.w3.org/International/articles/language-tags/>`_
|
| 570 |
+
Requires libraqm.
|
| 571 |
+
|
| 572 |
+
.. versionadded:: 6.0.0
|
| 573 |
+
|
| 574 |
+
:param stroke_width: The width of the text stroke.
|
| 575 |
+
|
| 576 |
+
.. versionadded:: 6.2.0
|
| 577 |
+
|
| 578 |
+
:param anchor: The text anchor alignment. Determines the relative location of
|
| 579 |
+
the anchor to the text. The default alignment is top left,
|
| 580 |
+
specifically ``la`` for horizontal text and ``lt`` for
|
| 581 |
+
vertical text. See :ref:`text-anchors` for details.
|
| 582 |
+
|
| 583 |
+
.. versionadded:: 8.0.0
|
| 584 |
+
|
| 585 |
+
:param ink: Foreground ink for rendering in RGBA mode.
|
| 586 |
+
|
| 587 |
+
.. versionadded:: 8.0.0
|
| 588 |
+
|
| 589 |
+
:param start: Tuple of horizontal and vertical offset, as text may render
|
| 590 |
+
differently when starting at fractional coordinates.
|
| 591 |
+
|
| 592 |
+
.. versionadded:: 9.4.0
|
| 593 |
+
|
| 594 |
+
:return: A tuple of an internal PIL storage memory instance as defined by the
|
| 595 |
+
:py:mod:`PIL.Image.core` interface module, and the text offset, the
|
| 596 |
+
gap between the starting coordinate and the first marking
|
| 597 |
+
"""
|
| 598 |
+
_string_length_check(text)
|
| 599 |
+
if start is None:
|
| 600 |
+
start = (0, 0)
|
| 601 |
+
|
| 602 |
+
def fill(width, height):
|
| 603 |
+
size = (width, height)
|
| 604 |
+
Image._decompression_bomb_check(size)
|
| 605 |
+
return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
|
| 606 |
+
|
| 607 |
+
return self.font.render(
|
| 608 |
+
text,
|
| 609 |
+
fill,
|
| 610 |
+
mode,
|
| 611 |
+
direction,
|
| 612 |
+
features,
|
| 613 |
+
language,
|
| 614 |
+
stroke_width,
|
| 615 |
+
anchor,
|
| 616 |
+
ink,
|
| 617 |
+
start[0],
|
| 618 |
+
start[1],
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
def font_variant(
|
| 622 |
+
self, font=None, size=None, index=None, encoding=None, layout_engine=None
|
| 623 |
+
):
|
| 624 |
+
"""
|
| 625 |
+
Create a copy of this FreeTypeFont object,
|
| 626 |
+
using any specified arguments to override the settings.
|
| 627 |
+
|
| 628 |
+
Parameters are identical to the parameters used to initialize this
|
| 629 |
+
object.
|
| 630 |
+
|
| 631 |
+
:return: A FreeTypeFont object.
|
| 632 |
+
"""
|
| 633 |
+
if font is None:
|
| 634 |
+
try:
|
| 635 |
+
font = BytesIO(self.font_bytes)
|
| 636 |
+
except AttributeError:
|
| 637 |
+
font = self.path
|
| 638 |
+
return FreeTypeFont(
|
| 639 |
+
font=font,
|
| 640 |
+
size=self.size if size is None else size,
|
| 641 |
+
index=self.index if index is None else index,
|
| 642 |
+
encoding=self.encoding if encoding is None else encoding,
|
| 643 |
+
layout_engine=layout_engine or self.layout_engine,
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
def get_variation_names(self) -> list[bytes]:
|
| 647 |
+
"""
|
| 648 |
+
:returns: A list of the named styles in a variation font.
|
| 649 |
+
:exception OSError: If the font is not a variation font.
|
| 650 |
+
"""
|
| 651 |
+
try:
|
| 652 |
+
names = self.font.getvarnames()
|
| 653 |
+
except AttributeError as e:
|
| 654 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 655 |
+
raise NotImplementedError(msg) from e
|
| 656 |
+
return [name.replace(b"\x00", b"") for name in names]
|
| 657 |
+
|
| 658 |
+
def set_variation_by_name(self, name):
|
| 659 |
+
"""
|
| 660 |
+
:param name: The name of the style.
|
| 661 |
+
:exception OSError: If the font is not a variation font.
|
| 662 |
+
"""
|
| 663 |
+
names = self.get_variation_names()
|
| 664 |
+
if not isinstance(name, bytes):
|
| 665 |
+
name = name.encode()
|
| 666 |
+
index = names.index(name) + 1
|
| 667 |
+
|
| 668 |
+
if index == getattr(self, "_last_variation_index", None):
|
| 669 |
+
# When the same name is set twice in a row,
|
| 670 |
+
# there is an 'unknown freetype error'
|
| 671 |
+
# https://savannah.nongnu.org/bugs/?56186
|
| 672 |
+
return
|
| 673 |
+
self._last_variation_index = index
|
| 674 |
+
|
| 675 |
+
self.font.setvarname(index)
|
| 676 |
+
|
| 677 |
+
def get_variation_axes(self):
|
| 678 |
+
"""
|
| 679 |
+
:returns: A list of the axes in a variation font.
|
| 680 |
+
:exception OSError: If the font is not a variation font.
|
| 681 |
+
"""
|
| 682 |
+
try:
|
| 683 |
+
axes = self.font.getvaraxes()
|
| 684 |
+
except AttributeError as e:
|
| 685 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 686 |
+
raise NotImplementedError(msg) from e
|
| 687 |
+
for axis in axes:
|
| 688 |
+
if axis["name"]:
|
| 689 |
+
axis["name"] = axis["name"].replace(b"\x00", b"")
|
| 690 |
+
return axes
|
| 691 |
+
|
| 692 |
+
def set_variation_by_axes(self, axes: list[float]) -> None:
|
| 693 |
+
"""
|
| 694 |
+
:param axes: A list of values for each axis.
|
| 695 |
+
:exception OSError: If the font is not a variation font.
|
| 696 |
+
"""
|
| 697 |
+
try:
|
| 698 |
+
self.font.setvaraxes(axes)
|
| 699 |
+
except AttributeError as e:
|
| 700 |
+
msg = "FreeType 2.9.1 or greater is required"
|
| 701 |
+
raise NotImplementedError(msg) from e
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class TransposedFont:
|
| 705 |
+
"""Wrapper for writing rotated or mirrored text"""
|
| 706 |
+
|
| 707 |
+
def __init__(self, font, orientation=None):
|
| 708 |
+
"""
|
| 709 |
+
Wrapper that creates a transposed font from any existing font
|
| 710 |
+
object.
|
| 711 |
+
|
| 712 |
+
:param font: A font object.
|
| 713 |
+
:param orientation: An optional orientation. If given, this should
|
| 714 |
+
be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
|
| 715 |
+
Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
|
| 716 |
+
Image.Transpose.ROTATE_270.
|
| 717 |
+
"""
|
| 718 |
+
self.font = font
|
| 719 |
+
self.orientation = orientation # any 'transpose' argument, or None
|
| 720 |
+
|
| 721 |
+
def getmask(self, text, mode="", *args, **kwargs):
|
| 722 |
+
im = self.font.getmask(text, mode, *args, **kwargs)
|
| 723 |
+
if self.orientation is not None:
|
| 724 |
+
return im.transpose(self.orientation)
|
| 725 |
+
return im
|
| 726 |
+
|
| 727 |
+
def getbbox(self, text, *args, **kwargs):
|
| 728 |
+
# TransposedFont doesn't support getmask2, move top-left point to (0, 0)
|
| 729 |
+
# this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
|
| 730 |
+
left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
|
| 731 |
+
width = right - left
|
| 732 |
+
height = bottom - top
|
| 733 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
| 734 |
+
return 0, 0, height, width
|
| 735 |
+
return 0, 0, width, height
|
| 736 |
+
|
| 737 |
+
def getlength(self, text: str | bytes, *args, **kwargs) -> float:
|
| 738 |
+
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
|
| 739 |
+
msg = "text length is undefined for text rotated by 90 or 270 degrees"
|
| 740 |
+
raise ValueError(msg)
|
| 741 |
+
return self.font.getlength(text, *args, **kwargs)
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def load(filename: str) -> ImageFont:
|
| 745 |
+
"""
|
| 746 |
+
Load a font file. This function loads a font object from the given
|
| 747 |
+
bitmap font file, and returns the corresponding font object.
|
| 748 |
+
|
| 749 |
+
:param filename: Name of font file.
|
| 750 |
+
:return: A font object.
|
| 751 |
+
:exception OSError: If the file could not be read.
|
| 752 |
+
"""
|
| 753 |
+
f = ImageFont()
|
| 754 |
+
f._load_pilfont(filename)
|
| 755 |
+
return f
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def truetype(
|
| 759 |
+
font: StrOrBytesPath | BinaryIO | None = None,
|
| 760 |
+
size: float = 10,
|
| 761 |
+
index: int = 0,
|
| 762 |
+
encoding: str = "",
|
| 763 |
+
layout_engine: Layout | None = None,
|
| 764 |
+
) -> FreeTypeFont:
|
| 765 |
+
"""
|
| 766 |
+
Load a TrueType or OpenType font from a file or file-like object,
|
| 767 |
+
and create a font object.
|
| 768 |
+
This function loads a font object from the given file or file-like
|
| 769 |
+
object, and creates a font object for a font of the given size.
|
| 770 |
+
|
| 771 |
+
Pillow uses FreeType to open font files. On Windows, be aware that FreeType
|
| 772 |
+
will keep the file open as long as the FreeTypeFont object exists. Windows
|
| 773 |
+
limits the number of files that can be open in C at once to 512, so if many
|
| 774 |
+
fonts are opened simultaneously and that limit is approached, an
|
| 775 |
+
``OSError`` may be thrown, reporting that FreeType "cannot open resource".
|
| 776 |
+
A workaround would be to copy the file(s) into memory, and open that instead.
|
| 777 |
+
|
| 778 |
+
This function requires the _imagingft service.
|
| 779 |
+
|
| 780 |
+
:param font: A filename or file-like object containing a TrueType font.
|
| 781 |
+
If the file is not found in this filename, the loader may also
|
| 782 |
+
search in other directories, such as:
|
| 783 |
+
|
| 784 |
+
* The :file:`fonts/` directory on Windows,
|
| 785 |
+
* :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
|
| 786 |
+
and :file:`~/Library/Fonts/` on macOS.
|
| 787 |
+
* :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
|
| 788 |
+
and :file:`/usr/share/fonts` on Linux; or those specified by
|
| 789 |
+
the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
|
| 790 |
+
for user-installed and system-wide fonts, respectively.
|
| 791 |
+
|
| 792 |
+
:param size: The requested size, in pixels.
|
| 793 |
+
:param index: Which font face to load (default is first available face).
|
| 794 |
+
:param encoding: Which font encoding to use (default is Unicode). Possible
|
| 795 |
+
encodings include (see the FreeType documentation for more
|
| 796 |
+
information):
|
| 797 |
+
|
| 798 |
+
* "unic" (Unicode)
|
| 799 |
+
* "symb" (Microsoft Symbol)
|
| 800 |
+
* "ADOB" (Adobe Standard)
|
| 801 |
+
* "ADBE" (Adobe Expert)
|
| 802 |
+
* "ADBC" (Adobe Custom)
|
| 803 |
+
* "armn" (Apple Roman)
|
| 804 |
+
* "sjis" (Shift JIS)
|
| 805 |
+
* "gb " (PRC)
|
| 806 |
+
* "big5"
|
| 807 |
+
* "wans" (Extended Wansung)
|
| 808 |
+
* "joha" (Johab)
|
| 809 |
+
* "lat1" (Latin-1)
|
| 810 |
+
|
| 811 |
+
This specifies the character set to use. It does not alter the
|
| 812 |
+
encoding of any text provided in subsequent operations.
|
| 813 |
+
:param layout_engine: Which layout engine to use, if available:
|
| 814 |
+
:attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
|
| 815 |
+
If it is available, Raqm layout will be used by default.
|
| 816 |
+
Otherwise, basic layout will be used.
|
| 817 |
+
|
| 818 |
+
Raqm layout is recommended for all non-English text. If Raqm layout
|
| 819 |
+
is not required, basic layout will have better performance.
|
| 820 |
+
|
| 821 |
+
You can check support for Raqm layout using
|
| 822 |
+
:py:func:`PIL.features.check_feature` with ``feature="raqm"``.
|
| 823 |
+
|
| 824 |
+
.. versionadded:: 4.2.0
|
| 825 |
+
:return: A font object.
|
| 826 |
+
:exception OSError: If the file could not be read.
|
| 827 |
+
:exception ValueError: If the font size is not greater than zero.
|
| 828 |
+
"""
|
| 829 |
+
|
| 830 |
+
def freetype(font: StrOrBytesPath | BinaryIO | None) -> FreeTypeFont:
|
| 831 |
+
return FreeTypeFont(font, size, index, encoding, layout_engine)
|
| 832 |
+
|
| 833 |
+
try:
|
| 834 |
+
return freetype(font)
|
| 835 |
+
except OSError:
|
| 836 |
+
if not is_path(font):
|
| 837 |
+
raise
|
| 838 |
+
ttf_filename = os.path.basename(font)
|
| 839 |
+
|
| 840 |
+
dirs = []
|
| 841 |
+
if sys.platform == "win32":
|
| 842 |
+
# check the windows font repository
|
| 843 |
+
# NOTE: must use uppercase WINDIR, to work around bugs in
|
| 844 |
+
# 1.5.2's os.environ.get()
|
| 845 |
+
windir = os.environ.get("WINDIR")
|
| 846 |
+
if windir:
|
| 847 |
+
dirs.append(os.path.join(windir, "fonts"))
|
| 848 |
+
elif sys.platform in ("linux", "linux2"):
|
| 849 |
+
data_home = os.environ.get("XDG_DATA_HOME")
|
| 850 |
+
if not data_home:
|
| 851 |
+
# The freedesktop spec defines the following default directory for
|
| 852 |
+
# when XDG_DATA_HOME is unset or empty. This user-level directory
|
| 853 |
+
# takes precedence over system-level directories.
|
| 854 |
+
data_home = os.path.expanduser("~/.local/share")
|
| 855 |
+
xdg_dirs = [data_home]
|
| 856 |
+
|
| 857 |
+
data_dirs = os.environ.get("XDG_DATA_DIRS")
|
| 858 |
+
if not data_dirs:
|
| 859 |
+
# Similarly, defaults are defined for the system-level directories
|
| 860 |
+
data_dirs = "/usr/local/share:/usr/share"
|
| 861 |
+
xdg_dirs += data_dirs.split(":")
|
| 862 |
+
|
| 863 |
+
dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
|
| 864 |
+
elif sys.platform == "darwin":
|
| 865 |
+
dirs += [
|
| 866 |
+
"/Library/Fonts",
|
| 867 |
+
"/System/Library/Fonts",
|
| 868 |
+
os.path.expanduser("~/Library/Fonts"),
|
| 869 |
+
]
|
| 870 |
+
|
| 871 |
+
ext = os.path.splitext(ttf_filename)[1]
|
| 872 |
+
first_font_with_a_different_extension = None
|
| 873 |
+
for directory in dirs:
|
| 874 |
+
for walkroot, walkdir, walkfilenames in os.walk(directory):
|
| 875 |
+
for walkfilename in walkfilenames:
|
| 876 |
+
if ext and walkfilename == ttf_filename:
|
| 877 |
+
return freetype(os.path.join(walkroot, walkfilename))
|
| 878 |
+
elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
|
| 879 |
+
fontpath = os.path.join(walkroot, walkfilename)
|
| 880 |
+
if os.path.splitext(fontpath)[1] == ".ttf":
|
| 881 |
+
return freetype(fontpath)
|
| 882 |
+
if not ext and first_font_with_a_different_extension is None:
|
| 883 |
+
first_font_with_a_different_extension = fontpath
|
| 884 |
+
if first_font_with_a_different_extension:
|
| 885 |
+
return freetype(first_font_with_a_different_extension)
|
| 886 |
+
raise
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def load_path(filename: str | bytes) -> ImageFont:
|
| 890 |
+
"""
|
| 891 |
+
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
|
| 892 |
+
bitmap font along the Python path.
|
| 893 |
+
|
| 894 |
+
:param filename: Name of font file.
|
| 895 |
+
:return: A font object.
|
| 896 |
+
:exception OSError: If the file could not be read.
|
| 897 |
+
"""
|
| 898 |
+
if not isinstance(filename, str):
|
| 899 |
+
filename = filename.decode("utf-8")
|
| 900 |
+
for directory in sys.path:
|
| 901 |
+
try:
|
| 902 |
+
return load(os.path.join(directory, filename))
|
| 903 |
+
except OSError:
|
| 904 |
+
pass
|
| 905 |
+
msg = "cannot find font file"
|
| 906 |
+
raise OSError(msg)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def load_default_imagefont() -> ImageFont:
|
| 910 |
+
f = ImageFont()
|
| 911 |
+
f._load_pilfont_data(
|
| 912 |
+
# courB08
|
| 913 |
+
BytesIO(
|
| 914 |
+
base64.b64decode(
|
| 915 |
+
b"""
|
| 916 |
+
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 917 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 918 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 919 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 920 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 921 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
| 922 |
+
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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VgAH
|
| 935 |
+
AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
|
| 936 |
+
ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
|
| 937 |
+
AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
|
| 938 |
+
/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
|
| 939 |
+
AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
|
| 940 |
+
AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
|
| 941 |
+
AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
|
| 942 |
+
BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
|
| 943 |
+
AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
|
| 944 |
+
2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
|
| 945 |
+
AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
|
| 946 |
+
+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
|
| 947 |
+
////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
|
| 948 |
+
BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
|
| 949 |
+
AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
|
| 950 |
+
AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
|
| 951 |
+
AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
|
| 952 |
+
BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
|
| 953 |
+
//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
|
| 954 |
+
AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
|
| 955 |
+
AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
|
| 956 |
+
mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
|
| 957 |
+
AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
|
| 958 |
+
AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
|
| 959 |
+
AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
|
| 960 |
+
Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
|
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AAAAAAAAAAAYAAAAB
|
| 973 |
+
//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
|
| 974 |
+
AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/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
|
| 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wdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
|
| 1031 |
+
pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
|
| 1032 |
+
oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+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 |
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ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
|
| 1281 |
+
gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
|
| 1282 |
+
YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
|
| 1283 |
+
AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
|
| 1284 |
+
"""
|
| 1285 |
+
)
|
| 1286 |
+
),
|
| 1287 |
+
10 if size is None else size,
|
| 1288 |
+
layout_engine=Layout.BASIC,
|
| 1289 |
+
)
|
| 1290 |
+
return load_default_imagefont()
|
.venv/lib/python3.11/site-packages/PIL/ImageMode.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# standard mode descriptors
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2006-03-20 fl Added
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2006 by Secret Labs AB.
|
| 11 |
+
# Copyright (c) 2006 by Fredrik Lundh.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
from functools import lru_cache
|
| 19 |
+
from typing import NamedTuple
|
| 20 |
+
|
| 21 |
+
from ._deprecate import deprecate
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ModeDescriptor(NamedTuple):
|
| 25 |
+
"""Wrapper for mode strings."""
|
| 26 |
+
|
| 27 |
+
mode: str
|
| 28 |
+
bands: tuple[str, ...]
|
| 29 |
+
basemode: str
|
| 30 |
+
basetype: str
|
| 31 |
+
typestr: str
|
| 32 |
+
|
| 33 |
+
def __str__(self) -> str:
|
| 34 |
+
return self.mode
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@lru_cache
|
| 38 |
+
def getmode(mode: str) -> ModeDescriptor:
|
| 39 |
+
"""Gets a mode descriptor for the given mode."""
|
| 40 |
+
endian = "<" if sys.byteorder == "little" else ">"
|
| 41 |
+
|
| 42 |
+
modes = {
|
| 43 |
+
# core modes
|
| 44 |
+
# Bits need to be extended to bytes
|
| 45 |
+
"1": ("L", "L", ("1",), "|b1"),
|
| 46 |
+
"L": ("L", "L", ("L",), "|u1"),
|
| 47 |
+
"I": ("L", "I", ("I",), f"{endian}i4"),
|
| 48 |
+
"F": ("L", "F", ("F",), f"{endian}f4"),
|
| 49 |
+
"P": ("P", "L", ("P",), "|u1"),
|
| 50 |
+
"RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
|
| 51 |
+
"RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
|
| 52 |
+
"RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
|
| 53 |
+
"CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
|
| 54 |
+
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
|
| 55 |
+
# UNDONE - unsigned |u1i1i1
|
| 56 |
+
"LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
|
| 57 |
+
"HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
|
| 58 |
+
# extra experimental modes
|
| 59 |
+
"RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
|
| 60 |
+
"BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
| 61 |
+
"BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
| 62 |
+
"BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
|
| 63 |
+
"LA": ("L", "L", ("L", "A"), "|u1"),
|
| 64 |
+
"La": ("L", "L", ("L", "a"), "|u1"),
|
| 65 |
+
"PA": ("RGB", "L", ("P", "A"), "|u1"),
|
| 66 |
+
}
|
| 67 |
+
if mode in modes:
|
| 68 |
+
if mode in ("BGR;15", "BGR;16", "BGR;24"):
|
| 69 |
+
deprecate(mode, 12)
|
| 70 |
+
base_mode, base_type, bands, type_str = modes[mode]
|
| 71 |
+
return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
|
| 72 |
+
|
| 73 |
+
mapping_modes = {
|
| 74 |
+
# I;16 == I;16L, and I;32 == I;32L
|
| 75 |
+
"I;16": "<u2",
|
| 76 |
+
"I;16S": "<i2",
|
| 77 |
+
"I;16L": "<u2",
|
| 78 |
+
"I;16LS": "<i2",
|
| 79 |
+
"I;16B": ">u2",
|
| 80 |
+
"I;16BS": ">i2",
|
| 81 |
+
"I;16N": f"{endian}u2",
|
| 82 |
+
"I;16NS": f"{endian}i2",
|
| 83 |
+
"I;32": "<u4",
|
| 84 |
+
"I;32B": ">u4",
|
| 85 |
+
"I;32L": "<u4",
|
| 86 |
+
"I;32S": "<i4",
|
| 87 |
+
"I;32BS": ">i4",
|
| 88 |
+
"I;32LS": "<i4",
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
type_str = mapping_modes[mode]
|
| 92 |
+
return ModeDescriptor(mode, ("I",), "L", "L", type_str)
|
.venv/lib/python3.11/site-packages/PIL/ImagePath.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# path interface
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1996-11-04 fl Created
|
| 9 |
+
# 2002-04-14 fl Added documentation stub class
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from . import Image
|
| 19 |
+
|
| 20 |
+
Path = Image.core.path
|
.venv/lib/python3.11/site-packages/PIL/ImageShow.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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# History:
|
| 8 |
+
# 2008-04-06 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 2008.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import abc
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
from shlex import quote
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from . import Image
|
| 25 |
+
|
| 26 |
+
_viewers = []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def register(viewer, 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:]))
|
.venv/lib/python3.11/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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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()
|
.venv/lib/python3.11/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
|
.venv/lib/python3.11/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))
|
.venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# IM Tools support for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 1996-05-27 fl Created (read 8-bit images only)
|
| 9 |
+
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997-2001.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996-2001.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
from . import Image, ImageFile
|
| 21 |
+
|
| 22 |
+
#
|
| 23 |
+
# --------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
##
|
| 29 |
+
# Image plugin for IM Tools images.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ImtImageFile(ImageFile.ImageFile):
|
| 33 |
+
format = "IMT"
|
| 34 |
+
format_description = "IM Tools"
|
| 35 |
+
|
| 36 |
+
def _open(self) -> None:
|
| 37 |
+
# Quick rejection: if there's not a LF among the first
|
| 38 |
+
# 100 bytes, this is (probably) not a text header.
|
| 39 |
+
|
| 40 |
+
assert self.fp is not None
|
| 41 |
+
|
| 42 |
+
buffer = self.fp.read(100)
|
| 43 |
+
if b"\n" not in buffer:
|
| 44 |
+
msg = "not an IM file"
|
| 45 |
+
raise SyntaxError(msg)
|
| 46 |
+
|
| 47 |
+
xsize = ysize = 0
|
| 48 |
+
|
| 49 |
+
while True:
|
| 50 |
+
if buffer:
|
| 51 |
+
s = buffer[:1]
|
| 52 |
+
buffer = buffer[1:]
|
| 53 |
+
else:
|
| 54 |
+
s = self.fp.read(1)
|
| 55 |
+
if not s:
|
| 56 |
+
break
|
| 57 |
+
|
| 58 |
+
if s == b"\x0C":
|
| 59 |
+
# image data begins
|
| 60 |
+
self.tile = [
|
| 61 |
+
(
|
| 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)
|
.venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# JPEG2000 file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2014-03-12 ajh Created
|
| 9 |
+
# 2021-06-30 rogermb Extract dpi information from the 'resc' header box
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2014 Coriolis Systems Limited
|
| 12 |
+
# Copyright (c) 2014 Alastair Houghton
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
import os
|
| 20 |
+
import struct
|
| 21 |
+
from typing import 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")
|
.venv/lib/python3.11/site-packages/PIL/JpegPresets.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JPEG quality settings equivalent to the Photoshop settings.
|
| 3 |
+
Can be used when saving JPEG files.
|
| 4 |
+
|
| 5 |
+
The following presets are available by default:
|
| 6 |
+
``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
|
| 7 |
+
``low``, ``medium``, ``high``, ``maximum``.
|
| 8 |
+
More presets can be added to the :py:data:`presets` dict if needed.
|
| 9 |
+
|
| 10 |
+
To apply the preset, specify::
|
| 11 |
+
|
| 12 |
+
quality="preset_name"
|
| 13 |
+
|
| 14 |
+
To apply only the quantization table::
|
| 15 |
+
|
| 16 |
+
qtables="preset_name"
|
| 17 |
+
|
| 18 |
+
To apply only the subsampling setting::
|
| 19 |
+
|
| 20 |
+
subsampling="preset_name"
|
| 21 |
+
|
| 22 |
+
Example::
|
| 23 |
+
|
| 24 |
+
im.save("image_name.jpg", quality="web_high")
|
| 25 |
+
|
| 26 |
+
Subsampling
|
| 27 |
+
-----------
|
| 28 |
+
|
| 29 |
+
Subsampling is the practice of encoding images by implementing less resolution
|
| 30 |
+
for chroma information than for luma information.
|
| 31 |
+
(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
|
| 32 |
+
|
| 33 |
+
Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and
|
| 34 |
+
4:2:0.
|
| 35 |
+
|
| 36 |
+
You can get the subsampling of a JPEG with the
|
| 37 |
+
:func:`.JpegImagePlugin.get_sampling` function.
|
| 38 |
+
|
| 39 |
+
In JPEG compressed data a JPEG marker is used instead of an EXIF tag.
|
| 40 |
+
(ref.: https://web.archive.org/web/20240227115053/https://exiv2.org/tags.html)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
Quantization tables
|
| 44 |
+
-------------------
|
| 45 |
+
|
| 46 |
+
They are values use by the DCT (Discrete cosine transform) to remove
|
| 47 |
+
*unnecessary* information from the image (the lossy part of the compression).
|
| 48 |
+
(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
|
| 49 |
+
https://en.wikipedia.org/wiki/JPEG#Quantization)
|
| 50 |
+
|
| 51 |
+
You can get the quantization tables of a JPEG with::
|
| 52 |
+
|
| 53 |
+
im.quantization
|
| 54 |
+
|
| 55 |
+
This will return a dict with a number of lists. You can pass this dict
|
| 56 |
+
directly as the qtables argument when saving a JPEG.
|
| 57 |
+
|
| 58 |
+
The quantization table format in presets is a list with sublists. These formats
|
| 59 |
+
are interchangeable.
|
| 60 |
+
|
| 61 |
+
Libjpeg ref.:
|
| 62 |
+
https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
from __future__ import annotations
|
| 67 |
+
|
| 68 |
+
# fmt: off
|
| 69 |
+
presets = {
|
| 70 |
+
'web_low': {'subsampling': 2, # "4:2:0"
|
| 71 |
+
'quantization': [
|
| 72 |
+
[20, 16, 25, 39, 50, 46, 62, 68,
|
| 73 |
+
16, 18, 23, 38, 38, 53, 65, 68,
|
| 74 |
+
25, 23, 31, 38, 53, 65, 68, 68,
|
| 75 |
+
39, 38, 38, 53, 65, 68, 68, 68,
|
| 76 |
+
50, 38, 53, 65, 68, 68, 68, 68,
|
| 77 |
+
46, 53, 65, 68, 68, 68, 68, 68,
|
| 78 |
+
62, 65, 68, 68, 68, 68, 68, 68,
|
| 79 |
+
68, 68, 68, 68, 68, 68, 68, 68],
|
| 80 |
+
[21, 25, 32, 38, 54, 68, 68, 68,
|
| 81 |
+
25, 28, 24, 38, 54, 68, 68, 68,
|
| 82 |
+
32, 24, 32, 43, 66, 68, 68, 68,
|
| 83 |
+
38, 38, 43, 53, 68, 68, 68, 68,
|
| 84 |
+
54, 54, 66, 68, 68, 68, 68, 68,
|
| 85 |
+
68, 68, 68, 68, 68, 68, 68, 68,
|
| 86 |
+
68, 68, 68, 68, 68, 68, 68, 68,
|
| 87 |
+
68, 68, 68, 68, 68, 68, 68, 68]
|
| 88 |
+
]},
|
| 89 |
+
'web_medium': {'subsampling': 2, # "4:2:0"
|
| 90 |
+
'quantization': [
|
| 91 |
+
[16, 11, 11, 16, 23, 27, 31, 30,
|
| 92 |
+
11, 12, 12, 15, 20, 23, 23, 30,
|
| 93 |
+
11, 12, 13, 16, 23, 26, 35, 47,
|
| 94 |
+
16, 15, 16, 23, 26, 37, 47, 64,
|
| 95 |
+
23, 20, 23, 26, 39, 51, 64, 64,
|
| 96 |
+
27, 23, 26, 37, 51, 64, 64, 64,
|
| 97 |
+
31, 23, 35, 47, 64, 64, 64, 64,
|
| 98 |
+
30, 30, 47, 64, 64, 64, 64, 64],
|
| 99 |
+
[17, 15, 17, 21, 20, 26, 38, 48,
|
| 100 |
+
15, 19, 18, 17, 20, 26, 35, 43,
|
| 101 |
+
17, 18, 20, 22, 26, 30, 46, 53,
|
| 102 |
+
21, 17, 22, 28, 30, 39, 53, 64,
|
| 103 |
+
20, 20, 26, 30, 39, 48, 64, 64,
|
| 104 |
+
26, 26, 30, 39, 48, 63, 64, 64,
|
| 105 |
+
38, 35, 46, 53, 64, 64, 64, 64,
|
| 106 |
+
48, 43, 53, 64, 64, 64, 64, 64]
|
| 107 |
+
]},
|
| 108 |
+
'web_high': {'subsampling': 0, # "4:4:4"
|
| 109 |
+
'quantization': [
|
| 110 |
+
[6, 4, 4, 6, 9, 11, 12, 16,
|
| 111 |
+
4, 5, 5, 6, 8, 10, 12, 12,
|
| 112 |
+
4, 5, 5, 6, 10, 12, 14, 19,
|
| 113 |
+
6, 6, 6, 11, 12, 15, 19, 28,
|
| 114 |
+
9, 8, 10, 12, 16, 20, 27, 31,
|
| 115 |
+
11, 10, 12, 15, 20, 27, 31, 31,
|
| 116 |
+
12, 12, 14, 19, 27, 31, 31, 31,
|
| 117 |
+
16, 12, 19, 28, 31, 31, 31, 31],
|
| 118 |
+
[7, 7, 13, 24, 26, 31, 31, 31,
|
| 119 |
+
7, 12, 16, 21, 31, 31, 31, 31,
|
| 120 |
+
13, 16, 17, 31, 31, 31, 31, 31,
|
| 121 |
+
24, 21, 31, 31, 31, 31, 31, 31,
|
| 122 |
+
26, 31, 31, 31, 31, 31, 31, 31,
|
| 123 |
+
31, 31, 31, 31, 31, 31, 31, 31,
|
| 124 |
+
31, 31, 31, 31, 31, 31, 31, 31,
|
| 125 |
+
31, 31, 31, 31, 31, 31, 31, 31]
|
| 126 |
+
]},
|
| 127 |
+
'web_very_high': {'subsampling': 0, # "4:4:4"
|
| 128 |
+
'quantization': [
|
| 129 |
+
[2, 2, 2, 2, 3, 4, 5, 6,
|
| 130 |
+
2, 2, 2, 2, 3, 4, 5, 6,
|
| 131 |
+
2, 2, 2, 2, 4, 5, 7, 9,
|
| 132 |
+
2, 2, 2, 4, 5, 7, 9, 12,
|
| 133 |
+
3, 3, 4, 5, 8, 10, 12, 12,
|
| 134 |
+
4, 4, 5, 7, 10, 12, 12, 12,
|
| 135 |
+
5, 5, 7, 9, 12, 12, 12, 12,
|
| 136 |
+
6, 6, 9, 12, 12, 12, 12, 12],
|
| 137 |
+
[3, 3, 5, 9, 13, 15, 15, 15,
|
| 138 |
+
3, 4, 6, 11, 14, 12, 12, 12,
|
| 139 |
+
5, 6, 9, 14, 12, 12, 12, 12,
|
| 140 |
+
9, 11, 14, 12, 12, 12, 12, 12,
|
| 141 |
+
13, 14, 12, 12, 12, 12, 12, 12,
|
| 142 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 143 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 144 |
+
15, 12, 12, 12, 12, 12, 12, 12]
|
| 145 |
+
]},
|
| 146 |
+
'web_maximum': {'subsampling': 0, # "4:4:4"
|
| 147 |
+
'quantization': [
|
| 148 |
+
[1, 1, 1, 1, 1, 1, 1, 1,
|
| 149 |
+
1, 1, 1, 1, 1, 1, 1, 1,
|
| 150 |
+
1, 1, 1, 1, 1, 1, 1, 2,
|
| 151 |
+
1, 1, 1, 1, 1, 1, 2, 2,
|
| 152 |
+
1, 1, 1, 1, 1, 2, 2, 3,
|
| 153 |
+
1, 1, 1, 1, 2, 2, 3, 3,
|
| 154 |
+
1, 1, 1, 2, 2, 3, 3, 3,
|
| 155 |
+
1, 1, 2, 2, 3, 3, 3, 3],
|
| 156 |
+
[1, 1, 1, 2, 2, 3, 3, 3,
|
| 157 |
+
1, 1, 1, 2, 3, 3, 3, 3,
|
| 158 |
+
1, 1, 1, 3, 3, 3, 3, 3,
|
| 159 |
+
2, 2, 3, 3, 3, 3, 3, 3,
|
| 160 |
+
2, 3, 3, 3, 3, 3, 3, 3,
|
| 161 |
+
3, 3, 3, 3, 3, 3, 3, 3,
|
| 162 |
+
3, 3, 3, 3, 3, 3, 3, 3,
|
| 163 |
+
3, 3, 3, 3, 3, 3, 3, 3]
|
| 164 |
+
]},
|
| 165 |
+
'low': {'subsampling': 2, # "4:2:0"
|
| 166 |
+
'quantization': [
|
| 167 |
+
[18, 14, 14, 21, 30, 35, 34, 17,
|
| 168 |
+
14, 16, 16, 19, 26, 23, 12, 12,
|
| 169 |
+
14, 16, 17, 21, 23, 12, 12, 12,
|
| 170 |
+
21, 19, 21, 23, 12, 12, 12, 12,
|
| 171 |
+
30, 26, 23, 12, 12, 12, 12, 12,
|
| 172 |
+
35, 23, 12, 12, 12, 12, 12, 12,
|
| 173 |
+
34, 12, 12, 12, 12, 12, 12, 12,
|
| 174 |
+
17, 12, 12, 12, 12, 12, 12, 12],
|
| 175 |
+
[20, 19, 22, 27, 20, 20, 17, 17,
|
| 176 |
+
19, 25, 23, 14, 14, 12, 12, 12,
|
| 177 |
+
22, 23, 14, 14, 12, 12, 12, 12,
|
| 178 |
+
27, 14, 14, 12, 12, 12, 12, 12,
|
| 179 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 180 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 181 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 182 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 183 |
+
]},
|
| 184 |
+
'medium': {'subsampling': 2, # "4:2:0"
|
| 185 |
+
'quantization': [
|
| 186 |
+
[12, 8, 8, 12, 17, 21, 24, 17,
|
| 187 |
+
8, 9, 9, 11, 15, 19, 12, 12,
|
| 188 |
+
8, 9, 10, 12, 19, 12, 12, 12,
|
| 189 |
+
12, 11, 12, 21, 12, 12, 12, 12,
|
| 190 |
+
17, 15, 19, 12, 12, 12, 12, 12,
|
| 191 |
+
21, 19, 12, 12, 12, 12, 12, 12,
|
| 192 |
+
24, 12, 12, 12, 12, 12, 12, 12,
|
| 193 |
+
17, 12, 12, 12, 12, 12, 12, 12],
|
| 194 |
+
[13, 11, 13, 16, 20, 20, 17, 17,
|
| 195 |
+
11, 14, 14, 14, 14, 12, 12, 12,
|
| 196 |
+
13, 14, 14, 14, 12, 12, 12, 12,
|
| 197 |
+
16, 14, 14, 12, 12, 12, 12, 12,
|
| 198 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 199 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 200 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 201 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 202 |
+
]},
|
| 203 |
+
'high': {'subsampling': 0, # "4:4:4"
|
| 204 |
+
'quantization': [
|
| 205 |
+
[6, 4, 4, 6, 9, 11, 12, 16,
|
| 206 |
+
4, 5, 5, 6, 8, 10, 12, 12,
|
| 207 |
+
4, 5, 5, 6, 10, 12, 12, 12,
|
| 208 |
+
6, 6, 6, 11, 12, 12, 12, 12,
|
| 209 |
+
9, 8, 10, 12, 12, 12, 12, 12,
|
| 210 |
+
11, 10, 12, 12, 12, 12, 12, 12,
|
| 211 |
+
12, 12, 12, 12, 12, 12, 12, 12,
|
| 212 |
+
16, 12, 12, 12, 12, 12, 12, 12],
|
| 213 |
+
[7, 7, 13, 24, 20, 20, 17, 17,
|
| 214 |
+
7, 12, 16, 14, 14, 12, 12, 12,
|
| 215 |
+
13, 16, 14, 14, 12, 12, 12, 12,
|
| 216 |
+
24, 14, 14, 12, 12, 12, 12, 12,
|
| 217 |
+
20, 14, 12, 12, 12, 12, 12, 12,
|
| 218 |
+
20, 12, 12, 12, 12, 12, 12, 12,
|
| 219 |
+
17, 12, 12, 12, 12, 12, 12, 12,
|
| 220 |
+
17, 12, 12, 12, 12, 12, 12, 12]
|
| 221 |
+
]},
|
| 222 |
+
'maximum': {'subsampling': 0, # "4:4:4"
|
| 223 |
+
'quantization': [
|
| 224 |
+
[2, 2, 2, 2, 3, 4, 5, 6,
|
| 225 |
+
2, 2, 2, 2, 3, 4, 5, 6,
|
| 226 |
+
2, 2, 2, 2, 4, 5, 7, 9,
|
| 227 |
+
2, 2, 2, 4, 5, 7, 9, 12,
|
| 228 |
+
3, 3, 4, 5, 8, 10, 12, 12,
|
| 229 |
+
4, 4, 5, 7, 10, 12, 12, 12,
|
| 230 |
+
5, 5, 7, 9, 12, 12, 12, 12,
|
| 231 |
+
6, 6, 9, 12, 12, 12, 12, 12],
|
| 232 |
+
[3, 3, 5, 9, 13, 15, 15, 15,
|
| 233 |
+
3, 4, 6, 10, 14, 12, 12, 12,
|
| 234 |
+
5, 6, 9, 14, 12, 12, 12, 12,
|
| 235 |
+
9, 10, 14, 12, 12, 12, 12, 12,
|
| 236 |
+
13, 14, 12, 12, 12, 12, 12, 12,
|
| 237 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 238 |
+
15, 12, 12, 12, 12, 12, 12, 12,
|
| 239 |
+
15, 12, 12, 12, 12, 12, 12, 12]
|
| 240 |
+
]},
|
| 241 |
+
}
|
| 242 |
+
# fmt: on
|
.venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# Basic McIdas support for PIL
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 1997-05-05 fl Created (8-bit images only)
|
| 9 |
+
# 2009-03-08 fl Added 16/32-bit support.
|
| 10 |
+
#
|
| 11 |
+
# Thanks to Richard Jones and Craig Swank for specs and samples.
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import struct
|
| 21 |
+
|
| 22 |
+
from . import Image, ImageFile
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _accept(prefix: bytes) -> bool:
|
| 26 |
+
return prefix[:8] == b"\x00\x00\x00\x00\x00\x00\x00\x04"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
##
|
| 30 |
+
# Image plugin for McIdas area images.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class McIdasImageFile(ImageFile.ImageFile):
|
| 34 |
+
format = "MCIDAS"
|
| 35 |
+
format_description = "McIdas area file"
|
| 36 |
+
|
| 37 |
+
def _open(self) -> None:
|
| 38 |
+
# parse area file directory
|
| 39 |
+
assert self.fp is not None
|
| 40 |
+
|
| 41 |
+
s = self.fp.read(256)
|
| 42 |
+
if not _accept(s) or len(s) != 256:
|
| 43 |
+
msg = "not an McIdas area file"
|
| 44 |
+
raise SyntaxError(msg)
|
| 45 |
+
|
| 46 |
+
self.area_descriptor_raw = s
|
| 47 |
+
self.area_descriptor = w = [0] + list(struct.unpack("!64i", s))
|
| 48 |
+
|
| 49 |
+
# get mode
|
| 50 |
+
if w[11] == 1:
|
| 51 |
+
mode = rawmode = "L"
|
| 52 |
+
elif w[11] == 2:
|
| 53 |
+
# FIXME: add memory map support
|
| 54 |
+
mode = "I"
|
| 55 |
+
rawmode = "I;16B"
|
| 56 |
+
elif w[11] == 4:
|
| 57 |
+
# FIXME: add memory map support
|
| 58 |
+
mode = "I"
|
| 59 |
+
rawmode = "I;32B"
|
| 60 |
+
else:
|
| 61 |
+
msg = "unsupported McIdas format"
|
| 62 |
+
raise SyntaxError(msg)
|
| 63 |
+
|
| 64 |
+
self._mode = mode
|
| 65 |
+
self._size = w[10], w[9]
|
| 66 |
+
|
| 67 |
+
offset = w[34] + w[15]
|
| 68 |
+
stride = w[15] + w[10] * w[11] * w[14]
|
| 69 |
+
|
| 70 |
+
self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# --------------------------------------------------------------------
|
| 74 |
+
# registry
|
| 75 |
+
|
| 76 |
+
Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept)
|
| 77 |
+
|
| 78 |
+
# no default extension
|
.venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
.venv/lib/python3.11/site-packages/PIL/PaletteFile.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Python Imaging Library
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# stuff to read simple, teragon-style palette files
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 97-08-23 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 11 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import IO
|
| 18 |
+
|
| 19 |
+
from ._binary import o8
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PaletteFile:
|
| 23 |
+
"""File handler for Teragon-style palette files."""
|
| 24 |
+
|
| 25 |
+
rawmode = "RGB"
|
| 26 |
+
|
| 27 |
+
def __init__(self, fp: IO[bytes]) -> None:
|
| 28 |
+
palette = [o8(i) * 3 for i in range(256)]
|
| 29 |
+
|
| 30 |
+
while True:
|
| 31 |
+
s = fp.readline()
|
| 32 |
+
|
| 33 |
+
if not s:
|
| 34 |
+
break
|
| 35 |
+
if s[: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
|
.venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
|
| 6 |
+
##
|
| 7 |
+
# Image plugin for Palm pixmap images (output only).
|
| 8 |
+
##
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from typing import IO
|
| 12 |
+
|
| 13 |
+
from . import Image, ImageFile
|
| 14 |
+
from ._binary import o8
|
| 15 |
+
from ._binary import o16be as o16b
|
| 16 |
+
|
| 17 |
+
# fmt: off
|
| 18 |
+
_Palm8BitColormapValues = (
|
| 19 |
+
(255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
|
| 20 |
+
(255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
|
| 21 |
+
(255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
|
| 22 |
+
(255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),
|
| 23 |
+
(255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),
|
| 24 |
+
(204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),
|
| 25 |
+
(204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),
|
| 26 |
+
(204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),
|
| 27 |
+
(204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),
|
| 28 |
+
(153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),
|
| 29 |
+
(153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),
|
| 30 |
+
(153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),
|
| 31 |
+
(153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),
|
| 32 |
+
(153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),
|
| 33 |
+
(102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),
|
| 34 |
+
(102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
|
| 35 |
+
(102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
|
| 36 |
+
(102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
|
| 37 |
+
(51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
|
| 38 |
+
(51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
|
| 39 |
+
(51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
|
| 40 |
+
(51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
|
| 41 |
+
(51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
|
| 42 |
+
(0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
|
| 43 |
+
(0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
|
| 44 |
+
(0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
|
| 45 |
+
(0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
|
| 46 |
+
(255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
|
| 47 |
+
(255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
|
| 48 |
+
(255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
|
| 49 |
+
(255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),
|
| 50 |
+
(255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),
|
| 51 |
+
(204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),
|
| 52 |
+
(204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),
|
| 53 |
+
(204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),
|
| 54 |
+
(204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),
|
| 55 |
+
(153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),
|
| 56 |
+
(153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),
|
| 57 |
+
(153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),
|
| 58 |
+
(153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),
|
| 59 |
+
(153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),
|
| 60 |
+
(102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),
|
| 61 |
+
(102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
|
| 62 |
+
(102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
|
| 63 |
+
(102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
|
| 64 |
+
(51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
|
| 65 |
+
(51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
|
| 66 |
+
(51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
|
| 67 |
+
(51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
|
| 68 |
+
(51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
|
| 69 |
+
(0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
|
| 70 |
+
(0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
|
| 71 |
+
(0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
|
| 72 |
+
(0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
|
| 73 |
+
(34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
|
| 74 |
+
(136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
|
| 75 |
+
(238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
|
| 76 |
+
(0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
|
| 77 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 78 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 79 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 80 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 81 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
|
| 82 |
+
(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
|
| 83 |
+
# fmt: on
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# so build a prototype image to be used for palette resampling
|
| 87 |
+
def build_prototype_image() -> Image.Image:
|
| 88 |
+
image = Image.new("L", (1, len(_Palm8BitColormapValues)))
|
| 89 |
+
image.putdata(list(range(len(_Palm8BitColormapValues))))
|
| 90 |
+
palettedata: tuple[int, ...] = ()
|
| 91 |
+
for colormapValue in _Palm8BitColormapValues:
|
| 92 |
+
palettedata += colormapValue
|
| 93 |
+
palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))
|
| 94 |
+
image.putpalette(palettedata)
|
| 95 |
+
return image
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
Palm8BitColormapImage = build_prototype_image()
|
| 99 |
+
|
| 100 |
+
# OK, we now have in Palm8BitColormapImage,
|
| 101 |
+
# a "P"-mode image with the right palette
|
| 102 |
+
#
|
| 103 |
+
# --------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
|
| 106 |
+
|
| 107 |
+
_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
#
|
| 111 |
+
# --------------------------------------------------------------------
|
| 112 |
+
|
| 113 |
+
##
|
| 114 |
+
# (Internal) Image save plugin for the Palm format.
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 118 |
+
if im.mode == "P":
|
| 119 |
+
# 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")
|
.venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
.venv/lib/python3.11/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")
|
.venv/lib/python3.11/site-packages/PIL/PdfParser.py
ADDED
|
@@ -0,0 +1,1003 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import calendar
|
| 4 |
+
import codecs
|
| 5 |
+
import collections
|
| 6 |
+
import mmap
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
import zlib
|
| 11 |
+
from typing import TYPE_CHECKING, Any, List, NamedTuple, Union
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set
|
| 15 |
+
# on page 656
|
| 16 |
+
def encode_text(s: str) -> bytes:
|
| 17 |
+
return codecs.BOM_UTF16_BE + s.encode("utf_16_be")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
PDFDocEncoding = {
|
| 21 |
+
0x16: "\u0017",
|
| 22 |
+
0x18: "\u02D8",
|
| 23 |
+
0x19: "\u02C7",
|
| 24 |
+
0x1A: "\u02C6",
|
| 25 |
+
0x1B: "\u02D9",
|
| 26 |
+
0x1C: "\u02DD",
|
| 27 |
+
0x1D: "\u02DB",
|
| 28 |
+
0x1E: "\u02DA",
|
| 29 |
+
0x1F: "\u02DC",
|
| 30 |
+
0x80: "\u2022",
|
| 31 |
+
0x81: "\u2020",
|
| 32 |
+
0x82: "\u2021",
|
| 33 |
+
0x83: "\u2026",
|
| 34 |
+
0x84: "\u2014",
|
| 35 |
+
0x85: "\u2013",
|
| 36 |
+
0x86: "\u0192",
|
| 37 |
+
0x87: "\u2044",
|
| 38 |
+
0x88: "\u2039",
|
| 39 |
+
0x89: "\u203A",
|
| 40 |
+
0x8A: "\u2212",
|
| 41 |
+
0x8B: "\u2030",
|
| 42 |
+
0x8C: "\u201E",
|
| 43 |
+
0x8D: "\u201C",
|
| 44 |
+
0x8E: "\u201D",
|
| 45 |
+
0x8F: "\u2018",
|
| 46 |
+
0x90: "\u2019",
|
| 47 |
+
0x91: "\u201A",
|
| 48 |
+
0x92: "\u2122",
|
| 49 |
+
0x93: "\uFB01",
|
| 50 |
+
0x94: "\uFB02",
|
| 51 |
+
0x95: "\u0141",
|
| 52 |
+
0x96: "\u0152",
|
| 53 |
+
0x97: "\u0160",
|
| 54 |
+
0x98: "\u0178",
|
| 55 |
+
0x99: "\u017D",
|
| 56 |
+
0x9A: "\u0131",
|
| 57 |
+
0x9B: "\u0142",
|
| 58 |
+
0x9C: "\u0153",
|
| 59 |
+
0x9D: "\u0161",
|
| 60 |
+
0x9E: "\u017E",
|
| 61 |
+
0xA0: "\u20AC",
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def decode_text(b):
|
| 66 |
+
if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:
|
| 67 |
+
return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be")
|
| 68 |
+
else:
|
| 69 |
+
return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class PdfFormatError(RuntimeError):
|
| 73 |
+
"""An error that probably indicates a syntactic or semantic error in the
|
| 74 |
+
PDF file structure"""
|
| 75 |
+
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def check_format_condition(condition: bool, error_message: str) -> None:
|
| 80 |
+
if not condition:
|
| 81 |
+
raise PdfFormatError(error_message)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class IndirectReferenceTuple(NamedTuple):
|
| 85 |
+
object_id: int
|
| 86 |
+
generation: int
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class IndirectReference(IndirectReferenceTuple):
|
| 90 |
+
def __str__(self) -> str:
|
| 91 |
+
return f"{self.object_id} {self.generation} R"
|
| 92 |
+
|
| 93 |
+
def __bytes__(self) -> bytes:
|
| 94 |
+
return self.__str__().encode("us-ascii")
|
| 95 |
+
|
| 96 |
+
def __eq__(self, other: object) -> bool:
|
| 97 |
+
if self.__class__ is not other.__class__:
|
| 98 |
+
return False
|
| 99 |
+
assert isinstance(other, IndirectReference)
|
| 100 |
+
return other.object_id == self.object_id and other.generation == self.generation
|
| 101 |
+
|
| 102 |
+
def __ne__(self, other):
|
| 103 |
+
return not (self == other)
|
| 104 |
+
|
| 105 |
+
def __hash__(self) -> int:
|
| 106 |
+
return hash((self.object_id, self.generation))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class IndirectObjectDef(IndirectReference):
|
| 110 |
+
def __str__(self) -> str:
|
| 111 |
+
return f"{self.object_id} {self.generation} obj"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class XrefTable:
|
| 115 |
+
def __init__(self):
|
| 116 |
+
self.existing_entries = {} # object ID => (offset, generation)
|
| 117 |
+
self.new_entries = {} # object ID => (offset, generation)
|
| 118 |
+
self.deleted_entries = {0: 65536} # object ID => generation
|
| 119 |
+
self.reading_finished = False
|
| 120 |
+
|
| 121 |
+
def __setitem__(self, key, value):
|
| 122 |
+
if self.reading_finished:
|
| 123 |
+
self.new_entries[key] = value
|
| 124 |
+
else:
|
| 125 |
+
self.existing_entries[key] = value
|
| 126 |
+
if key in self.deleted_entries:
|
| 127 |
+
del self.deleted_entries[key]
|
| 128 |
+
|
| 129 |
+
def __getitem__(self, key):
|
| 130 |
+
try:
|
| 131 |
+
return self.new_entries[key]
|
| 132 |
+
except KeyError:
|
| 133 |
+
return self.existing_entries[key]
|
| 134 |
+
|
| 135 |
+
def __delitem__(self, key):
|
| 136 |
+
if key in self.new_entries:
|
| 137 |
+
generation = self.new_entries[key][1] + 1
|
| 138 |
+
del self.new_entries[key]
|
| 139 |
+
self.deleted_entries[key] = generation
|
| 140 |
+
elif key in self.existing_entries:
|
| 141 |
+
generation = self.existing_entries[key][1] + 1
|
| 142 |
+
self.deleted_entries[key] = generation
|
| 143 |
+
elif key in self.deleted_entries:
|
| 144 |
+
generation = self.deleted_entries[key]
|
| 145 |
+
else:
|
| 146 |
+
msg = f"object ID {key} cannot be deleted because it doesn't exist"
|
| 147 |
+
raise IndexError(msg)
|
| 148 |
+
|
| 149 |
+
def __contains__(self, key):
|
| 150 |
+
return key in self.existing_entries or key in self.new_entries
|
| 151 |
+
|
| 152 |
+
def __len__(self) -> int:
|
| 153 |
+
return len(
|
| 154 |
+
set(self.existing_entries.keys())
|
| 155 |
+
| set(self.new_entries.keys())
|
| 156 |
+
| set(self.deleted_entries.keys())
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
def keys(self):
|
| 160 |
+
return (
|
| 161 |
+
set(self.existing_entries.keys()) - set(self.deleted_entries.keys())
|
| 162 |
+
) | set(self.new_entries.keys())
|
| 163 |
+
|
| 164 |
+
def write(self, f):
|
| 165 |
+
keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys()))
|
| 166 |
+
deleted_keys = sorted(set(self.deleted_entries.keys()))
|
| 167 |
+
startxref = f.tell()
|
| 168 |
+
f.write(b"xref\n")
|
| 169 |
+
while keys:
|
| 170 |
+
# find a contiguous sequence of object IDs
|
| 171 |
+
prev = None
|
| 172 |
+
for index, key in enumerate(keys):
|
| 173 |
+
if prev is None or prev + 1 == key:
|
| 174 |
+
prev = key
|
| 175 |
+
else:
|
| 176 |
+
contiguous_keys = keys[:index]
|
| 177 |
+
keys = keys[index:]
|
| 178 |
+
break
|
| 179 |
+
else:
|
| 180 |
+
contiguous_keys = keys
|
| 181 |
+
keys = None
|
| 182 |
+
f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys)))
|
| 183 |
+
for object_id in contiguous_keys:
|
| 184 |
+
if object_id in self.new_entries:
|
| 185 |
+
f.write(b"%010d %05d n \n" % self.new_entries[object_id])
|
| 186 |
+
else:
|
| 187 |
+
this_deleted_object_id = deleted_keys.pop(0)
|
| 188 |
+
check_format_condition(
|
| 189 |
+
object_id == this_deleted_object_id,
|
| 190 |
+
f"expected the next deleted object ID to be {object_id}, "
|
| 191 |
+
f"instead found {this_deleted_object_id}",
|
| 192 |
+
)
|
| 193 |
+
try:
|
| 194 |
+
next_in_linked_list = deleted_keys[0]
|
| 195 |
+
except IndexError:
|
| 196 |
+
next_in_linked_list = 0
|
| 197 |
+
f.write(
|
| 198 |
+
b"%010d %05d f \n"
|
| 199 |
+
% (next_in_linked_list, self.deleted_entries[object_id])
|
| 200 |
+
)
|
| 201 |
+
return startxref
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class PdfName:
|
| 205 |
+
def __init__(self, name):
|
| 206 |
+
if isinstance(name, PdfName):
|
| 207 |
+
self.name = name.name
|
| 208 |
+
elif isinstance(name, bytes):
|
| 209 |
+
self.name = name
|
| 210 |
+
else:
|
| 211 |
+
self.name = name.encode("us-ascii")
|
| 212 |
+
|
| 213 |
+
def name_as_str(self) -> str:
|
| 214 |
+
return self.name.decode("us-ascii")
|
| 215 |
+
|
| 216 |
+
def __eq__(self, other):
|
| 217 |
+
return (
|
| 218 |
+
isinstance(other, PdfName) and other.name == self.name
|
| 219 |
+
) or other == self.name
|
| 220 |
+
|
| 221 |
+
def __hash__(self) -> int:
|
| 222 |
+
return hash(self.name)
|
| 223 |
+
|
| 224 |
+
def __repr__(self) -> str:
|
| 225 |
+
return f"{self.__class__.__name__}({repr(self.name)})"
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def from_pdf_stream(cls, data):
|
| 229 |
+
return cls(PdfParser.interpret_name(data))
|
| 230 |
+
|
| 231 |
+
allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"}
|
| 232 |
+
|
| 233 |
+
def __bytes__(self) -> bytes:
|
| 234 |
+
result = bytearray(b"/")
|
| 235 |
+
for b in self.name:
|
| 236 |
+
if b in self.allowed_chars:
|
| 237 |
+
result.append(b)
|
| 238 |
+
else:
|
| 239 |
+
result.extend(b"#%02X" % b)
|
| 240 |
+
return bytes(result)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class PdfArray(List[Any]):
|
| 244 |
+
def __bytes__(self) -> bytes:
|
| 245 |
+
return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]"
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if TYPE_CHECKING:
|
| 249 |
+
_DictBase = collections.UserDict[Union[str, bytes], Any]
|
| 250 |
+
else:
|
| 251 |
+
_DictBase = collections.UserDict
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class PdfDict(_DictBase):
|
| 255 |
+
def __setattr__(self, key, value):
|
| 256 |
+
if key == "data":
|
| 257 |
+
collections.UserDict.__setattr__(self, key, value)
|
| 258 |
+
else:
|
| 259 |
+
self[key.encode("us-ascii")] = value
|
| 260 |
+
|
| 261 |
+
def __getattr__(self, key):
|
| 262 |
+
try:
|
| 263 |
+
value = self[key.encode("us-ascii")]
|
| 264 |
+
except KeyError as e:
|
| 265 |
+
raise AttributeError(key) from e
|
| 266 |
+
if isinstance(value, bytes):
|
| 267 |
+
value = decode_text(value)
|
| 268 |
+
if key.endswith("Date"):
|
| 269 |
+
if value.startswith("D:"):
|
| 270 |
+
value = value[2:]
|
| 271 |
+
|
| 272 |
+
relationship = "Z"
|
| 273 |
+
if len(value) > 17:
|
| 274 |
+
relationship = value[14]
|
| 275 |
+
offset = int(value[15:17]) * 60
|
| 276 |
+
if len(value) > 20:
|
| 277 |
+
offset += int(value[18:20])
|
| 278 |
+
|
| 279 |
+
format = "%Y%m%d%H%M%S"[: len(value) - 2]
|
| 280 |
+
value = time.strptime(value[: len(format) + 2], format)
|
| 281 |
+
if relationship in ["+", "-"]:
|
| 282 |
+
offset *= 60
|
| 283 |
+
if relationship == "+":
|
| 284 |
+
offset *= -1
|
| 285 |
+
value = time.gmtime(calendar.timegm(value) + offset)
|
| 286 |
+
return value
|
| 287 |
+
|
| 288 |
+
def __bytes__(self) -> bytes:
|
| 289 |
+
out = bytearray(b"<<")
|
| 290 |
+
for key, value in self.items():
|
| 291 |
+
if value is None:
|
| 292 |
+
continue
|
| 293 |
+
value = pdf_repr(value)
|
| 294 |
+
out.extend(b"\n")
|
| 295 |
+
out.extend(bytes(PdfName(key)))
|
| 296 |
+
out.extend(b" ")
|
| 297 |
+
out.extend(value)
|
| 298 |
+
out.extend(b"\n>>")
|
| 299 |
+
return bytes(out)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class PdfBinary:
|
| 303 |
+
def __init__(self, data):
|
| 304 |
+
self.data = data
|
| 305 |
+
|
| 306 |
+
def __bytes__(self) -> bytes:
|
| 307 |
+
return b"<%s>" % b"".join(b"%02X" % b for b in self.data)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class PdfStream:
|
| 311 |
+
def __init__(self, dictionary, buf):
|
| 312 |
+
self.dictionary = dictionary
|
| 313 |
+
self.buf = buf
|
| 314 |
+
|
| 315 |
+
def decode(self):
|
| 316 |
+
try:
|
| 317 |
+
filter = self.dictionary.Filter
|
| 318 |
+
except AttributeError:
|
| 319 |
+
return self.buf
|
| 320 |
+
if filter == b"FlateDecode":
|
| 321 |
+
try:
|
| 322 |
+
expected_length = self.dictionary.DL
|
| 323 |
+
except AttributeError:
|
| 324 |
+
expected_length = self.dictionary.Length
|
| 325 |
+
return zlib.decompress(self.buf, bufsize=int(expected_length))
|
| 326 |
+
else:
|
| 327 |
+
msg = f"stream filter {repr(self.dictionary.Filter)} unknown/unsupported"
|
| 328 |
+
raise NotImplementedError(msg)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def pdf_repr(x):
|
| 332 |
+
if x is True:
|
| 333 |
+
return b"true"
|
| 334 |
+
elif x is False:
|
| 335 |
+
return b"false"
|
| 336 |
+
elif x is None:
|
| 337 |
+
return b"null"
|
| 338 |
+
elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):
|
| 339 |
+
return bytes(x)
|
| 340 |
+
elif isinstance(x, (int, float)):
|
| 341 |
+
return str(x).encode("us-ascii")
|
| 342 |
+
elif isinstance(x, time.struct_time):
|
| 343 |
+
return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"
|
| 344 |
+
elif isinstance(x, dict):
|
| 345 |
+
return bytes(PdfDict(x))
|
| 346 |
+
elif isinstance(x, list):
|
| 347 |
+
return bytes(PdfArray(x))
|
| 348 |
+
elif isinstance(x, str):
|
| 349 |
+
return pdf_repr(encode_text(x))
|
| 350 |
+
elif isinstance(x, bytes):
|
| 351 |
+
# XXX escape more chars? handle binary garbage
|
| 352 |
+
x = x.replace(b"\\", b"\\\\")
|
| 353 |
+
x = x.replace(b"(", b"\\(")
|
| 354 |
+
x = x.replace(b")", b"\\)")
|
| 355 |
+
return b"(" + x + b")"
|
| 356 |
+
else:
|
| 357 |
+
return bytes(x)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class PdfParser:
|
| 361 |
+
"""Based on
|
| 362 |
+
https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
|
| 363 |
+
Supports PDF up to 1.4
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
def __init__(self, filename=None, f=None, buf=None, start_offset=0, mode="rb"):
|
| 367 |
+
if buf and f:
|
| 368 |
+
msg = "specify buf or f or filename, but not both buf and f"
|
| 369 |
+
raise RuntimeError(msg)
|
| 370 |
+
self.filename = filename
|
| 371 |
+
self.buf = buf
|
| 372 |
+
self.f = f
|
| 373 |
+
self.start_offset = start_offset
|
| 374 |
+
self.should_close_buf = False
|
| 375 |
+
self.should_close_file = False
|
| 376 |
+
if filename is not None and f is None:
|
| 377 |
+
self.f = f = open(filename, mode)
|
| 378 |
+
self.should_close_file = True
|
| 379 |
+
if f is not None:
|
| 380 |
+
self.buf = buf = self.get_buf_from_file(f)
|
| 381 |
+
self.should_close_buf = True
|
| 382 |
+
if not filename and hasattr(f, "name"):
|
| 383 |
+
self.filename = f.name
|
| 384 |
+
self.cached_objects = {}
|
| 385 |
+
if buf:
|
| 386 |
+
self.read_pdf_info()
|
| 387 |
+
else:
|
| 388 |
+
self.file_size_total = self.file_size_this = 0
|
| 389 |
+
self.root = PdfDict()
|
| 390 |
+
self.root_ref = None
|
| 391 |
+
self.info = PdfDict()
|
| 392 |
+
self.info_ref = None
|
| 393 |
+
self.page_tree_root = {}
|
| 394 |
+
self.pages = []
|
| 395 |
+
self.orig_pages = []
|
| 396 |
+
self.pages_ref = None
|
| 397 |
+
self.last_xref_section_offset = None
|
| 398 |
+
self.trailer_dict = {}
|
| 399 |
+
self.xref_table = XrefTable()
|
| 400 |
+
self.xref_table.reading_finished = True
|
| 401 |
+
if f:
|
| 402 |
+
self.seek_end()
|
| 403 |
+
|
| 404 |
+
def __enter__(self) -> PdfParser:
|
| 405 |
+
return self
|
| 406 |
+
|
| 407 |
+
def __exit__(self, *args: object) -> None:
|
| 408 |
+
self.close()
|
| 409 |
+
|
| 410 |
+
def start_writing(self) -> None:
|
| 411 |
+
self.close_buf()
|
| 412 |
+
self.seek_end()
|
| 413 |
+
|
| 414 |
+
def close_buf(self) -> None:
|
| 415 |
+
try:
|
| 416 |
+
self.buf.close()
|
| 417 |
+
except AttributeError:
|
| 418 |
+
pass
|
| 419 |
+
self.buf = None
|
| 420 |
+
|
| 421 |
+
def close(self) -> None:
|
| 422 |
+
if self.should_close_buf:
|
| 423 |
+
self.close_buf()
|
| 424 |
+
if self.f is not None and self.should_close_file:
|
| 425 |
+
self.f.close()
|
| 426 |
+
self.f = None
|
| 427 |
+
|
| 428 |
+
def seek_end(self) -> None:
|
| 429 |
+
self.f.seek(0, os.SEEK_END)
|
| 430 |
+
|
| 431 |
+
def write_header(self) -> None:
|
| 432 |
+
self.f.write(b"%PDF-1.4\n")
|
| 433 |
+
|
| 434 |
+
def write_comment(self, s):
|
| 435 |
+
self.f.write(f"% {s}\n".encode())
|
| 436 |
+
|
| 437 |
+
def write_catalog(self) -> IndirectReference:
|
| 438 |
+
self.del_root()
|
| 439 |
+
self.root_ref = self.next_object_id(self.f.tell())
|
| 440 |
+
self.pages_ref = self.next_object_id(0)
|
| 441 |
+
self.rewrite_pages()
|
| 442 |
+
self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref)
|
| 443 |
+
self.write_obj(
|
| 444 |
+
self.pages_ref,
|
| 445 |
+
Type=PdfName(b"Pages"),
|
| 446 |
+
Count=len(self.pages),
|
| 447 |
+
Kids=self.pages,
|
| 448 |
+
)
|
| 449 |
+
return self.root_ref
|
| 450 |
+
|
| 451 |
+
def rewrite_pages(self) -> None:
|
| 452 |
+
pages_tree_nodes_to_delete = []
|
| 453 |
+
for i, page_ref in enumerate(self.orig_pages):
|
| 454 |
+
page_info = self.cached_objects[page_ref]
|
| 455 |
+
del self.xref_table[page_ref.object_id]
|
| 456 |
+
pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")])
|
| 457 |
+
if page_ref not in self.pages:
|
| 458 |
+
# the page has been deleted
|
| 459 |
+
continue
|
| 460 |
+
# make dict keys into strings for passing to write_page
|
| 461 |
+
stringified_page_info = {}
|
| 462 |
+
for key, value in page_info.items():
|
| 463 |
+
# key should be a PdfName
|
| 464 |
+
stringified_page_info[key.name_as_str()] = value
|
| 465 |
+
stringified_page_info["Parent"] = self.pages_ref
|
| 466 |
+
new_page_ref = self.write_page(None, **stringified_page_info)
|
| 467 |
+
for j, cur_page_ref in enumerate(self.pages):
|
| 468 |
+
if cur_page_ref == page_ref:
|
| 469 |
+
# replace the page reference with the new one
|
| 470 |
+
self.pages[j] = new_page_ref
|
| 471 |
+
# delete redundant Pages tree nodes from xref table
|
| 472 |
+
for pages_tree_node_ref in pages_tree_nodes_to_delete:
|
| 473 |
+
while pages_tree_node_ref:
|
| 474 |
+
pages_tree_node = self.cached_objects[pages_tree_node_ref]
|
| 475 |
+
if pages_tree_node_ref.object_id in self.xref_table:
|
| 476 |
+
del self.xref_table[pages_tree_node_ref.object_id]
|
| 477 |
+
pages_tree_node_ref = pages_tree_node.get(b"Parent", None)
|
| 478 |
+
self.orig_pages = []
|
| 479 |
+
|
| 480 |
+
def write_xref_and_trailer(self, new_root_ref=None):
|
| 481 |
+
if new_root_ref:
|
| 482 |
+
self.del_root()
|
| 483 |
+
self.root_ref = new_root_ref
|
| 484 |
+
if self.info:
|
| 485 |
+
self.info_ref = self.write_obj(None, self.info)
|
| 486 |
+
start_xref = self.xref_table.write(self.f)
|
| 487 |
+
num_entries = len(self.xref_table)
|
| 488 |
+
trailer_dict = {b"Root": self.root_ref, b"Size": num_entries}
|
| 489 |
+
if self.last_xref_section_offset is not None:
|
| 490 |
+
trailer_dict[b"Prev"] = self.last_xref_section_offset
|
| 491 |
+
if self.info:
|
| 492 |
+
trailer_dict[b"Info"] = self.info_ref
|
| 493 |
+
self.last_xref_section_offset = start_xref
|
| 494 |
+
self.f.write(
|
| 495 |
+
b"trailer\n"
|
| 496 |
+
+ bytes(PdfDict(trailer_dict))
|
| 497 |
+
+ b"\nstartxref\n%d\n%%%%EOF" % start_xref
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
def write_page(self, ref, *objs, **dict_obj):
|
| 501 |
+
if isinstance(ref, int):
|
| 502 |
+
ref = self.pages[ref]
|
| 503 |
+
if "Type" not in dict_obj:
|
| 504 |
+
dict_obj["Type"] = PdfName(b"Page")
|
| 505 |
+
if "Parent" not in dict_obj:
|
| 506 |
+
dict_obj["Parent"] = self.pages_ref
|
| 507 |
+
return self.write_obj(ref, *objs, **dict_obj)
|
| 508 |
+
|
| 509 |
+
def write_obj(self, ref, *objs, **dict_obj):
|
| 510 |
+
f = self.f
|
| 511 |
+
if ref is None:
|
| 512 |
+
ref = self.next_object_id(f.tell())
|
| 513 |
+
else:
|
| 514 |
+
self.xref_table[ref.object_id] = (f.tell(), ref.generation)
|
| 515 |
+
f.write(bytes(IndirectObjectDef(*ref)))
|
| 516 |
+
stream = dict_obj.pop("stream", None)
|
| 517 |
+
if stream is not None:
|
| 518 |
+
dict_obj["Length"] = len(stream)
|
| 519 |
+
if dict_obj:
|
| 520 |
+
f.write(pdf_repr(dict_obj))
|
| 521 |
+
for obj in objs:
|
| 522 |
+
f.write(pdf_repr(obj))
|
| 523 |
+
if stream is not None:
|
| 524 |
+
f.write(b"stream\n")
|
| 525 |
+
f.write(stream)
|
| 526 |
+
f.write(b"\nendstream\n")
|
| 527 |
+
f.write(b"endobj\n")
|
| 528 |
+
return ref
|
| 529 |
+
|
| 530 |
+
def del_root(self) -> None:
|
| 531 |
+
if self.root_ref is None:
|
| 532 |
+
return
|
| 533 |
+
del self.xref_table[self.root_ref.object_id]
|
| 534 |
+
del self.xref_table[self.root[b"Pages"].object_id]
|
| 535 |
+
|
| 536 |
+
@staticmethod
|
| 537 |
+
def get_buf_from_file(f):
|
| 538 |
+
if hasattr(f, "getbuffer"):
|
| 539 |
+
return f.getbuffer()
|
| 540 |
+
elif hasattr(f, "getvalue"):
|
| 541 |
+
return f.getvalue()
|
| 542 |
+
else:
|
| 543 |
+
try:
|
| 544 |
+
return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
|
| 545 |
+
except ValueError: # cannot mmap an empty file
|
| 546 |
+
return b""
|
| 547 |
+
|
| 548 |
+
def read_pdf_info(self) -> None:
|
| 549 |
+
self.file_size_total = len(self.buf)
|
| 550 |
+
self.file_size_this = self.file_size_total - self.start_offset
|
| 551 |
+
self.read_trailer()
|
| 552 |
+
self.root_ref = self.trailer_dict[b"Root"]
|
| 553 |
+
self.info_ref = self.trailer_dict.get(b"Info", None)
|
| 554 |
+
self.root = PdfDict(self.read_indirect(self.root_ref))
|
| 555 |
+
if self.info_ref is None:
|
| 556 |
+
self.info = PdfDict()
|
| 557 |
+
else:
|
| 558 |
+
self.info = PdfDict(self.read_indirect(self.info_ref))
|
| 559 |
+
check_format_condition(b"Type" in self.root, "/Type missing in Root")
|
| 560 |
+
check_format_condition(
|
| 561 |
+
self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog"
|
| 562 |
+
)
|
| 563 |
+
check_format_condition(b"Pages" in self.root, "/Pages missing in Root")
|
| 564 |
+
check_format_condition(
|
| 565 |
+
isinstance(self.root[b"Pages"], IndirectReference),
|
| 566 |
+
"/Pages in Root is not an indirect reference",
|
| 567 |
+
)
|
| 568 |
+
self.pages_ref = self.root[b"Pages"]
|
| 569 |
+
self.page_tree_root = self.read_indirect(self.pages_ref)
|
| 570 |
+
self.pages = self.linearize_page_tree(self.page_tree_root)
|
| 571 |
+
# save the original list of page references
|
| 572 |
+
# in case the user modifies, adds or deletes some pages
|
| 573 |
+
# and we need to rewrite the pages and their list
|
| 574 |
+
self.orig_pages = self.pages[:]
|
| 575 |
+
|
| 576 |
+
def next_object_id(self, offset=None):
|
| 577 |
+
try:
|
| 578 |
+
# TODO: support reuse of deleted objects
|
| 579 |
+
reference = IndirectReference(max(self.xref_table.keys()) + 1, 0)
|
| 580 |
+
except ValueError:
|
| 581 |
+
reference = IndirectReference(1, 0)
|
| 582 |
+
if offset is not None:
|
| 583 |
+
self.xref_table[reference.object_id] = (offset, 0)
|
| 584 |
+
return reference
|
| 585 |
+
|
| 586 |
+
delimiter = rb"[][()<>{}/%]"
|
| 587 |
+
delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]"
|
| 588 |
+
whitespace = rb"[\000\011\012\014\015\040]"
|
| 589 |
+
whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]"
|
| 590 |
+
whitespace_optional = whitespace + b"*"
|
| 591 |
+
whitespace_mandatory = whitespace + b"+"
|
| 592 |
+
# No "\012" aka "\n" or "\015" aka "\r":
|
| 593 |
+
whitespace_optional_no_nl = rb"[\000\011\014\040]*"
|
| 594 |
+
newline_only = rb"[\r\n]+"
|
| 595 |
+
newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl
|
| 596 |
+
re_trailer_end = re.compile(
|
| 597 |
+
whitespace_mandatory
|
| 598 |
+
+ rb"trailer"
|
| 599 |
+
+ whitespace_optional
|
| 600 |
+
+ rb"<<(.*>>)"
|
| 601 |
+
+ newline
|
| 602 |
+
+ rb"startxref"
|
| 603 |
+
+ newline
|
| 604 |
+
+ rb"([0-9]+)"
|
| 605 |
+
+ newline
|
| 606 |
+
+ rb"%%EOF"
|
| 607 |
+
+ whitespace_optional
|
| 608 |
+
+ rb"$",
|
| 609 |
+
re.DOTALL,
|
| 610 |
+
)
|
| 611 |
+
re_trailer_prev = re.compile(
|
| 612 |
+
whitespace_optional
|
| 613 |
+
+ rb"trailer"
|
| 614 |
+
+ whitespace_optional
|
| 615 |
+
+ rb"<<(.*?>>)"
|
| 616 |
+
+ newline
|
| 617 |
+
+ rb"startxref"
|
| 618 |
+
+ newline
|
| 619 |
+
+ rb"([0-9]+)"
|
| 620 |
+
+ newline
|
| 621 |
+
+ rb"%%EOF"
|
| 622 |
+
+ whitespace_optional,
|
| 623 |
+
re.DOTALL,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
def read_trailer(self):
|
| 627 |
+
search_start_offset = len(self.buf) - 16384
|
| 628 |
+
if search_start_offset < self.start_offset:
|
| 629 |
+
search_start_offset = self.start_offset
|
| 630 |
+
m = self.re_trailer_end.search(self.buf, search_start_offset)
|
| 631 |
+
check_format_condition(m, "trailer end not found")
|
| 632 |
+
# make sure we found the LAST trailer
|
| 633 |
+
last_match = m
|
| 634 |
+
while m:
|
| 635 |
+
last_match = m
|
| 636 |
+
m = self.re_trailer_end.search(self.buf, m.start() + 16)
|
| 637 |
+
if not m:
|
| 638 |
+
m = last_match
|
| 639 |
+
trailer_data = m.group(1)
|
| 640 |
+
self.last_xref_section_offset = int(m.group(2))
|
| 641 |
+
self.trailer_dict = self.interpret_trailer(trailer_data)
|
| 642 |
+
self.xref_table = XrefTable()
|
| 643 |
+
self.read_xref_table(xref_section_offset=self.last_xref_section_offset)
|
| 644 |
+
if b"Prev" in self.trailer_dict:
|
| 645 |
+
self.read_prev_trailer(self.trailer_dict[b"Prev"])
|
| 646 |
+
|
| 647 |
+
def read_prev_trailer(self, xref_section_offset):
|
| 648 |
+
trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)
|
| 649 |
+
m = self.re_trailer_prev.search(
|
| 650 |
+
self.buf[trailer_offset : trailer_offset + 16384]
|
| 651 |
+
)
|
| 652 |
+
check_format_condition(m, "previous trailer not found")
|
| 653 |
+
trailer_data = m.group(1)
|
| 654 |
+
check_format_condition(
|
| 655 |
+
int(m.group(2)) == xref_section_offset,
|
| 656 |
+
"xref section offset in previous trailer doesn't match what was expected",
|
| 657 |
+
)
|
| 658 |
+
trailer_dict = self.interpret_trailer(trailer_data)
|
| 659 |
+
if b"Prev" in trailer_dict:
|
| 660 |
+
self.read_prev_trailer(trailer_dict[b"Prev"])
|
| 661 |
+
|
| 662 |
+
re_whitespace_optional = re.compile(whitespace_optional)
|
| 663 |
+
re_name = re.compile(
|
| 664 |
+
whitespace_optional
|
| 665 |
+
+ rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?="
|
| 666 |
+
+ delimiter_or_ws
|
| 667 |
+
+ rb")"
|
| 668 |
+
)
|
| 669 |
+
re_dict_start = re.compile(whitespace_optional + rb"<<")
|
| 670 |
+
re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional)
|
| 671 |
+
|
| 672 |
+
@classmethod
|
| 673 |
+
def interpret_trailer(cls, trailer_data):
|
| 674 |
+
trailer = {}
|
| 675 |
+
offset = 0
|
| 676 |
+
while True:
|
| 677 |
+
m = cls.re_name.match(trailer_data, offset)
|
| 678 |
+
if not m:
|
| 679 |
+
m = cls.re_dict_end.match(trailer_data, offset)
|
| 680 |
+
check_format_condition(
|
| 681 |
+
m and m.end() == len(trailer_data),
|
| 682 |
+
"name not found in trailer, remaining data: "
|
| 683 |
+
+ repr(trailer_data[offset:]),
|
| 684 |
+
)
|
| 685 |
+
break
|
| 686 |
+
key = cls.interpret_name(m.group(1))
|
| 687 |
+
value, offset = cls.get_value(trailer_data, m.end())
|
| 688 |
+
trailer[key] = value
|
| 689 |
+
check_format_condition(
|
| 690 |
+
b"Size" in trailer and isinstance(trailer[b"Size"], int),
|
| 691 |
+
"/Size not in trailer or not an integer",
|
| 692 |
+
)
|
| 693 |
+
check_format_condition(
|
| 694 |
+
b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference),
|
| 695 |
+
"/Root not in trailer or not an indirect reference",
|
| 696 |
+
)
|
| 697 |
+
return trailer
|
| 698 |
+
|
| 699 |
+
re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?")
|
| 700 |
+
|
| 701 |
+
@classmethod
|
| 702 |
+
def interpret_name(cls, raw, as_text=False):
|
| 703 |
+
name = b""
|
| 704 |
+
for m in cls.re_hashes_in_name.finditer(raw):
|
| 705 |
+
if m.group(3):
|
| 706 |
+
name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii"))
|
| 707 |
+
else:
|
| 708 |
+
name += m.group(1)
|
| 709 |
+
if as_text:
|
| 710 |
+
return name.decode("utf-8")
|
| 711 |
+
else:
|
| 712 |
+
return bytes(name)
|
| 713 |
+
|
| 714 |
+
re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")")
|
| 715 |
+
re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")")
|
| 716 |
+
re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")")
|
| 717 |
+
re_int = re.compile(
|
| 718 |
+
whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")"
|
| 719 |
+
)
|
| 720 |
+
re_real = re.compile(
|
| 721 |
+
whitespace_optional
|
| 722 |
+
+ rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?="
|
| 723 |
+
+ delimiter_or_ws
|
| 724 |
+
+ rb")"
|
| 725 |
+
)
|
| 726 |
+
re_array_start = re.compile(whitespace_optional + rb"\[")
|
| 727 |
+
re_array_end = re.compile(whitespace_optional + rb"]")
|
| 728 |
+
re_string_hex = re.compile(
|
| 729 |
+
whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>"
|
| 730 |
+
)
|
| 731 |
+
re_string_lit = re.compile(whitespace_optional + rb"\(")
|
| 732 |
+
re_indirect_reference = re.compile(
|
| 733 |
+
whitespace_optional
|
| 734 |
+
+ rb"([-+]?[0-9]+)"
|
| 735 |
+
+ whitespace_mandatory
|
| 736 |
+
+ rb"([-+]?[0-9]+)"
|
| 737 |
+
+ whitespace_mandatory
|
| 738 |
+
+ rb"R(?="
|
| 739 |
+
+ delimiter_or_ws
|
| 740 |
+
+ rb")"
|
| 741 |
+
)
|
| 742 |
+
re_indirect_def_start = re.compile(
|
| 743 |
+
whitespace_optional
|
| 744 |
+
+ rb"([-+]?[0-9]+)"
|
| 745 |
+
+ whitespace_mandatory
|
| 746 |
+
+ rb"([-+]?[0-9]+)"
|
| 747 |
+
+ whitespace_mandatory
|
| 748 |
+
+ rb"obj(?="
|
| 749 |
+
+ delimiter_or_ws
|
| 750 |
+
+ rb")"
|
| 751 |
+
)
|
| 752 |
+
re_indirect_def_end = re.compile(
|
| 753 |
+
whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")"
|
| 754 |
+
)
|
| 755 |
+
re_comment = re.compile(
|
| 756 |
+
rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*"
|
| 757 |
+
)
|
| 758 |
+
re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n")
|
| 759 |
+
re_stream_end = re.compile(
|
| 760 |
+
whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")"
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
@classmethod
|
| 764 |
+
def get_value(cls, data, offset, expect_indirect=None, max_nesting=-1):
|
| 765 |
+
if max_nesting == 0:
|
| 766 |
+
return None, None
|
| 767 |
+
m = cls.re_comment.match(data, offset)
|
| 768 |
+
if m:
|
| 769 |
+
offset = m.end()
|
| 770 |
+
m = cls.re_indirect_def_start.match(data, offset)
|
| 771 |
+
if m:
|
| 772 |
+
check_format_condition(
|
| 773 |
+
int(m.group(1)) > 0,
|
| 774 |
+
"indirect object definition: object ID must be greater than 0",
|
| 775 |
+
)
|
| 776 |
+
check_format_condition(
|
| 777 |
+
int(m.group(2)) >= 0,
|
| 778 |
+
"indirect object definition: generation must be non-negative",
|
| 779 |
+
)
|
| 780 |
+
check_format_condition(
|
| 781 |
+
expect_indirect is None
|
| 782 |
+
or expect_indirect
|
| 783 |
+
== IndirectReference(int(m.group(1)), int(m.group(2))),
|
| 784 |
+
"indirect object definition different than expected",
|
| 785 |
+
)
|
| 786 |
+
object, offset = cls.get_value(data, m.end(), max_nesting=max_nesting - 1)
|
| 787 |
+
if offset is None:
|
| 788 |
+
return object, None
|
| 789 |
+
m = cls.re_indirect_def_end.match(data, offset)
|
| 790 |
+
check_format_condition(m, "indirect object definition end not found")
|
| 791 |
+
return object, m.end()
|
| 792 |
+
check_format_condition(
|
| 793 |
+
not expect_indirect, "indirect object definition not found"
|
| 794 |
+
)
|
| 795 |
+
m = cls.re_indirect_reference.match(data, offset)
|
| 796 |
+
if m:
|
| 797 |
+
check_format_condition(
|
| 798 |
+
int(m.group(1)) > 0,
|
| 799 |
+
"indirect object reference: object ID must be greater than 0",
|
| 800 |
+
)
|
| 801 |
+
check_format_condition(
|
| 802 |
+
int(m.group(2)) >= 0,
|
| 803 |
+
"indirect object reference: generation must be non-negative",
|
| 804 |
+
)
|
| 805 |
+
return IndirectReference(int(m.group(1)), int(m.group(2))), m.end()
|
| 806 |
+
m = cls.re_dict_start.match(data, offset)
|
| 807 |
+
if m:
|
| 808 |
+
offset = m.end()
|
| 809 |
+
result = {}
|
| 810 |
+
m = cls.re_dict_end.match(data, offset)
|
| 811 |
+
while not m:
|
| 812 |
+
key, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1)
|
| 813 |
+
if offset is None:
|
| 814 |
+
return result, None
|
| 815 |
+
value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1)
|
| 816 |
+
result[key] = value
|
| 817 |
+
if offset is None:
|
| 818 |
+
return result, None
|
| 819 |
+
m = cls.re_dict_end.match(data, offset)
|
| 820 |
+
offset = m.end()
|
| 821 |
+
m = cls.re_stream_start.match(data, offset)
|
| 822 |
+
if m:
|
| 823 |
+
try:
|
| 824 |
+
stream_len_str = result.get(b"Length")
|
| 825 |
+
stream_len = int(stream_len_str)
|
| 826 |
+
except (TypeError, ValueError) as e:
|
| 827 |
+
msg = f"bad or missing Length in stream dict ({stream_len_str})"
|
| 828 |
+
raise PdfFormatError(msg) from e
|
| 829 |
+
stream_data = data[m.end() : m.end() + stream_len]
|
| 830 |
+
m = cls.re_stream_end.match(data, m.end() + stream_len)
|
| 831 |
+
check_format_condition(m, "stream end not found")
|
| 832 |
+
offset = m.end()
|
| 833 |
+
result = PdfStream(PdfDict(result), stream_data)
|
| 834 |
+
else:
|
| 835 |
+
result = PdfDict(result)
|
| 836 |
+
return result, offset
|
| 837 |
+
m = cls.re_array_start.match(data, offset)
|
| 838 |
+
if m:
|
| 839 |
+
offset = m.end()
|
| 840 |
+
result = []
|
| 841 |
+
m = cls.re_array_end.match(data, offset)
|
| 842 |
+
while not m:
|
| 843 |
+
value, offset = cls.get_value(data, offset, max_nesting=max_nesting - 1)
|
| 844 |
+
result.append(value)
|
| 845 |
+
if offset is None:
|
| 846 |
+
return result, None
|
| 847 |
+
m = cls.re_array_end.match(data, offset)
|
| 848 |
+
return result, m.end()
|
| 849 |
+
m = cls.re_null.match(data, offset)
|
| 850 |
+
if m:
|
| 851 |
+
return None, m.end()
|
| 852 |
+
m = cls.re_true.match(data, offset)
|
| 853 |
+
if m:
|
| 854 |
+
return True, m.end()
|
| 855 |
+
m = cls.re_false.match(data, offset)
|
| 856 |
+
if m:
|
| 857 |
+
return False, m.end()
|
| 858 |
+
m = cls.re_name.match(data, offset)
|
| 859 |
+
if m:
|
| 860 |
+
return PdfName(cls.interpret_name(m.group(1))), m.end()
|
| 861 |
+
m = cls.re_int.match(data, offset)
|
| 862 |
+
if m:
|
| 863 |
+
return int(m.group(1)), m.end()
|
| 864 |
+
m = cls.re_real.match(data, offset)
|
| 865 |
+
if m:
|
| 866 |
+
# XXX Decimal instead of float???
|
| 867 |
+
return float(m.group(1)), m.end()
|
| 868 |
+
m = cls.re_string_hex.match(data, offset)
|
| 869 |
+
if m:
|
| 870 |
+
# filter out whitespace
|
| 871 |
+
hex_string = bytearray(
|
| 872 |
+
b for b in m.group(1) if b in b"0123456789abcdefABCDEF"
|
| 873 |
+
)
|
| 874 |
+
if len(hex_string) % 2 == 1:
|
| 875 |
+
# append a 0 if the length is not even - yes, at the end
|
| 876 |
+
hex_string.append(ord(b"0"))
|
| 877 |
+
return bytearray.fromhex(hex_string.decode("us-ascii")), m.end()
|
| 878 |
+
m = cls.re_string_lit.match(data, offset)
|
| 879 |
+
if m:
|
| 880 |
+
return cls.get_literal_string(data, m.end())
|
| 881 |
+
# return None, offset # fallback (only for debugging)
|
| 882 |
+
msg = f"unrecognized object: {repr(data[offset : offset + 32])}"
|
| 883 |
+
raise PdfFormatError(msg)
|
| 884 |
+
|
| 885 |
+
re_lit_str_token = re.compile(
|
| 886 |
+
rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"
|
| 887 |
+
)
|
| 888 |
+
escaped_chars = {
|
| 889 |
+
b"n": b"\n",
|
| 890 |
+
b"r": b"\r",
|
| 891 |
+
b"t": b"\t",
|
| 892 |
+
b"b": b"\b",
|
| 893 |
+
b"f": b"\f",
|
| 894 |
+
b"(": b"(",
|
| 895 |
+
b")": b")",
|
| 896 |
+
b"\\": b"\\",
|
| 897 |
+
ord(b"n"): b"\n",
|
| 898 |
+
ord(b"r"): b"\r",
|
| 899 |
+
ord(b"t"): b"\t",
|
| 900 |
+
ord(b"b"): b"\b",
|
| 901 |
+
ord(b"f"): b"\f",
|
| 902 |
+
ord(b"("): b"(",
|
| 903 |
+
ord(b")"): b")",
|
| 904 |
+
ord(b"\\"): b"\\",
|
| 905 |
+
}
|
| 906 |
+
|
| 907 |
+
@classmethod
|
| 908 |
+
def get_literal_string(cls, data, offset):
|
| 909 |
+
nesting_depth = 0
|
| 910 |
+
result = bytearray()
|
| 911 |
+
for m in cls.re_lit_str_token.finditer(data, offset):
|
| 912 |
+
result.extend(data[offset : m.start()])
|
| 913 |
+
if m.group(1):
|
| 914 |
+
result.extend(cls.escaped_chars[m.group(1)[1]])
|
| 915 |
+
elif m.group(2):
|
| 916 |
+
result.append(int(m.group(2)[1:], 8))
|
| 917 |
+
elif m.group(3):
|
| 918 |
+
pass
|
| 919 |
+
elif m.group(5):
|
| 920 |
+
result.extend(b"\n")
|
| 921 |
+
elif m.group(6):
|
| 922 |
+
result.extend(b"(")
|
| 923 |
+
nesting_depth += 1
|
| 924 |
+
elif m.group(7):
|
| 925 |
+
if nesting_depth == 0:
|
| 926 |
+
return bytes(result), m.end()
|
| 927 |
+
result.extend(b")")
|
| 928 |
+
nesting_depth -= 1
|
| 929 |
+
offset = m.end()
|
| 930 |
+
msg = "unfinished literal string"
|
| 931 |
+
raise PdfFormatError(msg)
|
| 932 |
+
|
| 933 |
+
re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline)
|
| 934 |
+
re_xref_subsection_start = re.compile(
|
| 935 |
+
whitespace_optional
|
| 936 |
+
+ rb"([0-9]+)"
|
| 937 |
+
+ whitespace_mandatory
|
| 938 |
+
+ rb"([0-9]+)"
|
| 939 |
+
+ whitespace_optional
|
| 940 |
+
+ newline_only
|
| 941 |
+
)
|
| 942 |
+
re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)")
|
| 943 |
+
|
| 944 |
+
def read_xref_table(self, xref_section_offset):
|
| 945 |
+
subsection_found = False
|
| 946 |
+
m = self.re_xref_section_start.match(
|
| 947 |
+
self.buf, xref_section_offset + self.start_offset
|
| 948 |
+
)
|
| 949 |
+
check_format_condition(m, "xref section start not found")
|
| 950 |
+
offset = m.end()
|
| 951 |
+
while True:
|
| 952 |
+
m = self.re_xref_subsection_start.match(self.buf, offset)
|
| 953 |
+
if not m:
|
| 954 |
+
check_format_condition(
|
| 955 |
+
subsection_found, "xref subsection start not found"
|
| 956 |
+
)
|
| 957 |
+
break
|
| 958 |
+
subsection_found = True
|
| 959 |
+
offset = m.end()
|
| 960 |
+
first_object = int(m.group(1))
|
| 961 |
+
num_objects = int(m.group(2))
|
| 962 |
+
for i in range(first_object, first_object + num_objects):
|
| 963 |
+
m = self.re_xref_entry.match(self.buf, offset)
|
| 964 |
+
check_format_condition(m, "xref entry not found")
|
| 965 |
+
offset = m.end()
|
| 966 |
+
is_free = m.group(3) == b"f"
|
| 967 |
+
if not is_free:
|
| 968 |
+
generation = int(m.group(2))
|
| 969 |
+
new_entry = (int(m.group(1)), generation)
|
| 970 |
+
if i not in self.xref_table:
|
| 971 |
+
self.xref_table[i] = new_entry
|
| 972 |
+
return offset
|
| 973 |
+
|
| 974 |
+
def read_indirect(self, ref, max_nesting=-1):
|
| 975 |
+
offset, generation = self.xref_table[ref[0]]
|
| 976 |
+
check_format_condition(
|
| 977 |
+
generation == ref[1],
|
| 978 |
+
f"expected to find generation {ref[1]} for object ID {ref[0]} in xref "
|
| 979 |
+
f"table, instead found generation {generation} at offset {offset}",
|
| 980 |
+
)
|
| 981 |
+
value = self.get_value(
|
| 982 |
+
self.buf,
|
| 983 |
+
offset + self.start_offset,
|
| 984 |
+
expect_indirect=IndirectReference(*ref),
|
| 985 |
+
max_nesting=max_nesting,
|
| 986 |
+
)[0]
|
| 987 |
+
self.cached_objects[ref] = value
|
| 988 |
+
return value
|
| 989 |
+
|
| 990 |
+
def linearize_page_tree(self, node=None):
|
| 991 |
+
if node is None:
|
| 992 |
+
node = self.page_tree_root
|
| 993 |
+
check_format_condition(
|
| 994 |
+
node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages"
|
| 995 |
+
)
|
| 996 |
+
pages = []
|
| 997 |
+
for kid in node[b"Kids"]:
|
| 998 |
+
kid_object = self.read_indirect(kid)
|
| 999 |
+
if kid_object[b"Type"] == b"Page":
|
| 1000 |
+
pages.append(kid)
|
| 1001 |
+
else:
|
| 1002 |
+
pages.extend(self.linearize_page_tree(node=kid_object))
|
| 1003 |
+
return pages
|
.venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PIXAR raster support for PIL
|
| 6 |
+
#
|
| 7 |
+
# history:
|
| 8 |
+
# 97-01-29 fl Created
|
| 9 |
+
#
|
| 10 |
+
# notes:
|
| 11 |
+
# This is incomplete; it is based on a few samples created with
|
| 12 |
+
# Photoshop 2.5 and 3.0, and a summary description provided by
|
| 13 |
+
# Greg Coats <gcoats@labiris.er.usgs.gov>. Hopefully, "L" and
|
| 14 |
+
# "RGBA" support will be added in future versions.
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) Secret Labs AB 1997.
|
| 17 |
+
# Copyright (c) Fredrik Lundh 1997.
|
| 18 |
+
#
|
| 19 |
+
# See the README file for information on usage and redistribution.
|
| 20 |
+
#
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile
|
| 24 |
+
from ._binary import i16le as i16
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# helpers
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _accept(prefix: bytes) -> bool:
|
| 31 |
+
return prefix[:4] == b"\200\350\000\000"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
##
|
| 35 |
+
# Image plugin for PIXAR raster images.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PixarImageFile(ImageFile.ImageFile):
|
| 39 |
+
format = "PIXAR"
|
| 40 |
+
format_description = "PIXAR raster image"
|
| 41 |
+
|
| 42 |
+
def _open(self) -> None:
|
| 43 |
+
# assuming a 4-byte magic label
|
| 44 |
+
assert self.fp is not None
|
| 45 |
+
|
| 46 |
+
s = self.fp.read(4)
|
| 47 |
+
if not _accept(s):
|
| 48 |
+
msg = "not a PIXAR file"
|
| 49 |
+
raise SyntaxError(msg)
|
| 50 |
+
|
| 51 |
+
# read rest of header
|
| 52 |
+
s = s + self.fp.read(508)
|
| 53 |
+
|
| 54 |
+
self._size = i16(s, 418), i16(s, 416)
|
| 55 |
+
|
| 56 |
+
# get channel/depth descriptions
|
| 57 |
+
mode = i16(s, 424), i16(s, 426)
|
| 58 |
+
|
| 59 |
+
if mode == (14, 2):
|
| 60 |
+
self._mode = "RGB"
|
| 61 |
+
# FIXME: to be continued...
|
| 62 |
+
|
| 63 |
+
# create tile descriptor (assuming "dumped")
|
| 64 |
+
self.tile = [("raw", (0, 0) + self.size, 1024, (self.mode, 0, 1))]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
#
|
| 68 |
+
# --------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
Image.register_open(PixarImageFile.format, PixarImageFile, _accept)
|
| 71 |
+
|
| 72 |
+
Image.register_extension(PixarImageFile.format, ".pxr")
|
.venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py
ADDED
|
@@ -0,0 +1,1489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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(PngImageFile.format, [".png", ".apng"])
|
| 1488 |
+
|
| 1489 |
+
Image.register_mime(PngImageFile.format, "image/png")
|
.venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# PPM support for PIL
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 96-03-24 fl Created
|
| 9 |
+
# 98-03-06 fl Write RGBA images (as RGB, that is)
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
| 12 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 13 |
+
#
|
| 14 |
+
# See the README file for information on usage and redistribution.
|
| 15 |
+
#
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import IO
|
| 20 |
+
|
| 21 |
+
from . import Image, ImageFile
|
| 22 |
+
from ._binary import i16be as i16
|
| 23 |
+
from ._binary import o8
|
| 24 |
+
from ._binary import o32le as o32
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# --------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d"
|
| 30 |
+
|
| 31 |
+
MODES = {
|
| 32 |
+
# standard
|
| 33 |
+
b"P1": "1",
|
| 34 |
+
b"P2": "L",
|
| 35 |
+
b"P3": "RGB",
|
| 36 |
+
b"P4": "1",
|
| 37 |
+
b"P5": "L",
|
| 38 |
+
b"P6": "RGB",
|
| 39 |
+
# extensions
|
| 40 |
+
b"P0CMYK": "CMYK",
|
| 41 |
+
b"Pf": "F",
|
| 42 |
+
# PIL extensions (for test purposes only)
|
| 43 |
+
b"PyP": "P",
|
| 44 |
+
b"PyRGBA": "RGBA",
|
| 45 |
+
b"PyCMYK": "CMYK",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _accept(prefix: bytes) -> bool:
|
| 50 |
+
return prefix[0:1] == b"P" and prefix[1] in b"0123456fy"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
##
|
| 54 |
+
# Image plugin for PBM, PGM, and PPM images.
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PpmImageFile(ImageFile.ImageFile):
|
| 58 |
+
format = "PPM"
|
| 59 |
+
format_description = "Pbmplus image"
|
| 60 |
+
|
| 61 |
+
def _read_magic(self) -> bytes:
|
| 62 |
+
assert self.fp is not None
|
| 63 |
+
|
| 64 |
+
magic = b""
|
| 65 |
+
# read until whitespace or longest available magic number
|
| 66 |
+
for _ in range(6):
|
| 67 |
+
c = self.fp.read(1)
|
| 68 |
+
if not c or c in b_whitespace:
|
| 69 |
+
break
|
| 70 |
+
magic += c
|
| 71 |
+
return magic
|
| 72 |
+
|
| 73 |
+
def _read_token(self) -> bytes:
|
| 74 |
+
assert self.fp is not None
|
| 75 |
+
|
| 76 |
+
token = b""
|
| 77 |
+
while len(token) <= 10: # read until next whitespace or limit of 10 characters
|
| 78 |
+
c = self.fp.read(1)
|
| 79 |
+
if not c:
|
| 80 |
+
break
|
| 81 |
+
elif c in b_whitespace: # token ended
|
| 82 |
+
if not token:
|
| 83 |
+
# skip whitespace at start
|
| 84 |
+
continue
|
| 85 |
+
break
|
| 86 |
+
elif c == b"#":
|
| 87 |
+
# ignores rest of the line; stops at CR, LF or EOF
|
| 88 |
+
while self.fp.read(1) not in b"\r\n":
|
| 89 |
+
pass
|
| 90 |
+
continue
|
| 91 |
+
token += c
|
| 92 |
+
if not token:
|
| 93 |
+
# Token was not even 1 byte
|
| 94 |
+
msg = "Reached EOF while reading header"
|
| 95 |
+
raise ValueError(msg)
|
| 96 |
+
elif len(token) > 10:
|
| 97 |
+
msg = f"Token too long in file header: {token.decode()}"
|
| 98 |
+
raise ValueError(msg)
|
| 99 |
+
return token
|
| 100 |
+
|
| 101 |
+
def _open(self) -> None:
|
| 102 |
+
assert self.fp is not None
|
| 103 |
+
|
| 104 |
+
magic_number = self._read_magic()
|
| 105 |
+
try:
|
| 106 |
+
mode = MODES[magic_number]
|
| 107 |
+
except KeyError:
|
| 108 |
+
msg = "not a PPM file"
|
| 109 |
+
raise SyntaxError(msg)
|
| 110 |
+
self._mode = mode
|
| 111 |
+
|
| 112 |
+
if magic_number in (b"P1", b"P4"):
|
| 113 |
+
self.custom_mimetype = "image/x-portable-bitmap"
|
| 114 |
+
elif magic_number in (b"P2", b"P5"):
|
| 115 |
+
self.custom_mimetype = "image/x-portable-graymap"
|
| 116 |
+
elif magic_number in (b"P3", b"P6"):
|
| 117 |
+
self.custom_mimetype = "image/x-portable-pixmap"
|
| 118 |
+
|
| 119 |
+
self._size = int(self._read_token()), int(self._read_token())
|
| 120 |
+
|
| 121 |
+
decoder_name = "raw"
|
| 122 |
+
if magic_number in (b"P1", b"P2", b"P3"):
|
| 123 |
+
decoder_name = "ppm_plain"
|
| 124 |
+
|
| 125 |
+
args: str | tuple[str | int, ...]
|
| 126 |
+
if mode == "1":
|
| 127 |
+
args = "1;I"
|
| 128 |
+
elif mode == "F":
|
| 129 |
+
scale = float(self._read_token())
|
| 130 |
+
if scale == 0.0 or not math.isfinite(scale):
|
| 131 |
+
msg = "scale must be finite and non-zero"
|
| 132 |
+
raise ValueError(msg)
|
| 133 |
+
self.info["scale"] = abs(scale)
|
| 134 |
+
|
| 135 |
+
rawmode = "F;32F" if scale < 0 else "F;32BF"
|
| 136 |
+
args = (rawmode, 0, -1)
|
| 137 |
+
else:
|
| 138 |
+
maxval = int(self._read_token())
|
| 139 |
+
if not 0 < maxval < 65536:
|
| 140 |
+
msg = "maxval must be greater than 0 and less than 65536"
|
| 141 |
+
raise ValueError(msg)
|
| 142 |
+
if maxval > 255 and mode == "L":
|
| 143 |
+
self._mode = "I"
|
| 144 |
+
|
| 145 |
+
rawmode = mode
|
| 146 |
+
if decoder_name != "ppm_plain":
|
| 147 |
+
# If maxval matches a bit depth, use the raw decoder directly
|
| 148 |
+
if maxval == 65535 and mode == "L":
|
| 149 |
+
rawmode = "I;16B"
|
| 150 |
+
elif maxval != 255:
|
| 151 |
+
decoder_name = "ppm"
|
| 152 |
+
|
| 153 |
+
args = rawmode if decoder_name == "raw" else (rawmode, maxval)
|
| 154 |
+
self.tile = [(decoder_name, (0, 0) + self.size, self.fp.tell(), args)]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
#
|
| 158 |
+
# --------------------------------------------------------------------
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class PpmPlainDecoder(ImageFile.PyDecoder):
|
| 162 |
+
_pulls_fd = True
|
| 163 |
+
_comment_spans: bool
|
| 164 |
+
|
| 165 |
+
def _read_block(self) -> bytes:
|
| 166 |
+
assert self.fd is not None
|
| 167 |
+
|
| 168 |
+
return self.fd.read(ImageFile.SAFEBLOCK)
|
| 169 |
+
|
| 170 |
+
def _find_comment_end(self, block: bytes, start: int = 0) -> int:
|
| 171 |
+
a = block.find(b"\n", start)
|
| 172 |
+
b = block.find(b"\r", start)
|
| 173 |
+
return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1)
|
| 174 |
+
|
| 175 |
+
def _ignore_comments(self, block: bytes) -> bytes:
|
| 176 |
+
if self._comment_spans:
|
| 177 |
+
# Finish current comment
|
| 178 |
+
while block:
|
| 179 |
+
comment_end = self._find_comment_end(block)
|
| 180 |
+
if comment_end != -1:
|
| 181 |
+
# Comment ends in this block
|
| 182 |
+
# Delete tail of comment
|
| 183 |
+
block = block[comment_end + 1 :]
|
| 184 |
+
break
|
| 185 |
+
else:
|
| 186 |
+
# Comment spans whole block
|
| 187 |
+
# So read the next block, looking for the end
|
| 188 |
+
block = self._read_block()
|
| 189 |
+
|
| 190 |
+
# Search for any further comments
|
| 191 |
+
self._comment_spans = False
|
| 192 |
+
while True:
|
| 193 |
+
comment_start = block.find(b"#")
|
| 194 |
+
if comment_start == -1:
|
| 195 |
+
# No comment found
|
| 196 |
+
break
|
| 197 |
+
comment_end = self._find_comment_end(block, comment_start)
|
| 198 |
+
if comment_end != -1:
|
| 199 |
+
# Comment ends in this block
|
| 200 |
+
# Delete comment
|
| 201 |
+
block = block[:comment_start] + block[comment_end + 1 :]
|
| 202 |
+
else:
|
| 203 |
+
# Comment continues to next block(s)
|
| 204 |
+
block = block[:comment_start]
|
| 205 |
+
self._comment_spans = True
|
| 206 |
+
break
|
| 207 |
+
return block
|
| 208 |
+
|
| 209 |
+
def _decode_bitonal(self) -> bytearray:
|
| 210 |
+
"""
|
| 211 |
+
This is a separate method because in the plain PBM format, all data tokens are
|
| 212 |
+
exactly one byte, so the inter-token whitespace is optional.
|
| 213 |
+
"""
|
| 214 |
+
data = bytearray()
|
| 215 |
+
total_bytes = self.state.xsize * self.state.ysize
|
| 216 |
+
|
| 217 |
+
while len(data) != total_bytes:
|
| 218 |
+
block = self._read_block() # read next block
|
| 219 |
+
if not block:
|
| 220 |
+
# eof
|
| 221 |
+
break
|
| 222 |
+
|
| 223 |
+
block = self._ignore_comments(block)
|
| 224 |
+
|
| 225 |
+
tokens = b"".join(block.split())
|
| 226 |
+
for token in tokens:
|
| 227 |
+
if token not in (48, 49):
|
| 228 |
+
msg = b"Invalid token for this mode: %s" % bytes([token])
|
| 229 |
+
raise ValueError(msg)
|
| 230 |
+
data = (data + tokens)[:total_bytes]
|
| 231 |
+
invert = bytes.maketrans(b"01", b"\xFF\x00")
|
| 232 |
+
return data.translate(invert)
|
| 233 |
+
|
| 234 |
+
def _decode_blocks(self, maxval: int) -> bytearray:
|
| 235 |
+
data = bytearray()
|
| 236 |
+
max_len = 10
|
| 237 |
+
out_byte_count = 4 if self.mode == "I" else 1
|
| 238 |
+
out_max = 65535 if self.mode == "I" else 255
|
| 239 |
+
bands = Image.getmodebands(self.mode)
|
| 240 |
+
total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count
|
| 241 |
+
|
| 242 |
+
half_token = b""
|
| 243 |
+
while len(data) != total_bytes:
|
| 244 |
+
block = self._read_block() # read next block
|
| 245 |
+
if not block:
|
| 246 |
+
if half_token:
|
| 247 |
+
block = bytearray(b" ") # flush half_token
|
| 248 |
+
else:
|
| 249 |
+
# eof
|
| 250 |
+
break
|
| 251 |
+
|
| 252 |
+
block = self._ignore_comments(block)
|
| 253 |
+
|
| 254 |
+
if half_token:
|
| 255 |
+
block = half_token + block # stitch half_token to new block
|
| 256 |
+
half_token = b""
|
| 257 |
+
|
| 258 |
+
tokens = block.split()
|
| 259 |
+
|
| 260 |
+
if block and not block[-1:].isspace(): # block might split token
|
| 261 |
+
half_token = tokens.pop() # save half token for later
|
| 262 |
+
if len(half_token) > max_len: # prevent buildup of half_token
|
| 263 |
+
msg = (
|
| 264 |
+
b"Token too long found in data: %s" % half_token[: max_len + 1]
|
| 265 |
+
)
|
| 266 |
+
raise ValueError(msg)
|
| 267 |
+
|
| 268 |
+
for token in tokens:
|
| 269 |
+
if len(token) > max_len:
|
| 270 |
+
msg = b"Token too long found in data: %s" % token[: max_len + 1]
|
| 271 |
+
raise ValueError(msg)
|
| 272 |
+
value = int(token)
|
| 273 |
+
if value < 0:
|
| 274 |
+
msg_str = f"Channel value is negative: {value}"
|
| 275 |
+
raise ValueError(msg_str)
|
| 276 |
+
if value > maxval:
|
| 277 |
+
msg_str = f"Channel value too large for this mode: {value}"
|
| 278 |
+
raise ValueError(msg_str)
|
| 279 |
+
value = round(value / maxval * out_max)
|
| 280 |
+
data += o32(value) if self.mode == "I" else o8(value)
|
| 281 |
+
if len(data) == total_bytes: # finished!
|
| 282 |
+
break
|
| 283 |
+
return data
|
| 284 |
+
|
| 285 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 286 |
+
self._comment_spans = False
|
| 287 |
+
if self.mode == "1":
|
| 288 |
+
data = self._decode_bitonal()
|
| 289 |
+
rawmode = "1;8"
|
| 290 |
+
else:
|
| 291 |
+
maxval = self.args[-1]
|
| 292 |
+
data = self._decode_blocks(maxval)
|
| 293 |
+
rawmode = "I;32" if self.mode == "I" else self.mode
|
| 294 |
+
self.set_as_raw(bytes(data), rawmode)
|
| 295 |
+
return -1, 0
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class PpmDecoder(ImageFile.PyDecoder):
|
| 299 |
+
_pulls_fd = True
|
| 300 |
+
|
| 301 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 302 |
+
assert self.fd is not None
|
| 303 |
+
|
| 304 |
+
data = bytearray()
|
| 305 |
+
maxval = self.args[-1]
|
| 306 |
+
in_byte_count = 1 if maxval < 256 else 2
|
| 307 |
+
out_byte_count = 4 if self.mode == "I" else 1
|
| 308 |
+
out_max = 65535 if self.mode == "I" else 255
|
| 309 |
+
bands = Image.getmodebands(self.mode)
|
| 310 |
+
dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count
|
| 311 |
+
while len(data) < dest_length:
|
| 312 |
+
pixels = self.fd.read(in_byte_count * bands)
|
| 313 |
+
if len(pixels) < in_byte_count * bands:
|
| 314 |
+
# eof
|
| 315 |
+
break
|
| 316 |
+
for b in range(bands):
|
| 317 |
+
value = (
|
| 318 |
+
pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count)
|
| 319 |
+
)
|
| 320 |
+
value = min(out_max, round(value / maxval * out_max))
|
| 321 |
+
data += o32(value) if self.mode == "I" else o8(value)
|
| 322 |
+
rawmode = "I;32" if self.mode == "I" else self.mode
|
| 323 |
+
self.set_as_raw(bytes(data), rawmode)
|
| 324 |
+
return -1, 0
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
#
|
| 328 |
+
# --------------------------------------------------------------------
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 332 |
+
if im.mode == "1":
|
| 333 |
+
rawmode, head = "1;I", b"P4"
|
| 334 |
+
elif im.mode == "L":
|
| 335 |
+
rawmode, head = "L", b"P5"
|
| 336 |
+
elif im.mode == "I":
|
| 337 |
+
rawmode, head = "I;16B", b"P5"
|
| 338 |
+
elif im.mode in ("RGB", "RGBA"):
|
| 339 |
+
rawmode, head = "RGB", b"P6"
|
| 340 |
+
elif im.mode == "F":
|
| 341 |
+
rawmode, head = "F;32F", b"Pf"
|
| 342 |
+
else:
|
| 343 |
+
msg = f"cannot write mode {im.mode} as PPM"
|
| 344 |
+
raise OSError(msg)
|
| 345 |
+
fp.write(head + b"\n%d %d\n" % im.size)
|
| 346 |
+
if head == b"P6":
|
| 347 |
+
fp.write(b"255\n")
|
| 348 |
+
elif head == b"P5":
|
| 349 |
+
if rawmode == "L":
|
| 350 |
+
fp.write(b"255\n")
|
| 351 |
+
else:
|
| 352 |
+
fp.write(b"65535\n")
|
| 353 |
+
elif head == b"Pf":
|
| 354 |
+
fp.write(b"-1.0\n")
|
| 355 |
+
row_order = -1 if im.mode == "F" else 1
|
| 356 |
+
ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))])
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
#
|
| 360 |
+
# --------------------------------------------------------------------
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
Image.register_open(PpmImageFile.format, PpmImageFile, _accept)
|
| 364 |
+
Image.register_save(PpmImageFile.format, _save)
|
| 365 |
+
|
| 366 |
+
Image.register_decoder("ppm", PpmDecoder)
|
| 367 |
+
Image.register_decoder("ppm_plain", PpmPlainDecoder)
|
| 368 |
+
|
| 369 |
+
Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"])
|
| 370 |
+
|
| 371 |
+
Image.register_mime(PpmImageFile.format, "image/x-portable-anymap")
|
.venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
Image.register_extension(PsdImageFile.format, ".psd")
|
| 325 |
+
|
| 326 |
+
Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")
|
.venv/lib/python3.11/site-packages/PIL/PyAccess.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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)
|
.venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
#
|
| 4 |
+
# QOI support for PIL
|
| 5 |
+
#
|
| 6 |
+
# See the README file for information on usage and redistribution.
|
| 7 |
+
#
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
from . import Image, ImageFile
|
| 13 |
+
from ._binary import i32be as i32
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _accept(prefix: bytes) -> bool:
|
| 17 |
+
return prefix[:4] == b"qoif"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class QoiImageFile(ImageFile.ImageFile):
|
| 21 |
+
format = "QOI"
|
| 22 |
+
format_description = "Quite OK Image"
|
| 23 |
+
|
| 24 |
+
def _open(self) -> None:
|
| 25 |
+
if not _accept(self.fp.read(4)):
|
| 26 |
+
msg = "not a QOI file"
|
| 27 |
+
raise SyntaxError(msg)
|
| 28 |
+
|
| 29 |
+
self._size = tuple(i32(self.fp.read(4)) for i in range(2))
|
| 30 |
+
|
| 31 |
+
channels = self.fp.read(1)[0]
|
| 32 |
+
self._mode = "RGB" if channels == 3 else "RGBA"
|
| 33 |
+
|
| 34 |
+
self.fp.seek(1, os.SEEK_CUR) # colorspace
|
| 35 |
+
self.tile = [("qoi", (0, 0) + self._size, self.fp.tell(), None)]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class QoiDecoder(ImageFile.PyDecoder):
|
| 39 |
+
_pulls_fd = True
|
| 40 |
+
_previous_pixel: bytes | bytearray | None = None
|
| 41 |
+
_previously_seen_pixels: dict[int, bytes | bytearray] = {}
|
| 42 |
+
|
| 43 |
+
def _add_to_previous_pixels(self, value: bytes | bytearray) -> None:
|
| 44 |
+
self._previous_pixel = value
|
| 45 |
+
|
| 46 |
+
r, g, b, a = value
|
| 47 |
+
hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64
|
| 48 |
+
self._previously_seen_pixels[hash_value] = value
|
| 49 |
+
|
| 50 |
+
def decode(self, buffer: bytes) -> tuple[int, int]:
|
| 51 |
+
assert self.fd is not None
|
| 52 |
+
|
| 53 |
+
self._previously_seen_pixels = {}
|
| 54 |
+
self._add_to_previous_pixels(bytearray((0, 0, 0, 255)))
|
| 55 |
+
|
| 56 |
+
data = bytearray()
|
| 57 |
+
bands = Image.getmodebands(self.mode)
|
| 58 |
+
dest_length = self.state.xsize * self.state.ysize * bands
|
| 59 |
+
while len(data) < dest_length:
|
| 60 |
+
byte = self.fd.read(1)[0]
|
| 61 |
+
value: bytes | bytearray
|
| 62 |
+
if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB
|
| 63 |
+
value = bytearray(self.fd.read(3)) + self._previous_pixel[3:]
|
| 64 |
+
elif byte == 0b11111111: # QOI_OP_RGBA
|
| 65 |
+
value = self.fd.read(4)
|
| 66 |
+
else:
|
| 67 |
+
op = byte >> 6
|
| 68 |
+
if op == 0: # QOI_OP_INDEX
|
| 69 |
+
op_index = byte & 0b00111111
|
| 70 |
+
value = self._previously_seen_pixels.get(
|
| 71 |
+
op_index, bytearray((0, 0, 0, 0))
|
| 72 |
+
)
|
| 73 |
+
elif op == 1 and self._previous_pixel: # QOI_OP_DIFF
|
| 74 |
+
value = bytearray(
|
| 75 |
+
(
|
| 76 |
+
(self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2)
|
| 77 |
+
% 256,
|
| 78 |
+
(self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2)
|
| 79 |
+
% 256,
|
| 80 |
+
(self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256,
|
| 81 |
+
self._previous_pixel[3],
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
elif op == 2 and self._previous_pixel: # QOI_OP_LUMA
|
| 85 |
+
second_byte = self.fd.read(1)[0]
|
| 86 |
+
diff_green = (byte & 0b00111111) - 32
|
| 87 |
+
diff_red = ((second_byte & 0b11110000) >> 4) - 8
|
| 88 |
+
diff_blue = (second_byte & 0b00001111) - 8
|
| 89 |
+
|
| 90 |
+
value = bytearray(
|
| 91 |
+
tuple(
|
| 92 |
+
(self._previous_pixel[i] + diff_green + diff) % 256
|
| 93 |
+
for i, diff in enumerate((diff_red, 0, diff_blue))
|
| 94 |
+
)
|
| 95 |
+
)
|
| 96 |
+
value += self._previous_pixel[3:]
|
| 97 |
+
elif op == 3 and self._previous_pixel: # QOI_OP_RUN
|
| 98 |
+
run_length = (byte & 0b00111111) + 1
|
| 99 |
+
value = self._previous_pixel
|
| 100 |
+
if bands == 3:
|
| 101 |
+
value = value[:3]
|
| 102 |
+
data += value * run_length
|
| 103 |
+
continue
|
| 104 |
+
self._add_to_previous_pixels(value)
|
| 105 |
+
|
| 106 |
+
if bands == 3:
|
| 107 |
+
value = value[:3]
|
| 108 |
+
data += value
|
| 109 |
+
self.set_as_raw(data)
|
| 110 |
+
return -1, 0
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
Image.register_open(QoiImageFile.format, QoiImageFile, _accept)
|
| 114 |
+
Image.register_decoder("qoi", QoiDecoder)
|
| 115 |
+
Image.register_extension(QoiImageFile.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# SGI image file handling
|
| 6 |
+
#
|
| 7 |
+
# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
|
| 8 |
+
# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
|
| 9 |
+
#
|
| 10 |
+
#
|
| 11 |
+
# History:
|
| 12 |
+
# 2017-22-07 mb Add RLE decompression
|
| 13 |
+
# 2016-16-10 mb Add save method without compression
|
| 14 |
+
# 1995-09-10 fl Created
|
| 15 |
+
#
|
| 16 |
+
# Copyright (c) 2016 by Mickael Bonfill.
|
| 17 |
+
# Copyright (c) 2008 by Karsten Hiddemann.
|
| 18 |
+
# Copyright (c) 1997 by Secret Labs AB.
|
| 19 |
+
# Copyright (c) 1995 by Fredrik Lundh.
|
| 20 |
+
#
|
| 21 |
+
# See the README file for information on usage and redistribution.
|
| 22 |
+
#
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
import struct
|
| 27 |
+
from typing import IO
|
| 28 |
+
|
| 29 |
+
from . import Image, ImageFile
|
| 30 |
+
from ._binary import i16be as i16
|
| 31 |
+
from ._binary import o8
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _accept(prefix: bytes) -> bool:
|
| 35 |
+
return len(prefix) >= 2 and i16(prefix) == 474
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
MODES = {
|
| 39 |
+
(1, 1, 1): "L",
|
| 40 |
+
(1, 2, 1): "L",
|
| 41 |
+
(2, 1, 1): "L;16B",
|
| 42 |
+
(2, 2, 1): "L;16B",
|
| 43 |
+
(1, 3, 3): "RGB",
|
| 44 |
+
(2, 3, 3): "RGB;16B",
|
| 45 |
+
(1, 3, 4): "RGBA",
|
| 46 |
+
(2, 3, 4): "RGBA;16B",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
##
|
| 51 |
+
# Image plugin for SGI images.
|
| 52 |
+
class SgiImageFile(ImageFile.ImageFile):
|
| 53 |
+
format = "SGI"
|
| 54 |
+
format_description = "SGI Image File Format"
|
| 55 |
+
|
| 56 |
+
def _open(self) -> None:
|
| 57 |
+
# HEAD
|
| 58 |
+
assert self.fp is not None
|
| 59 |
+
|
| 60 |
+
headlen = 512
|
| 61 |
+
s = self.fp.read(headlen)
|
| 62 |
+
|
| 63 |
+
if not _accept(s):
|
| 64 |
+
msg = "Not an SGI image file"
|
| 65 |
+
raise ValueError(msg)
|
| 66 |
+
|
| 67 |
+
# compression : verbatim or RLE
|
| 68 |
+
compression = s[2]
|
| 69 |
+
|
| 70 |
+
# bpc : 1 or 2 bytes (8bits or 16bits)
|
| 71 |
+
bpc = s[3]
|
| 72 |
+
|
| 73 |
+
# dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
|
| 74 |
+
dimension = i16(s, 4)
|
| 75 |
+
|
| 76 |
+
# xsize : width
|
| 77 |
+
xsize = i16(s, 6)
|
| 78 |
+
|
| 79 |
+
# ysize : height
|
| 80 |
+
ysize = i16(s, 8)
|
| 81 |
+
|
| 82 |
+
# zsize : channels count
|
| 83 |
+
zsize = i16(s, 10)
|
| 84 |
+
|
| 85 |
+
# 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
|
.venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 4 |
+
#
|
| 5 |
+
# TGA file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 95-09-01 fl created (reads 24-bit files only)
|
| 9 |
+
# 97-01-04 fl support more TGA versions, including compressed images
|
| 10 |
+
# 98-07-04 fl fixed orientation and alpha layer bugs
|
| 11 |
+
# 98-09-11 fl fixed orientation for runlength decoder
|
| 12 |
+
#
|
| 13 |
+
# Copyright (c) Secret Labs AB 1997-98.
|
| 14 |
+
# Copyright (c) Fredrik Lundh 1995-97.
|
| 15 |
+
#
|
| 16 |
+
# See the README file for information on usage and redistribution.
|
| 17 |
+
#
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import warnings
|
| 21 |
+
from typing import IO
|
| 22 |
+
|
| 23 |
+
from . import Image, ImageFile, ImagePalette
|
| 24 |
+
from ._binary import i16le as i16
|
| 25 |
+
from ._binary import o8
|
| 26 |
+
from ._binary import o16le as o16
|
| 27 |
+
|
| 28 |
+
#
|
| 29 |
+
# --------------------------------------------------------------------
|
| 30 |
+
# Read RGA file
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
MODES = {
|
| 34 |
+
# map imagetype/depth to rawmode
|
| 35 |
+
(1, 8): "P",
|
| 36 |
+
(3, 1): "1",
|
| 37 |
+
(3, 8): "L",
|
| 38 |
+
(3, 16): "LA",
|
| 39 |
+
(2, 16): "BGRA;15Z",
|
| 40 |
+
(2, 24): "BGR",
|
| 41 |
+
(2, 32): "BGRA",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
##
|
| 46 |
+
# Image plugin for Targa files.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class TgaImageFile(ImageFile.ImageFile):
|
| 50 |
+
format = "TGA"
|
| 51 |
+
format_description = "Targa"
|
| 52 |
+
|
| 53 |
+
def _open(self) -> None:
|
| 54 |
+
# process header
|
| 55 |
+
assert self.fp is not None
|
| 56 |
+
|
| 57 |
+
s = self.fp.read(18)
|
| 58 |
+
|
| 59 |
+
id_len = s[0]
|
| 60 |
+
|
| 61 |
+
colormaptype = s[1]
|
| 62 |
+
imagetype = s[2]
|
| 63 |
+
|
| 64 |
+
depth = s[16]
|
| 65 |
+
|
| 66 |
+
flags = s[17]
|
| 67 |
+
|
| 68 |
+
self._size = i16(s, 12), i16(s, 14)
|
| 69 |
+
|
| 70 |
+
# validate header fields
|
| 71 |
+
if (
|
| 72 |
+
colormaptype not in (0, 1)
|
| 73 |
+
or self.size[0] <= 0
|
| 74 |
+
or self.size[1] <= 0
|
| 75 |
+
or depth not in (1, 8, 16, 24, 32)
|
| 76 |
+
):
|
| 77 |
+
msg = "not a TGA file"
|
| 78 |
+
raise SyntaxError(msg)
|
| 79 |
+
|
| 80 |
+
# image mode
|
| 81 |
+
if imagetype in (3, 11):
|
| 82 |
+
self._mode = "L"
|
| 83 |
+
if depth == 1:
|
| 84 |
+
self._mode = "1" # ???
|
| 85 |
+
elif depth == 16:
|
| 86 |
+
self._mode = "LA"
|
| 87 |
+
elif imagetype in (1, 9):
|
| 88 |
+
self._mode = "P" if colormaptype else "L"
|
| 89 |
+
elif imagetype in (2, 10):
|
| 90 |
+
self._mode = "RGB" if depth == 24 else "RGBA"
|
| 91 |
+
else:
|
| 92 |
+
msg = "unknown TGA mode"
|
| 93 |
+
raise SyntaxError(msg)
|
| 94 |
+
|
| 95 |
+
# orientation
|
| 96 |
+
orientation = flags & 0x30
|
| 97 |
+
self._flip_horizontally = orientation in [0x10, 0x30]
|
| 98 |
+
if orientation in [0x20, 0x30]:
|
| 99 |
+
orientation = 1
|
| 100 |
+
elif orientation in [0, 0x10]:
|
| 101 |
+
orientation = -1
|
| 102 |
+
else:
|
| 103 |
+
msg = "unknown TGA orientation"
|
| 104 |
+
raise SyntaxError(msg)
|
| 105 |
+
|
| 106 |
+
self.info["orientation"] = orientation
|
| 107 |
+
|
| 108 |
+
if imagetype & 8:
|
| 109 |
+
self.info["compression"] = "tga_rle"
|
| 110 |
+
|
| 111 |
+
if id_len:
|
| 112 |
+
self.info["id_section"] = self.fp.read(id_len)
|
| 113 |
+
|
| 114 |
+
if colormaptype:
|
| 115 |
+
# read palette
|
| 116 |
+
start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
|
| 117 |
+
if mapdepth == 16:
|
| 118 |
+
self.palette = ImagePalette.raw(
|
| 119 |
+
"BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)
|
| 120 |
+
)
|
| 121 |
+
self.palette.mode = "RGBA"
|
| 122 |
+
elif mapdepth == 24:
|
| 123 |
+
self.palette = ImagePalette.raw(
|
| 124 |
+
"BGR", bytes(3 * start) + self.fp.read(3 * size)
|
| 125 |
+
)
|
| 126 |
+
elif mapdepth == 32:
|
| 127 |
+
self.palette = ImagePalette.raw(
|
| 128 |
+
"BGRA", bytes(4 * start) + self.fp.read(4 * size)
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
msg = "unknown TGA map depth"
|
| 132 |
+
raise SyntaxError(msg)
|
| 133 |
+
|
| 134 |
+
# setup tile descriptor
|
| 135 |
+
try:
|
| 136 |
+
rawmode = MODES[(imagetype & 7, depth)]
|
| 137 |
+
if imagetype & 8:
|
| 138 |
+
# compressed
|
| 139 |
+
self.tile = [
|
| 140 |
+
(
|
| 141 |
+
"tga_rle",
|
| 142 |
+
(0, 0) + self.size,
|
| 143 |
+
self.fp.tell(),
|
| 144 |
+
(rawmode, orientation, depth),
|
| 145 |
+
)
|
| 146 |
+
]
|
| 147 |
+
else:
|
| 148 |
+
self.tile = [
|
| 149 |
+
(
|
| 150 |
+
"raw",
|
| 151 |
+
(0, 0) + self.size,
|
| 152 |
+
self.fp.tell(),
|
| 153 |
+
(rawmode, 0, orientation),
|
| 154 |
+
)
|
| 155 |
+
]
|
| 156 |
+
except KeyError:
|
| 157 |
+
pass # cannot decode
|
| 158 |
+
|
| 159 |
+
def load_end(self) -> None:
|
| 160 |
+
if self._flip_horizontally:
|
| 161 |
+
assert self.im is not None
|
| 162 |
+
self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
#
|
| 166 |
+
# --------------------------------------------------------------------
|
| 167 |
+
# Write TGA file
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
SAVE = {
|
| 171 |
+
"1": ("1", 1, 0, 3),
|
| 172 |
+
"L": ("L", 8, 0, 3),
|
| 173 |
+
"LA": ("LA", 16, 0, 3),
|
| 174 |
+
"P": ("P", 8, 1, 1),
|
| 175 |
+
"RGB": ("BGR", 24, 0, 2),
|
| 176 |
+
"RGBA": ("BGRA", 32, 0, 2),
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 181 |
+
try:
|
| 182 |
+
rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
|
| 183 |
+
except KeyError as e:
|
| 184 |
+
msg = f"cannot write mode {im.mode} as TGA"
|
| 185 |
+
raise OSError(msg) from e
|
| 186 |
+
|
| 187 |
+
if "rle" in im.encoderinfo:
|
| 188 |
+
rle = im.encoderinfo["rle"]
|
| 189 |
+
else:
|
| 190 |
+
compression = im.encoderinfo.get("compression", im.info.get("compression"))
|
| 191 |
+
rle = compression == "tga_rle"
|
| 192 |
+
if rle:
|
| 193 |
+
imagetype += 8
|
| 194 |
+
|
| 195 |
+
id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
|
| 196 |
+
id_len = len(id_section)
|
| 197 |
+
if id_len > 255:
|
| 198 |
+
id_len = 255
|
| 199 |
+
id_section = id_section[:255]
|
| 200 |
+
warnings.warn("id_section has been trimmed to 255 characters")
|
| 201 |
+
|
| 202 |
+
if colormaptype:
|
| 203 |
+
assert im.im is not None
|
| 204 |
+
palette = im.im.getpalette("RGB", "BGR")
|
| 205 |
+
colormaplength, colormapentry = len(palette) // 3, 24
|
| 206 |
+
else:
|
| 207 |
+
colormaplength, colormapentry = 0, 0
|
| 208 |
+
|
| 209 |
+
if im.mode in ("LA", "RGBA"):
|
| 210 |
+
flags = 8
|
| 211 |
+
else:
|
| 212 |
+
flags = 0
|
| 213 |
+
|
| 214 |
+
orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
|
| 215 |
+
if orientation > 0:
|
| 216 |
+
flags = flags | 0x20
|
| 217 |
+
|
| 218 |
+
fp.write(
|
| 219 |
+
o8(id_len)
|
| 220 |
+
+ o8(colormaptype)
|
| 221 |
+
+ o8(imagetype)
|
| 222 |
+
+ o16(0) # colormapfirst
|
| 223 |
+
+ o16(colormaplength)
|
| 224 |
+
+ o8(colormapentry)
|
| 225 |
+
+ o16(0)
|
| 226 |
+
+ o16(0)
|
| 227 |
+
+ o16(im.size[0])
|
| 228 |
+
+ o16(im.size[1])
|
| 229 |
+
+ o8(bits)
|
| 230 |
+
+ o8(flags)
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
if id_section:
|
| 234 |
+
fp.write(id_section)
|
| 235 |
+
|
| 236 |
+
if colormaptype:
|
| 237 |
+
fp.write(palette)
|
| 238 |
+
|
| 239 |
+
if rle:
|
| 240 |
+
ImageFile._save(
|
| 241 |
+
im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))]
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
ImageFile._save(
|
| 245 |
+
im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))]
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# write targa version 2 footer
|
| 249 |
+
fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
#
|
| 253 |
+
# --------------------------------------------------------------------
|
| 254 |
+
# Registry
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
Image.register_open(TgaImageFile.format, TgaImageFile)
|
| 258 |
+
Image.register_save(TgaImageFile.format, _save)
|
| 259 |
+
|
| 260 |
+
Image.register_extensions(TgaImageFile.format,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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# TIFF file handling
|
| 6 |
+
#
|
| 7 |
+
# TIFF is a flexible, if somewhat aged, image file format originally
|
| 8 |
+
# defined by Aldus. Although TIFF supports a wide variety of pixel
|
| 9 |
+
# layouts and compression methods, the name doesn't really stand for
|
| 10 |
+
# "thousands of incompatible file formats," it just feels that way.
|
| 11 |
+
#
|
| 12 |
+
# To read TIFF data from a stream, the stream must be seekable. For
|
| 13 |
+
# progressive decoding, make sure to use TIFF files where the tag
|
| 14 |
+
# directory is placed first in the file.
|
| 15 |
+
#
|
| 16 |
+
# History:
|
| 17 |
+
# 1995-09-01 fl Created
|
| 18 |
+
# 1996-05-04 fl Handle JPEGTABLES tag
|
| 19 |
+
# 1996-05-18 fl Fixed COLORMAP support
|
| 20 |
+
# 1997-01-05 fl Fixed PREDICTOR support
|
| 21 |
+
# 1997-08-27 fl Added support for rational tags (from Perry Stoll)
|
| 22 |
+
# 1998-01-10 fl Fixed seek/tell (from Jan Blom)
|
| 23 |
+
# 1998-07-15 fl Use private names for internal variables
|
| 24 |
+
# 1999-06-13 fl Rewritten for PIL 1.0 (1.0)
|
| 25 |
+
# 2000-10-11 fl Additional fixes for Python 2.0 (1.1)
|
| 26 |
+
# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2)
|
| 27 |
+
# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3)
|
| 28 |
+
# 2001-12-18 fl Added workaround for broken Matrox library
|
| 29 |
+
# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart)
|
| 30 |
+
# 2003-05-19 fl Check FILLORDER tag
|
| 31 |
+
# 2003-09-26 fl Added RGBa support
|
| 32 |
+
# 2004-02-24 fl Added DPI support; fixed rational write support
|
| 33 |
+
# 2005-02-07 fl Added workaround for broken Corel Draw 10 files
|
| 34 |
+
# 2006-01-09 fl Added support for float/double tags (from Russell Nelson)
|
| 35 |
+
#
|
| 36 |
+
# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved.
|
| 37 |
+
# Copyright (c) 1995-1997 by Fredrik Lundh
|
| 38 |
+
#
|
| 39 |
+
# See the README file for information on usage and redistribution.
|
| 40 |
+
#
|
| 41 |
+
from __future__ import annotations
|
| 42 |
+
|
| 43 |
+
import io
|
| 44 |
+
import itertools
|
| 45 |
+
import logging
|
| 46 |
+
import math
|
| 47 |
+
import os
|
| 48 |
+
import struct
|
| 49 |
+
import warnings
|
| 50 |
+
from collections.abc import MutableMapping
|
| 51 |
+
from fractions import Fraction
|
| 52 |
+
from numbers import Number, Rational
|
| 53 |
+
from typing import IO, TYPE_CHECKING, Any, Callable, NoReturn
|
| 54 |
+
|
| 55 |
+
from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags
|
| 56 |
+
from ._binary import i16be as i16
|
| 57 |
+
from ._binary import i32be as i32
|
| 58 |
+
from ._binary import o8
|
| 59 |
+
from ._deprecate import deprecate
|
| 60 |
+
from .TiffTags import TYPES
|
| 61 |
+
|
| 62 |
+
logger = logging.getLogger(__name__)
|
| 63 |
+
|
| 64 |
+
# Set these to true to force use of libtiff for reading or writing.
|
| 65 |
+
READ_LIBTIFF = False
|
| 66 |
+
WRITE_LIBTIFF = False
|
| 67 |
+
IFD_LEGACY_API = True
|
| 68 |
+
STRIP_SIZE = 65536
|
| 69 |
+
|
| 70 |
+
II = b"II" # little-endian (Intel style)
|
| 71 |
+
MM = b"MM" # big-endian (Motorola style)
|
| 72 |
+
|
| 73 |
+
#
|
| 74 |
+
# --------------------------------------------------------------------
|
| 75 |
+
# Read TIFF files
|
| 76 |
+
|
| 77 |
+
# a few tag names, just to make the code below a bit more readable
|
| 78 |
+
OSUBFILETYPE = 255
|
| 79 |
+
IMAGEWIDTH = 256
|
| 80 |
+
IMAGELENGTH = 257
|
| 81 |
+
BITSPERSAMPLE = 258
|
| 82 |
+
COMPRESSION = 259
|
| 83 |
+
PHOTOMETRIC_INTERPRETATION = 262
|
| 84 |
+
FILLORDER = 266
|
| 85 |
+
IMAGEDESCRIPTION = 270
|
| 86 |
+
STRIPOFFSETS = 273
|
| 87 |
+
SAMPLESPERPIXEL = 277
|
| 88 |
+
ROWSPERSTRIP = 278
|
| 89 |
+
STRIPBYTECOUNTS = 279
|
| 90 |
+
X_RESOLUTION = 282
|
| 91 |
+
Y_RESOLUTION = 283
|
| 92 |
+
PLANAR_CONFIGURATION = 284
|
| 93 |
+
RESOLUTION_UNIT = 296
|
| 94 |
+
TRANSFERFUNCTION = 301
|
| 95 |
+
SOFTWARE = 305
|
| 96 |
+
DATE_TIME = 306
|
| 97 |
+
ARTIST = 315
|
| 98 |
+
PREDICTOR = 317
|
| 99 |
+
COLORMAP = 320
|
| 100 |
+
TILEWIDTH = 322
|
| 101 |
+
TILELENGTH = 323
|
| 102 |
+
TILEOFFSETS = 324
|
| 103 |
+
TILEBYTECOUNTS = 325
|
| 104 |
+
SUBIFD = 330
|
| 105 |
+
EXTRASAMPLES = 338
|
| 106 |
+
SAMPLEFORMAT = 339
|
| 107 |
+
JPEGTABLES = 347
|
| 108 |
+
YCBCRSUBSAMPLING = 530
|
| 109 |
+
REFERENCEBLACKWHITE = 532
|
| 110 |
+
COPYRIGHT = 33432
|
| 111 |
+
IPTC_NAA_CHUNK = 33723 # newsphoto properties
|
| 112 |
+
PHOTOSHOP_CHUNK = 34377 # photoshop properties
|
| 113 |
+
ICCPROFILE = 34675
|
| 114 |
+
EXIFIFD = 34665
|
| 115 |
+
XMP = 700
|
| 116 |
+
JPEGQUALITY = 65537 # pseudo-tag by libtiff
|
| 117 |
+
|
| 118 |
+
# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
|
| 119 |
+
IMAGEJ_META_DATA_BYTE_COUNTS = 50838
|
| 120 |
+
IMAGEJ_META_DATA = 50839
|
| 121 |
+
|
| 122 |
+
COMPRESSION_INFO = {
|
| 123 |
+
# Compression => pil compression name
|
| 124 |
+
1: "raw",
|
| 125 |
+
2: "tiff_ccitt",
|
| 126 |
+
3: "group3",
|
| 127 |
+
4: "group4",
|
| 128 |
+
5: "tiff_lzw",
|
| 129 |
+
6: "tiff_jpeg", # obsolete
|
| 130 |
+
7: "jpeg",
|
| 131 |
+
8: "tiff_adobe_deflate",
|
| 132 |
+
32771: "tiff_raw_16", # 16-bit padding
|
| 133 |
+
32773: "packbits",
|
| 134 |
+
32809: "tiff_thunderscan",
|
| 135 |
+
32946: "tiff_deflate",
|
| 136 |
+
34676: "tiff_sgilog",
|
| 137 |
+
34677: "tiff_sgilog24",
|
| 138 |
+
34925: "lzma",
|
| 139 |
+
50000: "zstd",
|
| 140 |
+
50001: "webp",
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}
|
| 144 |
+
|
| 145 |
+
OPEN_INFO = {
|
| 146 |
+
# (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
|
| 147 |
+
# ExtraSamples) => mode, rawmode
|
| 148 |
+
(II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 149 |
+
(MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
|
| 150 |
+
(II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 151 |
+
(MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
|
| 152 |
+
(II, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 153 |
+
(MM, 1, (1,), 1, (1,), ()): ("1", "1"),
|
| 154 |
+
(II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 155 |
+
(MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),
|
| 156 |
+
(II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 157 |
+
(MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
|
| 158 |
+
(II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 159 |
+
(MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
|
| 160 |
+
(II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 161 |
+
(MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
|
| 162 |
+
(II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 163 |
+
(MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
|
| 164 |
+
(II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 165 |
+
(MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
|
| 166 |
+
(II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 167 |
+
(MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
|
| 168 |
+
(II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 169 |
+
(MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
|
| 170 |
+
(II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 171 |
+
(MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
|
| 172 |
+
(II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 173 |
+
(MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
|
| 174 |
+
(II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 175 |
+
(MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
|
| 176 |
+
(II, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 177 |
+
(MM, 1, (1,), 1, (8,), ()): ("L", "L"),
|
| 178 |
+
(II, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 179 |
+
(MM, 1, (2,), 1, (8,), ()): ("L", "L"),
|
| 180 |
+
(II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 181 |
+
(MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),
|
| 182 |
+
(II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
|
| 183 |
+
(II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 184 |
+
(II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
|
| 185 |
+
(MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
|
| 186 |
+
(II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),
|
| 187 |
+
(II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),
|
| 188 |
+
(MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),
|
| 189 |
+
(II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 190 |
+
(MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 191 |
+
(II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
|
| 192 |
+
(II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
|
| 193 |
+
(MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),
|
| 194 |
+
(II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
|
| 195 |
+
(MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),
|
| 196 |
+
(II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 197 |
+
(MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
|
| 198 |
+
(II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 199 |
+
(MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
|
| 200 |
+
(II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 201 |
+
(MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
|
| 202 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 203 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
|
| 204 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 205 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
|
| 206 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 207 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
|
| 208 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 209 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
|
| 210 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 211 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
|
| 212 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 213 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
|
| 214 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 215 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
|
| 216 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 217 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
|
| 218 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 219 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
|
| 220 |
+
(II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 221 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
|
| 222 |
+
(II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 223 |
+
(MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
|
| 224 |
+
(II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),
|
| 225 |
+
(MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),
|
| 226 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),
|
| 227 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),
|
| 228 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),
|
| 229 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),
|
| 230 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),
|
| 231 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),
|
| 232 |
+
(II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),
|
| 233 |
+
(MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),
|
| 234 |
+
(II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 235 |
+
(MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
|
| 236 |
+
(II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 237 |
+
(MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
|
| 238 |
+
(II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 239 |
+
(MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
|
| 240 |
+
(II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 241 |
+
(MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
|
| 242 |
+
(II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 243 |
+
(MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
|
| 244 |
+
(II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 245 |
+
(MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
|
| 246 |
+
(II, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 247 |
+
(MM, 3, (1,), 1, (8,), ()): ("P", "P"),
|
| 248 |
+
(II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
|
| 249 |
+
(II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 250 |
+
(MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
|
| 251 |
+
(II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 252 |
+
(MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),
|
| 253 |
+
(II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 254 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
|
| 255 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 256 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
|
| 257 |
+
(II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 258 |
+
(MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
|
| 259 |
+
(II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),
|
| 260 |
+
(II, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 261 |
+
(MM, 6, (1,), 1, (8,), ()): ("L", "L"),
|
| 262 |
+
# JPEG compressed images handled by LibTiff and auto-converted to RGBX
|
| 263 |
+
# Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel
|
| 264 |
+
(II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 265 |
+
(MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
|
| 266 |
+
(II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 267 |
+
(MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)
|
| 271 |
+
|
| 272 |
+
PREFIXES = [
|
| 273 |
+
b"MM\x00\x2A", # Valid TIFF header with big-endian byte order
|
| 274 |
+
b"II\x2A\x00", # Valid TIFF header with little-endian byte order
|
| 275 |
+
b"MM\x2A\x00", # Invalid TIFF header, assume big-endian
|
| 276 |
+
b"II\x00\x2A", # Invalid TIFF header, assume little-endian
|
| 277 |
+
b"MM\x00\x2B", # BigTIFF with big-endian byte order
|
| 278 |
+
b"II\x2B\x00", # BigTIFF with little-endian byte order
|
| 279 |
+
]
|
| 280 |
+
|
| 281 |
+
if not getattr(Image.core, "libtiff_support_custom_tags", True):
|
| 282 |
+
deprecate("Support for LibTIFF earlier than version 4", 12)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _accept(prefix: bytes) -> bool:
|
| 286 |
+
return prefix[:4] in PREFIXES
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _limit_rational(val, max_val):
|
| 290 |
+
inv = abs(val) > 1
|
| 291 |
+
n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
|
| 292 |
+
return n_d[::-1] if inv else n_d
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _limit_signed_rational(val, max_val, min_val):
|
| 296 |
+
frac = Fraction(val)
|
| 297 |
+
n_d = frac.numerator, frac.denominator
|
| 298 |
+
|
| 299 |
+
if min(n_d) < min_val:
|
| 300 |
+
n_d = _limit_rational(val, abs(min_val))
|
| 301 |
+
|
| 302 |
+
if max(n_d) > max_val:
|
| 303 |
+
val = Fraction(*n_d)
|
| 304 |
+
n_d = _limit_rational(val, max_val)
|
| 305 |
+
|
| 306 |
+
return n_d
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
##
|
| 310 |
+
# Wrapper for TIFF IFDs.
|
| 311 |
+
|
| 312 |
+
_load_dispatch = {}
|
| 313 |
+
_write_dispatch = {}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _delegate(op):
|
| 317 |
+
def delegate(self, *args):
|
| 318 |
+
return getattr(self._val, op)(*args)
|
| 319 |
+
|
| 320 |
+
return delegate
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class IFDRational(Rational):
|
| 324 |
+
"""Implements a rational class where 0/0 is a legal value to match
|
| 325 |
+
the in the wild use of exif rationals.
|
| 326 |
+
|
| 327 |
+
e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
""" If the denominator is 0, store this as a float('nan'), otherwise store
|
| 331 |
+
as a fractions.Fraction(). Delegate as appropriate
|
| 332 |
+
|
| 333 |
+
"""
|
| 334 |
+
|
| 335 |
+
__slots__ = ("_numerator", "_denominator", "_val")
|
| 336 |
+
|
| 337 |
+
def __init__(self, value, denominator=1):
|
| 338 |
+
"""
|
| 339 |
+
:param value: either an integer numerator, a
|
| 340 |
+
float/rational/other number, or an IFDRational
|
| 341 |
+
:param denominator: Optional integer denominator
|
| 342 |
+
"""
|
| 343 |
+
if isinstance(value, IFDRational):
|
| 344 |
+
self._numerator = value.numerator
|
| 345 |
+
self._denominator = value.denominator
|
| 346 |
+
self._val = value._val
|
| 347 |
+
return
|
| 348 |
+
|
| 349 |
+
if isinstance(value, Fraction):
|
| 350 |
+
self._numerator = value.numerator
|
| 351 |
+
self._denominator = value.denominator
|
| 352 |
+
else:
|
| 353 |
+
self._numerator = value
|
| 354 |
+
self._denominator = denominator
|
| 355 |
+
|
| 356 |
+
if denominator == 0:
|
| 357 |
+
self._val = float("nan")
|
| 358 |
+
elif denominator == 1:
|
| 359 |
+
self._val = Fraction(value)
|
| 360 |
+
else:
|
| 361 |
+
self._val = Fraction(value, denominator)
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def numerator(self):
|
| 365 |
+
return self._numerator
|
| 366 |
+
|
| 367 |
+
@property
|
| 368 |
+
def denominator(self):
|
| 369 |
+
return self._denominator
|
| 370 |
+
|
| 371 |
+
def limit_rational(self, max_denominator):
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
:param max_denominator: Integer, the maximum denominator value
|
| 375 |
+
:returns: Tuple of (numerator, denominator)
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
if self.denominator == 0:
|
| 379 |
+
return self.numerator, self.denominator
|
| 380 |
+
|
| 381 |
+
f = self._val.limit_denominator(max_denominator)
|
| 382 |
+
return f.numerator, f.denominator
|
| 383 |
+
|
| 384 |
+
def __repr__(self) -> str:
|
| 385 |
+
return str(float(self._val))
|
| 386 |
+
|
| 387 |
+
def __hash__(self) -> int:
|
| 388 |
+
return self._val.__hash__()
|
| 389 |
+
|
| 390 |
+
def __eq__(self, other: object) -> bool:
|
| 391 |
+
val = self._val
|
| 392 |
+
if isinstance(other, IFDRational):
|
| 393 |
+
other = other._val
|
| 394 |
+
if isinstance(other, float):
|
| 395 |
+
val = float(val)
|
| 396 |
+
return val == other
|
| 397 |
+
|
| 398 |
+
def __getstate__(self):
|
| 399 |
+
return [self._val, self._numerator, self._denominator]
|
| 400 |
+
|
| 401 |
+
def __setstate__(self, state):
|
| 402 |
+
IFDRational.__init__(self, 0)
|
| 403 |
+
_val, _numerator, _denominator = state
|
| 404 |
+
self._val = _val
|
| 405 |
+
self._numerator = _numerator
|
| 406 |
+
self._denominator = _denominator
|
| 407 |
+
|
| 408 |
+
""" a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul',
|
| 409 |
+
'truediv', 'rtruediv', 'floordiv', 'rfloordiv',
|
| 410 |
+
'mod','rmod', 'pow','rpow', 'pos', 'neg',
|
| 411 |
+
'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool',
|
| 412 |
+
'ceil', 'floor', 'round']
|
| 413 |
+
print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
|
| 414 |
+
"""
|
| 415 |
+
|
| 416 |
+
__add__ = _delegate("__add__")
|
| 417 |
+
__radd__ = _delegate("__radd__")
|
| 418 |
+
__sub__ = _delegate("__sub__")
|
| 419 |
+
__rsub__ = _delegate("__rsub__")
|
| 420 |
+
__mul__ = _delegate("__mul__")
|
| 421 |
+
__rmul__ = _delegate("__rmul__")
|
| 422 |
+
__truediv__ = _delegate("__truediv__")
|
| 423 |
+
__rtruediv__ = _delegate("__rtruediv__")
|
| 424 |
+
__floordiv__ = _delegate("__floordiv__")
|
| 425 |
+
__rfloordiv__ = _delegate("__rfloordiv__")
|
| 426 |
+
__mod__ = _delegate("__mod__")
|
| 427 |
+
__rmod__ = _delegate("__rmod__")
|
| 428 |
+
__pow__ = _delegate("__pow__")
|
| 429 |
+
__rpow__ = _delegate("__rpow__")
|
| 430 |
+
__pos__ = _delegate("__pos__")
|
| 431 |
+
__neg__ = _delegate("__neg__")
|
| 432 |
+
__abs__ = _delegate("__abs__")
|
| 433 |
+
__trunc__ = _delegate("__trunc__")
|
| 434 |
+
__lt__ = _delegate("__lt__")
|
| 435 |
+
__gt__ = _delegate("__gt__")
|
| 436 |
+
__le__ = _delegate("__le__")
|
| 437 |
+
__ge__ = _delegate("__ge__")
|
| 438 |
+
__bool__ = _delegate("__bool__")
|
| 439 |
+
__ceil__ = _delegate("__ceil__")
|
| 440 |
+
__floor__ = _delegate("__floor__")
|
| 441 |
+
__round__ = _delegate("__round__")
|
| 442 |
+
# Python >= 3.11
|
| 443 |
+
if hasattr(Fraction, "__int__"):
|
| 444 |
+
__int__ = _delegate("__int__")
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _register_loader(idx, size):
|
| 448 |
+
def decorator(func):
|
| 449 |
+
from .TiffTags import TYPES
|
| 450 |
+
|
| 451 |
+
if func.__name__.startswith("load_"):
|
| 452 |
+
TYPES[idx] = func.__name__[5:].replace("_", " ")
|
| 453 |
+
_load_dispatch[idx] = size, func # noqa: F821
|
| 454 |
+
return func
|
| 455 |
+
|
| 456 |
+
return decorator
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _register_writer(idx):
|
| 460 |
+
def decorator(func):
|
| 461 |
+
_write_dispatch[idx] = func # noqa: F821
|
| 462 |
+
return func
|
| 463 |
+
|
| 464 |
+
return decorator
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def _register_basic(idx_fmt_name):
|
| 468 |
+
from .TiffTags import TYPES
|
| 469 |
+
|
| 470 |
+
idx, fmt, name = idx_fmt_name
|
| 471 |
+
TYPES[idx] = name
|
| 472 |
+
size = struct.calcsize(f"={fmt}")
|
| 473 |
+
_load_dispatch[idx] = ( # noqa: F821
|
| 474 |
+
size,
|
| 475 |
+
lambda self, data, legacy_api=True: (
|
| 476 |
+
self._unpack(f"{len(data) // size}{fmt}", data)
|
| 477 |
+
),
|
| 478 |
+
)
|
| 479 |
+
_write_dispatch[idx] = lambda self, *values: ( # noqa: F821
|
| 480 |
+
b"".join(self._pack(fmt, value) for value in values)
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
if TYPE_CHECKING:
|
| 485 |
+
_IFDv2Base = MutableMapping[int, Any]
|
| 486 |
+
else:
|
| 487 |
+
_IFDv2Base = MutableMapping
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class ImageFileDirectory_v2(_IFDv2Base):
|
| 491 |
+
"""This class represents a TIFF tag directory. To speed things up, we
|
| 492 |
+
don't decode tags unless they're asked for.
|
| 493 |
+
|
| 494 |
+
Exposes a dictionary interface of the tags in the directory::
|
| 495 |
+
|
| 496 |
+
ifd = ImageFileDirectory_v2()
|
| 497 |
+
ifd[key] = 'Some Data'
|
| 498 |
+
ifd.tagtype[key] = TiffTags.ASCII
|
| 499 |
+
print(ifd[key])
|
| 500 |
+
'Some Data'
|
| 501 |
+
|
| 502 |
+
Individual values are returned as the strings or numbers, sequences are
|
| 503 |
+
returned as tuples of the values.
|
| 504 |
+
|
| 505 |
+
The tiff metadata type of each item is stored in a dictionary of
|
| 506 |
+
tag types in
|
| 507 |
+
:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
|
| 508 |
+
are read from a tiff file, guessed from the type added, or added
|
| 509 |
+
manually.
|
| 510 |
+
|
| 511 |
+
Data Structures:
|
| 512 |
+
|
| 513 |
+
* ``self.tagtype = {}``
|
| 514 |
+
|
| 515 |
+
* Key: numerical TIFF tag number
|
| 516 |
+
* Value: integer corresponding to the data type from
|
| 517 |
+
:py:data:`.TiffTags.TYPES`
|
| 518 |
+
|
| 519 |
+
.. versionadded:: 3.0.0
|
| 520 |
+
|
| 521 |
+
'Internal' data structures:
|
| 522 |
+
|
| 523 |
+
* ``self._tags_v2 = {}``
|
| 524 |
+
|
| 525 |
+
* Key: numerical TIFF tag number
|
| 526 |
+
* Value: decoded data, as tuple for multiple values
|
| 527 |
+
|
| 528 |
+
* ``self._tagdata = {}``
|
| 529 |
+
|
| 530 |
+
* Key: numerical TIFF tag number
|
| 531 |
+
* Value: undecoded byte string from file
|
| 532 |
+
|
| 533 |
+
* ``self._tags_v1 = {}``
|
| 534 |
+
|
| 535 |
+
* Key: numerical TIFF tag number
|
| 536 |
+
* Value: decoded data in the v1 format
|
| 537 |
+
|
| 538 |
+
Tags will be found in the private attributes ``self._tagdata``, and in
|
| 539 |
+
``self._tags_v2`` once decoded.
|
| 540 |
+
|
| 541 |
+
``self.legacy_api`` is a value for internal use, and shouldn't be changed
|
| 542 |
+
from outside code. In cooperation with
|
| 543 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api``
|
| 544 |
+
is true, then decoded tags will be populated into both ``_tags_v1`` and
|
| 545 |
+
``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF
|
| 546 |
+
save routine. Tags should be read from ``_tags_v1`` if
|
| 547 |
+
``legacy_api == true``.
|
| 548 |
+
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
_load_dispatch: dict[int, Callable[[ImageFileDirectory_v2, bytes, bool], Any]] = {}
|
| 552 |
+
_write_dispatch: dict[int, Callable[..., Any]] = {}
|
| 553 |
+
|
| 554 |
+
def __init__(
|
| 555 |
+
self,
|
| 556 |
+
ifh: bytes = b"II\052\0\0\0\0\0",
|
| 557 |
+
prefix: bytes | None = None,
|
| 558 |
+
group: int | None = None,
|
| 559 |
+
) -> None:
|
| 560 |
+
"""Initialize an ImageFileDirectory.
|
| 561 |
+
|
| 562 |
+
To construct an ImageFileDirectory from a real file, pass the 8-byte
|
| 563 |
+
magic header to the constructor. To only set the endianness, pass it
|
| 564 |
+
as the 'prefix' keyword argument.
|
| 565 |
+
|
| 566 |
+
:param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
|
| 567 |
+
endianness.
|
| 568 |
+
:param prefix: Override the endianness of the file.
|
| 569 |
+
"""
|
| 570 |
+
if not _accept(ifh):
|
| 571 |
+
msg = f"not a TIFF file (header {repr(ifh)} not valid)"
|
| 572 |
+
raise SyntaxError(msg)
|
| 573 |
+
self._prefix = prefix if prefix is not None else ifh[:2]
|
| 574 |
+
if self._prefix == MM:
|
| 575 |
+
self._endian = ">"
|
| 576 |
+
elif self._prefix == II:
|
| 577 |
+
self._endian = "<"
|
| 578 |
+
else:
|
| 579 |
+
msg = "not a TIFF IFD"
|
| 580 |
+
raise SyntaxError(msg)
|
| 581 |
+
self._bigtiff = ifh[2] == 43
|
| 582 |
+
self.group = group
|
| 583 |
+
self.tagtype: dict[int, int] = {}
|
| 584 |
+
""" Dictionary of tag types """
|
| 585 |
+
self.reset()
|
| 586 |
+
(self.next,) = (
|
| 587 |
+
self._unpack("Q", ifh[8:]) if self._bigtiff else self._unpack("L", ifh[4:])
|
| 588 |
+
)
|
| 589 |
+
self._legacy_api = False
|
| 590 |
+
|
| 591 |
+
prefix = property(lambda self: self._prefix)
|
| 592 |
+
offset = property(lambda self: self._offset)
|
| 593 |
+
|
| 594 |
+
@property
|
| 595 |
+
def legacy_api(self) -> bool:
|
| 596 |
+
return self._legacy_api
|
| 597 |
+
|
| 598 |
+
@legacy_api.setter
|
| 599 |
+
def legacy_api(self, value: bool) -> NoReturn:
|
| 600 |
+
msg = "Not allowing setting of legacy api"
|
| 601 |
+
raise Exception(msg)
|
| 602 |
+
|
| 603 |
+
def reset(self) -> None:
|
| 604 |
+
self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false
|
| 605 |
+
self._tags_v2: dict[int, Any] = {} # main tag storage
|
| 606 |
+
self._tagdata: dict[int, bytes] = {}
|
| 607 |
+
self.tagtype = {} # added 2008-06-05 by Florian Hoech
|
| 608 |
+
self._next = None
|
| 609 |
+
self._offset = None
|
| 610 |
+
|
| 611 |
+
def __str__(self) -> str:
|
| 612 |
+
return str(dict(self))
|
| 613 |
+
|
| 614 |
+
def named(self):
|
| 615 |
+
"""
|
| 616 |
+
:returns: dict of name|key: value
|
| 617 |
+
|
| 618 |
+
Returns the complete tag dictionary, with named tags where possible.
|
| 619 |
+
"""
|
| 620 |
+
return {
|
| 621 |
+
TiffTags.lookup(code, self.group).name: value
|
| 622 |
+
for code, value in self.items()
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
def __len__(self) -> int:
|
| 626 |
+
return len(set(self._tagdata) | set(self._tags_v2))
|
| 627 |
+
|
| 628 |
+
def __getitem__(self, tag):
|
| 629 |
+
if tag not in self._tags_v2: # unpack on the fly
|
| 630 |
+
data = self._tagdata[tag]
|
| 631 |
+
typ = self.tagtype[tag]
|
| 632 |
+
size, handler = self._load_dispatch[typ]
|
| 633 |
+
self[tag] = handler(self, data, self.legacy_api) # check type
|
| 634 |
+
val = self._tags_v2[tag]
|
| 635 |
+
if self.legacy_api and not isinstance(val, (tuple, bytes)):
|
| 636 |
+
val = (val,)
|
| 637 |
+
return val
|
| 638 |
+
|
| 639 |
+
def __contains__(self, tag):
|
| 640 |
+
return tag in self._tags_v2 or tag in self._tagdata
|
| 641 |
+
|
| 642 |
+
def __setitem__(self, tag, value):
|
| 643 |
+
self._setitem(tag, value, self.legacy_api)
|
| 644 |
+
|
| 645 |
+
def _setitem(self, tag, value, legacy_api):
|
| 646 |
+
basetypes = (Number, bytes, str)
|
| 647 |
+
|
| 648 |
+
info = TiffTags.lookup(tag, self.group)
|
| 649 |
+
values = [value] if isinstance(value, basetypes) else value
|
| 650 |
+
|
| 651 |
+
if tag not in self.tagtype:
|
| 652 |
+
if info.type:
|
| 653 |
+
self.tagtype[tag] = info.type
|
| 654 |
+
else:
|
| 655 |
+
self.tagtype[tag] = TiffTags.UNDEFINED
|
| 656 |
+
if all(isinstance(v, IFDRational) for v in values):
|
| 657 |
+
self.tagtype[tag] = (
|
| 658 |
+
TiffTags.RATIONAL
|
| 659 |
+
if all(v >= 0 for v in values)
|
| 660 |
+
else TiffTags.SIGNED_RATIONAL
|
| 661 |
+
)
|
| 662 |
+
elif all(isinstance(v, int) for v in values):
|
| 663 |
+
if all(0 <= v < 2**16 for v in values):
|
| 664 |
+
self.tagtype[tag] = TiffTags.SHORT
|
| 665 |
+
elif all(-(2**15) < v < 2**15 for v in values):
|
| 666 |
+
self.tagtype[tag] = TiffTags.SIGNED_SHORT
|
| 667 |
+
else:
|
| 668 |
+
self.tagtype[tag] = (
|
| 669 |
+
TiffTags.LONG
|
| 670 |
+
if all(v >= 0 for v in values)
|
| 671 |
+
else TiffTags.SIGNED_LONG
|
| 672 |
+
)
|
| 673 |
+
elif all(isinstance(v, float) for v in values):
|
| 674 |
+
self.tagtype[tag] = TiffTags.DOUBLE
|
| 675 |
+
elif all(isinstance(v, str) for v in values):
|
| 676 |
+
self.tagtype[tag] = TiffTags.ASCII
|
| 677 |
+
elif all(isinstance(v, bytes) for v in values):
|
| 678 |
+
self.tagtype[tag] = TiffTags.BYTE
|
| 679 |
+
|
| 680 |
+
if self.tagtype[tag] == TiffTags.UNDEFINED:
|
| 681 |
+
values = [
|
| 682 |
+
v.encode("ascii", "replace") if isinstance(v, str) else v
|
| 683 |
+
for v in values
|
| 684 |
+
]
|
| 685 |
+
elif self.tagtype[tag] == TiffTags.RATIONAL:
|
| 686 |
+
values = [float(v) if isinstance(v, int) else v for v in values]
|
| 687 |
+
|
| 688 |
+
is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict)
|
| 689 |
+
if not is_ifd:
|
| 690 |
+
values = tuple(info.cvt_enum(value) for value in values)
|
| 691 |
+
|
| 692 |
+
dest = self._tags_v1 if legacy_api else self._tags_v2
|
| 693 |
+
|
| 694 |
+
# Three branches:
|
| 695 |
+
# Spec'd length == 1, Actual length 1, store as element
|
| 696 |
+
# Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed.
|
| 697 |
+
# No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple.
|
| 698 |
+
# Don't mess with the legacy api, since it's frozen.
|
| 699 |
+
if not is_ifd and (
|
| 700 |
+
(info.length == 1)
|
| 701 |
+
or self.tagtype[tag] == TiffTags.BYTE
|
| 702 |
+
or (info.length is None and len(values) == 1 and not legacy_api)
|
| 703 |
+
):
|
| 704 |
+
# Don't mess with the legacy api, since it's frozen.
|
| 705 |
+
if legacy_api and self.tagtype[tag] in [
|
| 706 |
+
TiffTags.RATIONAL,
|
| 707 |
+
TiffTags.SIGNED_RATIONAL,
|
| 708 |
+
]: # rationals
|
| 709 |
+
values = (values,)
|
| 710 |
+
try:
|
| 711 |
+
(dest[tag],) = values
|
| 712 |
+
except ValueError:
|
| 713 |
+
# We've got a builtin tag with 1 expected entry
|
| 714 |
+
warnings.warn(
|
| 715 |
+
f"Metadata Warning, tag {tag} had too many entries: "
|
| 716 |
+
f"{len(values)}, expected 1"
|
| 717 |
+
)
|
| 718 |
+
dest[tag] = values[0]
|
| 719 |
+
|
| 720 |
+
else:
|
| 721 |
+
# Spec'd length > 1 or undefined
|
| 722 |
+
# Unspec'd, and length > 1
|
| 723 |
+
dest[tag] = values
|
| 724 |
+
|
| 725 |
+
def __delitem__(self, tag: int) -> None:
|
| 726 |
+
self._tags_v2.pop(tag, None)
|
| 727 |
+
self._tags_v1.pop(tag, None)
|
| 728 |
+
self._tagdata.pop(tag, None)
|
| 729 |
+
|
| 730 |
+
def __iter__(self):
|
| 731 |
+
return iter(set(self._tagdata) | set(self._tags_v2))
|
| 732 |
+
|
| 733 |
+
def _unpack(self, fmt, data):
|
| 734 |
+
return struct.unpack(self._endian + fmt, data)
|
| 735 |
+
|
| 736 |
+
def _pack(self, fmt, *values):
|
| 737 |
+
return struct.pack(self._endian + fmt, *values)
|
| 738 |
+
|
| 739 |
+
list(
|
| 740 |
+
map(
|
| 741 |
+
_register_basic,
|
| 742 |
+
[
|
| 743 |
+
(TiffTags.SHORT, "H", "short"),
|
| 744 |
+
(TiffTags.LONG, "L", "long"),
|
| 745 |
+
(TiffTags.SIGNED_BYTE, "b", "signed byte"),
|
| 746 |
+
(TiffTags.SIGNED_SHORT, "h", "signed short"),
|
| 747 |
+
(TiffTags.SIGNED_LONG, "l", "signed long"),
|
| 748 |
+
(TiffTags.FLOAT, "f", "float"),
|
| 749 |
+
(TiffTags.DOUBLE, "d", "double"),
|
| 750 |
+
(TiffTags.IFD, "L", "long"),
|
| 751 |
+
(TiffTags.LONG8, "Q", "long8"),
|
| 752 |
+
],
|
| 753 |
+
)
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
@_register_loader(1, 1) # Basic type, except for the legacy API.
|
| 757 |
+
def load_byte(self, data, legacy_api=True):
|
| 758 |
+
return data
|
| 759 |
+
|
| 760 |
+
@_register_writer(1) # Basic type, except for the legacy API.
|
| 761 |
+
def write_byte(self, data):
|
| 762 |
+
if isinstance(data, IFDRational):
|
| 763 |
+
data = int(data)
|
| 764 |
+
if isinstance(data, int):
|
| 765 |
+
data = bytes((data,))
|
| 766 |
+
return data
|
| 767 |
+
|
| 768 |
+
@_register_loader(2, 1)
|
| 769 |
+
def load_string(self, data, legacy_api=True):
|
| 770 |
+
if data.endswith(b"\0"):
|
| 771 |
+
data = data[:-1]
|
| 772 |
+
return data.decode("latin-1", "replace")
|
| 773 |
+
|
| 774 |
+
@_register_writer(2)
|
| 775 |
+
def write_string(self, value):
|
| 776 |
+
# remerge of https://github.com/python-pillow/Pillow/pull/1416
|
| 777 |
+
if isinstance(value, int):
|
| 778 |
+
value = str(value)
|
| 779 |
+
if not isinstance(value, bytes):
|
| 780 |
+
value = value.encode("ascii", "replace")
|
| 781 |
+
return value + b"\0"
|
| 782 |
+
|
| 783 |
+
@_register_loader(5, 8)
|
| 784 |
+
def load_rational(self, data, legacy_api=True):
|
| 785 |
+
vals = self._unpack(f"{len(data) // 4}L", data)
|
| 786 |
+
|
| 787 |
+
def combine(a, b):
|
| 788 |
+
return (a, b) if legacy_api else IFDRational(a, b)
|
| 789 |
+
|
| 790 |
+
return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
|
| 791 |
+
|
| 792 |
+
@_register_writer(5)
|
| 793 |
+
def write_rational(self, *values):
|
| 794 |
+
return b"".join(
|
| 795 |
+
self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
@_register_loader(7, 1)
|
| 799 |
+
def load_undefined(self, data, legacy_api=True):
|
| 800 |
+
return data
|
| 801 |
+
|
| 802 |
+
@_register_writer(7)
|
| 803 |
+
def write_undefined(self, value):
|
| 804 |
+
if isinstance(value, IFDRational):
|
| 805 |
+
value = int(value)
|
| 806 |
+
if isinstance(value, int):
|
| 807 |
+
value = str(value).encode("ascii", "replace")
|
| 808 |
+
return value
|
| 809 |
+
|
| 810 |
+
@_register_loader(10, 8)
|
| 811 |
+
def load_signed_rational(self, data, legacy_api=True):
|
| 812 |
+
vals = self._unpack(f"{len(data) // 4}l", data)
|
| 813 |
+
|
| 814 |
+
def combine(a, b):
|
| 815 |
+
return (a, b) if legacy_api else IFDRational(a, b)
|
| 816 |
+
|
| 817 |
+
return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
|
| 818 |
+
|
| 819 |
+
@_register_writer(10)
|
| 820 |
+
def write_signed_rational(self, *values):
|
| 821 |
+
return b"".join(
|
| 822 |
+
self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31)))
|
| 823 |
+
for frac in values
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
def _ensure_read(self, fp, size):
|
| 827 |
+
ret = fp.read(size)
|
| 828 |
+
if len(ret) != size:
|
| 829 |
+
msg = (
|
| 830 |
+
"Corrupt EXIF data. "
|
| 831 |
+
f"Expecting to read {size} bytes but only got {len(ret)}. "
|
| 832 |
+
)
|
| 833 |
+
raise OSError(msg)
|
| 834 |
+
return ret
|
| 835 |
+
|
| 836 |
+
def load(self, fp):
|
| 837 |
+
self.reset()
|
| 838 |
+
self._offset = fp.tell()
|
| 839 |
+
|
| 840 |
+
try:
|
| 841 |
+
tag_count = (
|
| 842 |
+
self._unpack("Q", self._ensure_read(fp, 8))
|
| 843 |
+
if self._bigtiff
|
| 844 |
+
else self._unpack("H", self._ensure_read(fp, 2))
|
| 845 |
+
)[0]
|
| 846 |
+
for i in range(tag_count):
|
| 847 |
+
tag, typ, count, data = (
|
| 848 |
+
self._unpack("HHQ8s", self._ensure_read(fp, 20))
|
| 849 |
+
if self._bigtiff
|
| 850 |
+
else self._unpack("HHL4s", self._ensure_read(fp, 12))
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
tagname = TiffTags.lookup(tag, self.group).name
|
| 854 |
+
typname = TYPES.get(typ, "unknown")
|
| 855 |
+
msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})"
|
| 856 |
+
|
| 857 |
+
try:
|
| 858 |
+
unit_size, handler = self._load_dispatch[typ]
|
| 859 |
+
except KeyError:
|
| 860 |
+
logger.debug("%s - unsupported type %s", msg, typ)
|
| 861 |
+
continue # ignore unsupported type
|
| 862 |
+
size = count * unit_size
|
| 863 |
+
if size > (8 if self._bigtiff else 4):
|
| 864 |
+
here = fp.tell()
|
| 865 |
+
(offset,) = self._unpack("Q" if self._bigtiff else "L", data)
|
| 866 |
+
msg += f" Tag Location: {here} - Data Location: {offset}"
|
| 867 |
+
fp.seek(offset)
|
| 868 |
+
data = ImageFile._safe_read(fp, size)
|
| 869 |
+
fp.seek(here)
|
| 870 |
+
else:
|
| 871 |
+
data = data[:size]
|
| 872 |
+
|
| 873 |
+
if len(data) != size:
|
| 874 |
+
warnings.warn(
|
| 875 |
+
"Possibly corrupt EXIF data. "
|
| 876 |
+
f"Expecting to read {size} bytes but only got {len(data)}."
|
| 877 |
+
f" Skipping tag {tag}"
|
| 878 |
+
)
|
| 879 |
+
logger.debug(msg)
|
| 880 |
+
continue
|
| 881 |
+
|
| 882 |
+
if not data:
|
| 883 |
+
logger.debug(msg)
|
| 884 |
+
continue
|
| 885 |
+
|
| 886 |
+
self._tagdata[tag] = data
|
| 887 |
+
self.tagtype[tag] = typ
|
| 888 |
+
|
| 889 |
+
msg += " - value: " + (
|
| 890 |
+
"<table: %d bytes>" % size if size > 32 else repr(data)
|
| 891 |
+
)
|
| 892 |
+
logger.debug(msg)
|
| 893 |
+
|
| 894 |
+
(self.next,) = (
|
| 895 |
+
self._unpack("Q", self._ensure_read(fp, 8))
|
| 896 |
+
if self._bigtiff
|
| 897 |
+
else self._unpack("L", self._ensure_read(fp, 4))
|
| 898 |
+
)
|
| 899 |
+
except OSError as msg:
|
| 900 |
+
warnings.warn(str(msg))
|
| 901 |
+
return
|
| 902 |
+
|
| 903 |
+
def tobytes(self, offset=0):
|
| 904 |
+
# FIXME What about tagdata?
|
| 905 |
+
result = self._pack("H", len(self._tags_v2))
|
| 906 |
+
|
| 907 |
+
entries = []
|
| 908 |
+
offset = offset + len(result) + len(self._tags_v2) * 12 + 4
|
| 909 |
+
stripoffsets = None
|
| 910 |
+
|
| 911 |
+
# pass 1: convert tags to binary format
|
| 912 |
+
# always write tags in ascending order
|
| 913 |
+
for tag, value in sorted(self._tags_v2.items()):
|
| 914 |
+
if tag == STRIPOFFSETS:
|
| 915 |
+
stripoffsets = len(entries)
|
| 916 |
+
typ = self.tagtype.get(tag)
|
| 917 |
+
logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))
|
| 918 |
+
is_ifd = typ == TiffTags.LONG and isinstance(value, dict)
|
| 919 |
+
if is_ifd:
|
| 920 |
+
if self._endian == "<":
|
| 921 |
+
ifh = b"II\x2A\x00\x08\x00\x00\x00"
|
| 922 |
+
else:
|
| 923 |
+
ifh = b"MM\x00\x2A\x00\x00\x00\x08"
|
| 924 |
+
ifd = ImageFileDirectory_v2(ifh, group=tag)
|
| 925 |
+
values = self._tags_v2[tag]
|
| 926 |
+
for ifd_tag, ifd_value in values.items():
|
| 927 |
+
ifd[ifd_tag] = ifd_value
|
| 928 |
+
data = ifd.tobytes(offset)
|
| 929 |
+
else:
|
| 930 |
+
values = value if isinstance(value, tuple) else (value,)
|
| 931 |
+
data = self._write_dispatch[typ](self, *values)
|
| 932 |
+
|
| 933 |
+
tagname = TiffTags.lookup(tag, self.group).name
|
| 934 |
+
typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")
|
| 935 |
+
msg = f"save: {tagname} ({tag}) - type: {typname} ({typ})"
|
| 936 |
+
msg += " - value: " + (
|
| 937 |
+
"<table: %d bytes>" % len(data) if len(data) >= 16 else str(values)
|
| 938 |
+
)
|
| 939 |
+
logger.debug(msg)
|
| 940 |
+
|
| 941 |
+
# count is sum of lengths for string and arbitrary data
|
| 942 |
+
if is_ifd:
|
| 943 |
+
count = 1
|
| 944 |
+
elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
|
| 945 |
+
count = len(data)
|
| 946 |
+
else:
|
| 947 |
+
count = len(values)
|
| 948 |
+
# figure out if data fits into the entry
|
| 949 |
+
if len(data) <= 4:
|
| 950 |
+
entries.append((tag, typ, count, data.ljust(4, b"\0"), b""))
|
| 951 |
+
else:
|
| 952 |
+
entries.append((tag, typ, count, self._pack("L", offset), data))
|
| 953 |
+
offset += (len(data) + 1) // 2 * 2 # pad to word
|
| 954 |
+
|
| 955 |
+
# update strip offset data to point beyond auxiliary data
|
| 956 |
+
if stripoffsets is not None:
|
| 957 |
+
tag, typ, count, value, data = entries[stripoffsets]
|
| 958 |
+
if data:
|
| 959 |
+
msg = "multistrip support not yet implemented"
|
| 960 |
+
raise NotImplementedError(msg)
|
| 961 |
+
value = self._pack("L", self._unpack("L", value)[0] + offset)
|
| 962 |
+
entries[stripoffsets] = tag, typ, count, value, data
|
| 963 |
+
|
| 964 |
+
# pass 2: write entries to file
|
| 965 |
+
for tag, typ, count, value, data in entries:
|
| 966 |
+
logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))
|
| 967 |
+
result += self._pack("HHL4s", tag, typ, count, value)
|
| 968 |
+
|
| 969 |
+
# -- overwrite here for multi-page --
|
| 970 |
+
result += b"\0\0\0\0" # end of entries
|
| 971 |
+
|
| 972 |
+
# pass 3: write auxiliary data to file
|
| 973 |
+
for tag, typ, count, value, data in entries:
|
| 974 |
+
result += data
|
| 975 |
+
if len(data) & 1:
|
| 976 |
+
result += b"\0"
|
| 977 |
+
|
| 978 |
+
return result
|
| 979 |
+
|
| 980 |
+
def save(self, fp):
|
| 981 |
+
if fp.tell() == 0: # skip TIFF header on subsequent pages
|
| 982 |
+
# tiff header -- PIL always starts the first IFD at offset 8
|
| 983 |
+
fp.write(self._prefix + self._pack("HL", 42, 8))
|
| 984 |
+
|
| 985 |
+
offset = fp.tell()
|
| 986 |
+
result = self.tobytes(offset)
|
| 987 |
+
fp.write(result)
|
| 988 |
+
return offset + len(result)
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
ImageFileDirectory_v2._load_dispatch = _load_dispatch
|
| 992 |
+
ImageFileDirectory_v2._write_dispatch = _write_dispatch
|
| 993 |
+
for idx, name in TYPES.items():
|
| 994 |
+
name = name.replace(" ", "_")
|
| 995 |
+
setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])
|
| 996 |
+
setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])
|
| 997 |
+
del _load_dispatch, _write_dispatch, idx, name
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
# Legacy ImageFileDirectory support.
|
| 1001 |
+
class ImageFileDirectory_v1(ImageFileDirectory_v2):
|
| 1002 |
+
"""This class represents the **legacy** interface to a TIFF tag directory.
|
| 1003 |
+
|
| 1004 |
+
Exposes a dictionary interface of the tags in the directory::
|
| 1005 |
+
|
| 1006 |
+
ifd = ImageFileDirectory_v1()
|
| 1007 |
+
ifd[key] = 'Some Data'
|
| 1008 |
+
ifd.tagtype[key] = TiffTags.ASCII
|
| 1009 |
+
print(ifd[key])
|
| 1010 |
+
('Some Data',)
|
| 1011 |
+
|
| 1012 |
+
Also contains a dictionary of tag types as read from the tiff image file,
|
| 1013 |
+
:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.
|
| 1014 |
+
|
| 1015 |
+
Values are returned as a tuple.
|
| 1016 |
+
|
| 1017 |
+
.. deprecated:: 3.0.0
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
def __init__(self, *args, **kwargs):
|
| 1021 |
+
super().__init__(*args, **kwargs)
|
| 1022 |
+
self._legacy_api = True
|
| 1023 |
+
|
| 1024 |
+
tags = property(lambda self: self._tags_v1)
|
| 1025 |
+
tagdata = property(lambda self: self._tagdata)
|
| 1026 |
+
|
| 1027 |
+
# defined in ImageFileDirectory_v2
|
| 1028 |
+
tagtype: dict[int, int]
|
| 1029 |
+
"""Dictionary of tag types"""
|
| 1030 |
+
|
| 1031 |
+
@classmethod
|
| 1032 |
+
def from_v2(cls, original):
|
| 1033 |
+
"""Returns an
|
| 1034 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1035 |
+
instance with the same data as is contained in the original
|
| 1036 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1037 |
+
instance.
|
| 1038 |
+
|
| 1039 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1040 |
+
|
| 1041 |
+
"""
|
| 1042 |
+
|
| 1043 |
+
ifd = cls(prefix=original.prefix)
|
| 1044 |
+
ifd._tagdata = original._tagdata
|
| 1045 |
+
ifd.tagtype = original.tagtype
|
| 1046 |
+
ifd.next = original.next # an indicator for multipage tiffs
|
| 1047 |
+
return ifd
|
| 1048 |
+
|
| 1049 |
+
def to_v2(self) -> ImageFileDirectory_v2:
|
| 1050 |
+
"""Returns an
|
| 1051 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1052 |
+
instance with the same data as is contained in the original
|
| 1053 |
+
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
|
| 1054 |
+
instance.
|
| 1055 |
+
|
| 1056 |
+
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
|
| 1057 |
+
|
| 1058 |
+
"""
|
| 1059 |
+
|
| 1060 |
+
ifd = ImageFileDirectory_v2(prefix=self.prefix)
|
| 1061 |
+
ifd._tagdata = dict(self._tagdata)
|
| 1062 |
+
ifd.tagtype = dict(self.tagtype)
|
| 1063 |
+
ifd._tags_v2 = dict(self._tags_v2)
|
| 1064 |
+
return ifd
|
| 1065 |
+
|
| 1066 |
+
def __contains__(self, tag):
|
| 1067 |
+
return tag in self._tags_v1 or tag in self._tagdata
|
| 1068 |
+
|
| 1069 |
+
def __len__(self) -> int:
|
| 1070 |
+
return len(set(self._tagdata) | set(self._tags_v1))
|
| 1071 |
+
|
| 1072 |
+
def __iter__(self):
|
| 1073 |
+
return iter(set(self._tagdata) | set(self._tags_v1))
|
| 1074 |
+
|
| 1075 |
+
def __setitem__(self, tag, value):
|
| 1076 |
+
for legacy_api in (False, True):
|
| 1077 |
+
self._setitem(tag, value, legacy_api)
|
| 1078 |
+
|
| 1079 |
+
def __getitem__(self, tag):
|
| 1080 |
+
if tag not in self._tags_v1: # unpack on the fly
|
| 1081 |
+
data = self._tagdata[tag]
|
| 1082 |
+
typ = self.tagtype[tag]
|
| 1083 |
+
size, handler = self._load_dispatch[typ]
|
| 1084 |
+
for legacy in (False, True):
|
| 1085 |
+
self._setitem(tag, handler(self, data, legacy), legacy)
|
| 1086 |
+
val = self._tags_v1[tag]
|
| 1087 |
+
if not isinstance(val, (tuple, bytes)):
|
| 1088 |
+
val = (val,)
|
| 1089 |
+
return val
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
# undone -- switch this pointer when IFD_LEGACY_API == False
|
| 1093 |
+
ImageFileDirectory = ImageFileDirectory_v1
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
##
|
| 1097 |
+
# Image plugin for TIFF files.
|
| 1098 |
+
|
| 1099 |
+
|
| 1100 |
+
class TiffImageFile(ImageFile.ImageFile):
|
| 1101 |
+
format = "TIFF"
|
| 1102 |
+
format_description = "Adobe TIFF"
|
| 1103 |
+
_close_exclusive_fp_after_loading = False
|
| 1104 |
+
|
| 1105 |
+
def __init__(self, fp=None, filename=None):
|
| 1106 |
+
self.tag_v2 = None
|
| 1107 |
+
""" Image file directory (tag dictionary) """
|
| 1108 |
+
|
| 1109 |
+
self.tag = None
|
| 1110 |
+
""" Legacy tag entries """
|
| 1111 |
+
|
| 1112 |
+
super().__init__(fp, filename)
|
| 1113 |
+
|
| 1114 |
+
def _open(self) -> None:
|
| 1115 |
+
"""Open the first image in a TIFF file"""
|
| 1116 |
+
|
| 1117 |
+
# Header
|
| 1118 |
+
ifh = self.fp.read(8)
|
| 1119 |
+
if ifh[2] == 43:
|
| 1120 |
+
ifh += self.fp.read(8)
|
| 1121 |
+
|
| 1122 |
+
self.tag_v2 = ImageFileDirectory_v2(ifh)
|
| 1123 |
+
|
| 1124 |
+
# legacy IFD entries will be filled in later
|
| 1125 |
+
self.ifd = None
|
| 1126 |
+
|
| 1127 |
+
# setup frame pointers
|
| 1128 |
+
self.__first = self.__next = self.tag_v2.next
|
| 1129 |
+
self.__frame = -1
|
| 1130 |
+
self._fp = self.fp
|
| 1131 |
+
self._frame_pos: list[int] = []
|
| 1132 |
+
self._n_frames: int | None = None
|
| 1133 |
+
|
| 1134 |
+
logger.debug("*** TiffImageFile._open ***")
|
| 1135 |
+
logger.debug("- __first: %s", self.__first)
|
| 1136 |
+
logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)
|
| 1137 |
+
|
| 1138 |
+
# and load the first frame
|
| 1139 |
+
self._seek(0)
|
| 1140 |
+
|
| 1141 |
+
@property
|
| 1142 |
+
def n_frames(self):
|
| 1143 |
+
if self._n_frames is None:
|
| 1144 |
+
current = self.tell()
|
| 1145 |
+
self._seek(len(self._frame_pos))
|
| 1146 |
+
while self._n_frames is None:
|
| 1147 |
+
self._seek(self.tell() + 1)
|
| 1148 |
+
self.seek(current)
|
| 1149 |
+
return self._n_frames
|
| 1150 |
+
|
| 1151 |
+
def seek(self, frame: int) -> None:
|
| 1152 |
+
"""Select a given frame as current image"""
|
| 1153 |
+
if not self._seek_check(frame):
|
| 1154 |
+
return
|
| 1155 |
+
self._seek(frame)
|
| 1156 |
+
# Create a new core image object on second and
|
| 1157 |
+
# subsequent frames in the image. Image may be
|
| 1158 |
+
# different size/mode.
|
| 1159 |
+
Image._decompression_bomb_check(self.size)
|
| 1160 |
+
self.im = Image.core.new(self.mode, self.size)
|
| 1161 |
+
|
| 1162 |
+
def _seek(self, frame: int) -> None:
|
| 1163 |
+
self.fp = self._fp
|
| 1164 |
+
|
| 1165 |
+
# reset buffered io handle in case fp
|
| 1166 |
+
# was passed to libtiff, invalidating the buffer
|
| 1167 |
+
self.fp.tell()
|
| 1168 |
+
|
| 1169 |
+
while len(self._frame_pos) <= frame:
|
| 1170 |
+
if not self.__next:
|
| 1171 |
+
msg = "no more images in TIFF file"
|
| 1172 |
+
raise EOFError(msg)
|
| 1173 |
+
logger.debug(
|
| 1174 |
+
"Seeking to frame %s, on frame %s, __next %s, location: %s",
|
| 1175 |
+
frame,
|
| 1176 |
+
self.__frame,
|
| 1177 |
+
self.__next,
|
| 1178 |
+
self.fp.tell(),
|
| 1179 |
+
)
|
| 1180 |
+
if self.__next >= 2**63:
|
| 1181 |
+
msg = "Unable to seek to frame"
|
| 1182 |
+
raise ValueError(msg)
|
| 1183 |
+
self.fp.seek(self.__next)
|
| 1184 |
+
self._frame_pos.append(self.__next)
|
| 1185 |
+
logger.debug("Loading tags, location: %s", self.fp.tell())
|
| 1186 |
+
self.tag_v2.load(self.fp)
|
| 1187 |
+
if self.tag_v2.next in self._frame_pos:
|
| 1188 |
+
# This IFD has already been processed
|
| 1189 |
+
# Declare this to be the end of the image
|
| 1190 |
+
self.__next = 0
|
| 1191 |
+
else:
|
| 1192 |
+
self.__next = self.tag_v2.next
|
| 1193 |
+
if self.__next == 0:
|
| 1194 |
+
self._n_frames = frame + 1
|
| 1195 |
+
if len(self._frame_pos) == 1:
|
| 1196 |
+
self.is_animated = self.__next != 0
|
| 1197 |
+
self.__frame += 1
|
| 1198 |
+
self.fp.seek(self._frame_pos[frame])
|
| 1199 |
+
self.tag_v2.load(self.fp)
|
| 1200 |
+
if XMP in self.tag_v2:
|
| 1201 |
+
self.info["xmp"] = self.tag_v2[XMP]
|
| 1202 |
+
elif "xmp" in self.info:
|
| 1203 |
+
del self.info["xmp"]
|
| 1204 |
+
self._reload_exif()
|
| 1205 |
+
# fill the legacy tag/ifd entries
|
| 1206 |
+
self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
|
| 1207 |
+
self.__frame = frame
|
| 1208 |
+
self._setup()
|
| 1209 |
+
|
| 1210 |
+
def tell(self) -> int:
|
| 1211 |
+
"""Return the current frame number"""
|
| 1212 |
+
return self.__frame
|
| 1213 |
+
|
| 1214 |
+
def get_photoshop_blocks(self):
|
| 1215 |
+
"""
|
| 1216 |
+
Returns a dictionary of Photoshop "Image Resource Blocks".
|
| 1217 |
+
The keys are the image resource ID. For more information, see
|
| 1218 |
+
https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727
|
| 1219 |
+
|
| 1220 |
+
:returns: Photoshop "Image Resource Blocks" in a dictionary.
|
| 1221 |
+
"""
|
| 1222 |
+
blocks = {}
|
| 1223 |
+
val = self.tag_v2.get(ExifTags.Base.ImageResources)
|
| 1224 |
+
if val:
|
| 1225 |
+
while val[:4] == b"8BIM":
|
| 1226 |
+
id = i16(val[4:6])
|
| 1227 |
+
n = math.ceil((val[6] + 1) / 2) * 2
|
| 1228 |
+
size = i32(val[6 + n : 10 + n])
|
| 1229 |
+
data = val[10 + n : 10 + n + size]
|
| 1230 |
+
blocks[id] = {"data": data}
|
| 1231 |
+
|
| 1232 |
+
val = val[math.ceil((10 + n + size) / 2) * 2 :]
|
| 1233 |
+
return blocks
|
| 1234 |
+
|
| 1235 |
+
def load(self):
|
| 1236 |
+
if self.tile and self.use_load_libtiff:
|
| 1237 |
+
return self._load_libtiff()
|
| 1238 |
+
return super().load()
|
| 1239 |
+
|
| 1240 |
+
def load_end(self) -> None:
|
| 1241 |
+
# allow closing if we're on the first frame, there's no next
|
| 1242 |
+
# This is the ImageFile.load path only, libtiff specific below.
|
| 1243 |
+
if not self.is_animated:
|
| 1244 |
+
self._close_exclusive_fp_after_loading = True
|
| 1245 |
+
|
| 1246 |
+
# reset buffered io handle in case fp
|
| 1247 |
+
# was passed to libtiff, invalidating the buffer
|
| 1248 |
+
self.fp.tell()
|
| 1249 |
+
|
| 1250 |
+
# load IFD data from fp before it is closed
|
| 1251 |
+
exif = self.getexif()
|
| 1252 |
+
for key in TiffTags.TAGS_V2_GROUPS:
|
| 1253 |
+
if key not in exif:
|
| 1254 |
+
continue
|
| 1255 |
+
exif.get_ifd(key)
|
| 1256 |
+
|
| 1257 |
+
ImageOps.exif_transpose(self, in_place=True)
|
| 1258 |
+
if ExifTags.Base.Orientation in self.tag_v2:
|
| 1259 |
+
del self.tag_v2[ExifTags.Base.Orientation]
|
| 1260 |
+
|
| 1261 |
+
def _load_libtiff(self):
|
| 1262 |
+
"""Overload method triggered when we detect a compressed tiff
|
| 1263 |
+
Calls out to libtiff"""
|
| 1264 |
+
|
| 1265 |
+
Image.Image.load(self)
|
| 1266 |
+
|
| 1267 |
+
self.load_prepare()
|
| 1268 |
+
|
| 1269 |
+
if not len(self.tile) == 1:
|
| 1270 |
+
msg = "Not exactly one tile"
|
| 1271 |
+
raise OSError(msg)
|
| 1272 |
+
|
| 1273 |
+
# (self._compression, (extents tuple),
|
| 1274 |
+
# 0, (rawmode, self._compression, fp))
|
| 1275 |
+
extents = self.tile[0][1]
|
| 1276 |
+
args = list(self.tile[0][3])
|
| 1277 |
+
|
| 1278 |
+
# To be nice on memory footprint, if there's a
|
| 1279 |
+
# file descriptor, use that instead of reading
|
| 1280 |
+
# into a string in python.
|
| 1281 |
+
try:
|
| 1282 |
+
fp = hasattr(self.fp, "fileno") and self.fp.fileno()
|
| 1283 |
+
# flush the file descriptor, prevents error on pypy 2.4+
|
| 1284 |
+
# should also eliminate the need for fp.tell
|
| 1285 |
+
# in _seek
|
| 1286 |
+
if hasattr(self.fp, "flush"):
|
| 1287 |
+
self.fp.flush()
|
| 1288 |
+
except OSError:
|
| 1289 |
+
# io.BytesIO have a fileno, but returns an OSError if
|
| 1290 |
+
# it doesn't use a file descriptor.
|
| 1291 |
+
fp = False
|
| 1292 |
+
|
| 1293 |
+
if fp:
|
| 1294 |
+
args[2] = fp
|
| 1295 |
+
|
| 1296 |
+
decoder = Image._getdecoder(
|
| 1297 |
+
self.mode, "libtiff", tuple(args), self.decoderconfig
|
| 1298 |
+
)
|
| 1299 |
+
try:
|
| 1300 |
+
decoder.setimage(self.im, extents)
|
| 1301 |
+
except ValueError as e:
|
| 1302 |
+
msg = "Couldn't set the image"
|
| 1303 |
+
raise OSError(msg) from e
|
| 1304 |
+
|
| 1305 |
+
close_self_fp = self._exclusive_fp and not self.is_animated
|
| 1306 |
+
if hasattr(self.fp, "getvalue"):
|
| 1307 |
+
# We've got a stringio like thing passed in. Yay for all in memory.
|
| 1308 |
+
# The decoder needs the entire file in one shot, so there's not
|
| 1309 |
+
# a lot we can do here other than give it the entire file.
|
| 1310 |
+
# unless we could do something like get the address of the
|
| 1311 |
+
# underlying string for stringio.
|
| 1312 |
+
#
|
| 1313 |
+
# Rearranging for supporting byteio items, since they have a fileno
|
| 1314 |
+
# that returns an OSError if there's no underlying fp. Easier to
|
| 1315 |
+
# deal with here by reordering.
|
| 1316 |
+
logger.debug("have getvalue. just sending in a string from getvalue")
|
| 1317 |
+
n, err = decoder.decode(self.fp.getvalue())
|
| 1318 |
+
elif fp:
|
| 1319 |
+
# we've got a actual file on disk, pass in the fp.
|
| 1320 |
+
logger.debug("have fileno, calling fileno version of the decoder.")
|
| 1321 |
+
if not close_self_fp:
|
| 1322 |
+
self.fp.seek(0)
|
| 1323 |
+
# 4 bytes, otherwise the trace might error out
|
| 1324 |
+
n, err = decoder.decode(b"fpfp")
|
| 1325 |
+
else:
|
| 1326 |
+
# we have something else.
|
| 1327 |
+
logger.debug("don't have fileno or getvalue. just reading")
|
| 1328 |
+
self.fp.seek(0)
|
| 1329 |
+
# UNDONE -- so much for that buffer size thing.
|
| 1330 |
+
n, err = decoder.decode(self.fp.read())
|
| 1331 |
+
|
| 1332 |
+
self.tile = []
|
| 1333 |
+
self.readonly = 0
|
| 1334 |
+
|
| 1335 |
+
self.load_end()
|
| 1336 |
+
|
| 1337 |
+
if close_self_fp:
|
| 1338 |
+
self.fp.close()
|
| 1339 |
+
self.fp = None # might be shared
|
| 1340 |
+
|
| 1341 |
+
if err < 0:
|
| 1342 |
+
raise OSError(err)
|
| 1343 |
+
|
| 1344 |
+
return Image.Image.load(self)
|
| 1345 |
+
|
| 1346 |
+
def _setup(self):
|
| 1347 |
+
"""Setup this image object based on current tags"""
|
| 1348 |
+
|
| 1349 |
+
if 0xBC01 in self.tag_v2:
|
| 1350 |
+
msg = "Windows Media Photo files not yet supported"
|
| 1351 |
+
raise OSError(msg)
|
| 1352 |
+
|
| 1353 |
+
# extract relevant tags
|
| 1354 |
+
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
|
| 1355 |
+
self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
|
| 1356 |
+
|
| 1357 |
+
# photometric is a required tag, but not everyone is reading
|
| 1358 |
+
# the specification
|
| 1359 |
+
photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
|
| 1360 |
+
|
| 1361 |
+
# old style jpeg compression images most certainly are YCbCr
|
| 1362 |
+
if self._compression == "tiff_jpeg":
|
| 1363 |
+
photo = 6
|
| 1364 |
+
|
| 1365 |
+
fillorder = self.tag_v2.get(FILLORDER, 1)
|
| 1366 |
+
|
| 1367 |
+
logger.debug("*** Summary ***")
|
| 1368 |
+
logger.debug("- compression: %s", self._compression)
|
| 1369 |
+
logger.debug("- photometric_interpretation: %s", photo)
|
| 1370 |
+
logger.debug("- planar_configuration: %s", self._planar_configuration)
|
| 1371 |
+
logger.debug("- fill_order: %s", fillorder)
|
| 1372 |
+
logger.debug("- YCbCr subsampling: %s", self.tag.get(YCBCRSUBSAMPLING))
|
| 1373 |
+
|
| 1374 |
+
# size
|
| 1375 |
+
xsize = int(self.tag_v2.get(IMAGEWIDTH))
|
| 1376 |
+
ysize = int(self.tag_v2.get(IMAGELENGTH))
|
| 1377 |
+
self._size = xsize, ysize
|
| 1378 |
+
|
| 1379 |
+
logger.debug("- size: %s", self.size)
|
| 1380 |
+
|
| 1381 |
+
sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))
|
| 1382 |
+
if len(sample_format) > 1 and max(sample_format) == min(sample_format) == 1:
|
| 1383 |
+
# SAMPLEFORMAT is properly per band, so an RGB image will
|
| 1384 |
+
# be (1,1,1). But, we don't support per band pixel types,
|
| 1385 |
+
# and anything more than one band is a uint8. So, just
|
| 1386 |
+
# take the first element. Revisit this if adding support
|
| 1387 |
+
# for more exotic images.
|
| 1388 |
+
sample_format = (1,)
|
| 1389 |
+
|
| 1390 |
+
bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
|
| 1391 |
+
extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
|
| 1392 |
+
if photo in (2, 6, 8): # RGB, YCbCr, LAB
|
| 1393 |
+
bps_count = 3
|
| 1394 |
+
elif photo == 5: # CMYK
|
| 1395 |
+
bps_count = 4
|
| 1396 |
+
else:
|
| 1397 |
+
bps_count = 1
|
| 1398 |
+
bps_count += len(extra_tuple)
|
| 1399 |
+
bps_actual_count = len(bps_tuple)
|
| 1400 |
+
samples_per_pixel = self.tag_v2.get(
|
| 1401 |
+
SAMPLESPERPIXEL,
|
| 1402 |
+
3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
|
| 1403 |
+
)
|
| 1404 |
+
|
| 1405 |
+
if samples_per_pixel > MAX_SAMPLESPERPIXEL:
|
| 1406 |
+
# DOS check, samples_per_pixel can be a Long, and we extend the tuple below
|
| 1407 |
+
logger.error(
|
| 1408 |
+
"More samples per pixel than can be decoded: %s", samples_per_pixel
|
| 1409 |
+
)
|
| 1410 |
+
msg = "Invalid value for samples per pixel"
|
| 1411 |
+
raise SyntaxError(msg)
|
| 1412 |
+
|
| 1413 |
+
if samples_per_pixel < bps_actual_count:
|
| 1414 |
+
# If a file has more values in bps_tuple than expected,
|
| 1415 |
+
# remove the excess.
|
| 1416 |
+
bps_tuple = bps_tuple[:samples_per_pixel]
|
| 1417 |
+
elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:
|
| 1418 |
+
# If a file has only one value in bps_tuple, when it should have more,
|
| 1419 |
+
# presume it is the same number of bits for all of the samples.
|
| 1420 |
+
bps_tuple = bps_tuple * samples_per_pixel
|
| 1421 |
+
|
| 1422 |
+
if len(bps_tuple) != samples_per_pixel:
|
| 1423 |
+
msg = "unknown data organization"
|
| 1424 |
+
raise SyntaxError(msg)
|
| 1425 |
+
|
| 1426 |
+
# mode: check photometric interpretation and bits per pixel
|
| 1427 |
+
key = (
|
| 1428 |
+
self.tag_v2.prefix,
|
| 1429 |
+
photo,
|
| 1430 |
+
sample_format,
|
| 1431 |
+
fillorder,
|
| 1432 |
+
bps_tuple,
|
| 1433 |
+
extra_tuple,
|
| 1434 |
+
)
|
| 1435 |
+
logger.debug("format key: %s", key)
|
| 1436 |
+
try:
|
| 1437 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1438 |
+
except KeyError as e:
|
| 1439 |
+
logger.debug("- unsupported format")
|
| 1440 |
+
msg = "unknown pixel mode"
|
| 1441 |
+
raise SyntaxError(msg) from e
|
| 1442 |
+
|
| 1443 |
+
logger.debug("- raw mode: %s", rawmode)
|
| 1444 |
+
logger.debug("- pil mode: %s", self.mode)
|
| 1445 |
+
|
| 1446 |
+
self.info["compression"] = self._compression
|
| 1447 |
+
|
| 1448 |
+
xres = self.tag_v2.get(X_RESOLUTION, 1)
|
| 1449 |
+
yres = self.tag_v2.get(Y_RESOLUTION, 1)
|
| 1450 |
+
|
| 1451 |
+
if xres and yres:
|
| 1452 |
+
resunit = self.tag_v2.get(RESOLUTION_UNIT)
|
| 1453 |
+
if resunit == 2: # dots per inch
|
| 1454 |
+
self.info["dpi"] = (xres, yres)
|
| 1455 |
+
elif resunit == 3: # dots per centimeter. convert to dpi
|
| 1456 |
+
self.info["dpi"] = (xres * 2.54, yres * 2.54)
|
| 1457 |
+
elif resunit is None: # used to default to 1, but now 2)
|
| 1458 |
+
self.info["dpi"] = (xres, yres)
|
| 1459 |
+
# For backward compatibility,
|
| 1460 |
+
# we also preserve the old behavior
|
| 1461 |
+
self.info["resolution"] = xres, yres
|
| 1462 |
+
else: # No absolute unit of measurement
|
| 1463 |
+
self.info["resolution"] = xres, yres
|
| 1464 |
+
|
| 1465 |
+
# build tile descriptors
|
| 1466 |
+
x = y = layer = 0
|
| 1467 |
+
self.tile = []
|
| 1468 |
+
self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
|
| 1469 |
+
if self.use_load_libtiff:
|
| 1470 |
+
# Decoder expects entire file as one tile.
|
| 1471 |
+
# There's a buffer size limit in load (64k)
|
| 1472 |
+
# so large g4 images will fail if we use that
|
| 1473 |
+
# function.
|
| 1474 |
+
#
|
| 1475 |
+
# Setup the one tile for the whole image, then
|
| 1476 |
+
# use the _load_libtiff function.
|
| 1477 |
+
|
| 1478 |
+
# libtiff handles the fillmode for us, so 1;IR should
|
| 1479 |
+
# actually be 1;I. Including the R double reverses the
|
| 1480 |
+
# bits, so stripes of the image are reversed. See
|
| 1481 |
+
# https://github.com/python-pillow/Pillow/issues/279
|
| 1482 |
+
if fillorder == 2:
|
| 1483 |
+
# Replace fillorder with fillorder=1
|
| 1484 |
+
key = key[:3] + (1,) + key[4:]
|
| 1485 |
+
logger.debug("format key: %s", key)
|
| 1486 |
+
# this should always work, since all the
|
| 1487 |
+
# fillorder==2 modes have a corresponding
|
| 1488 |
+
# fillorder=1 mode
|
| 1489 |
+
self._mode, rawmode = OPEN_INFO[key]
|
| 1490 |
+
# libtiff always returns the bytes in native order.
|
| 1491 |
+
# we're expecting image byte order. So, if the rawmode
|
| 1492 |
+
# contains I;16, we need to convert from native to image
|
| 1493 |
+
# byte order.
|
| 1494 |
+
if rawmode == "I;16":
|
| 1495 |
+
rawmode = "I;16N"
|
| 1496 |
+
if ";16B" in rawmode:
|
| 1497 |
+
rawmode = rawmode.replace(";16B", ";16N")
|
| 1498 |
+
if ";16L" in rawmode:
|
| 1499 |
+
rawmode = rawmode.replace(";16L", ";16N")
|
| 1500 |
+
|
| 1501 |
+
# YCbCr images with new jpeg compression with pixels in one plane
|
| 1502 |
+
# unpacked straight into RGB values
|
| 1503 |
+
if (
|
| 1504 |
+
photo == 6
|
| 1505 |
+
and self._compression == "jpeg"
|
| 1506 |
+
and self._planar_configuration == 1
|
| 1507 |
+
):
|
| 1508 |
+
rawmode = "RGB"
|
| 1509 |
+
|
| 1510 |
+
# Offset in the tile tuple is 0, we go from 0,0 to
|
| 1511 |
+
# w,h, and we only do this once -- eds
|
| 1512 |
+
a = (rawmode, self._compression, False, self.tag_v2.offset)
|
| 1513 |
+
self.tile.append(("libtiff", (0, 0, xsize, ysize), 0, a))
|
| 1514 |
+
|
| 1515 |
+
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
|
| 1516 |
+
# striped image
|
| 1517 |
+
if STRIPOFFSETS in self.tag_v2:
|
| 1518 |
+
offsets = self.tag_v2[STRIPOFFSETS]
|
| 1519 |
+
h = self.tag_v2.get(ROWSPERSTRIP, ysize)
|
| 1520 |
+
w = self.size[0]
|
| 1521 |
+
else:
|
| 1522 |
+
# tiled image
|
| 1523 |
+
offsets = self.tag_v2[TILEOFFSETS]
|
| 1524 |
+
w = self.tag_v2.get(TILEWIDTH)
|
| 1525 |
+
h = self.tag_v2.get(TILELENGTH)
|
| 1526 |
+
|
| 1527 |
+
for offset in offsets:
|
| 1528 |
+
if x + w > xsize:
|
| 1529 |
+
stride = w * sum(bps_tuple) / 8 # bytes per line
|
| 1530 |
+
else:
|
| 1531 |
+
stride = 0
|
| 1532 |
+
|
| 1533 |
+
tile_rawmode = rawmode
|
| 1534 |
+
if self._planar_configuration == 2:
|
| 1535 |
+
# each band on it's own layer
|
| 1536 |
+
tile_rawmode = rawmode[layer]
|
| 1537 |
+
# adjust stride width accordingly
|
| 1538 |
+
stride /= bps_count
|
| 1539 |
+
|
| 1540 |
+
a = (tile_rawmode, int(stride), 1)
|
| 1541 |
+
self.tile.append(
|
| 1542 |
+
(
|
| 1543 |
+
self._compression,
|
| 1544 |
+
(x, y, min(x + w, xsize), min(y + h, ysize)),
|
| 1545 |
+
offset,
|
| 1546 |
+
a,
|
| 1547 |
+
)
|
| 1548 |
+
)
|
| 1549 |
+
x = x + w
|
| 1550 |
+
if x >= self.size[0]:
|
| 1551 |
+
x, y = 0, y + h
|
| 1552 |
+
if y >= self.size[1]:
|
| 1553 |
+
x = y = 0
|
| 1554 |
+
layer += 1
|
| 1555 |
+
else:
|
| 1556 |
+
logger.debug("- unsupported data organization")
|
| 1557 |
+
msg = "unknown data organization"
|
| 1558 |
+
raise SyntaxError(msg)
|
| 1559 |
+
|
| 1560 |
+
# Fix up info.
|
| 1561 |
+
if ICCPROFILE in self.tag_v2:
|
| 1562 |
+
self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
|
| 1563 |
+
|
| 1564 |
+
# fixup palette descriptor
|
| 1565 |
+
|
| 1566 |
+
if self.mode in ["P", "PA"]:
|
| 1567 |
+
palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
|
| 1568 |
+
self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
|
| 1569 |
+
|
| 1570 |
+
|
| 1571 |
+
#
|
| 1572 |
+
# --------------------------------------------------------------------
|
| 1573 |
+
# Write TIFF files
|
| 1574 |
+
|
| 1575 |
+
# little endian is default except for image modes with
|
| 1576 |
+
# explicit big endian byte-order
|
| 1577 |
+
|
| 1578 |
+
SAVE_INFO = {
|
| 1579 |
+
# mode => rawmode, byteorder, photometrics,
|
| 1580 |
+
# sampleformat, bitspersample, extra
|
| 1581 |
+
"1": ("1", II, 1, 1, (1,), None),
|
| 1582 |
+
"L": ("L", II, 1, 1, (8,), None),
|
| 1583 |
+
"LA": ("LA", II, 1, 1, (8, 8), 2),
|
| 1584 |
+
"P": ("P", II, 3, 1, (8,), None),
|
| 1585 |
+
"PA": ("PA", II, 3, 1, (8, 8), 2),
|
| 1586 |
+
"I": ("I;32S", II, 1, 2, (32,), None),
|
| 1587 |
+
"I;16": ("I;16", II, 1, 1, (16,), None),
|
| 1588 |
+
"I;16S": ("I;16S", II, 1, 2, (16,), None),
|
| 1589 |
+
"F": ("F;32F", II, 1, 3, (32,), None),
|
| 1590 |
+
"RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
|
| 1591 |
+
"RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
|
| 1592 |
+
"RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
|
| 1593 |
+
"CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
|
| 1594 |
+
"YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
|
| 1595 |
+
"LAB": ("LAB", II, 8, 1, (8, 8, 8), None),
|
| 1596 |
+
"I;32BS": ("I;32BS", MM, 1, 2, (32,), None),
|
| 1597 |
+
"I;16B": ("I;16B", MM, 1, 1, (16,), None),
|
| 1598 |
+
"I;16BS": ("I;16BS", MM, 1, 2, (16,), None),
|
| 1599 |
+
"F;32BF": ("F;32BF", MM, 1, 3, (32,), None),
|
| 1600 |
+
}
|
| 1601 |
+
|
| 1602 |
+
|
| 1603 |
+
def _save(im, fp, filename):
|
| 1604 |
+
try:
|
| 1605 |
+
rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
|
| 1606 |
+
except KeyError as e:
|
| 1607 |
+
msg = f"cannot write mode {im.mode} as TIFF"
|
| 1608 |
+
raise OSError(msg) from e
|
| 1609 |
+
|
| 1610 |
+
ifd = ImageFileDirectory_v2(prefix=prefix)
|
| 1611 |
+
|
| 1612 |
+
encoderinfo = im.encoderinfo
|
| 1613 |
+
encoderconfig = im.encoderconfig
|
| 1614 |
+
try:
|
| 1615 |
+
compression = encoderinfo["compression"]
|
| 1616 |
+
except KeyError:
|
| 1617 |
+
compression = im.info.get("compression")
|
| 1618 |
+
if isinstance(compression, int):
|
| 1619 |
+
# compression value may be from BMP. Ignore it
|
| 1620 |
+
compression = None
|
| 1621 |
+
if compression is None:
|
| 1622 |
+
compression = "raw"
|
| 1623 |
+
elif compression == "tiff_jpeg":
|
| 1624 |
+
# OJPEG is obsolete, so use new-style JPEG compression instead
|
| 1625 |
+
compression = "jpeg"
|
| 1626 |
+
elif compression == "tiff_deflate":
|
| 1627 |
+
compression = "tiff_adobe_deflate"
|
| 1628 |
+
|
| 1629 |
+
libtiff = WRITE_LIBTIFF or compression != "raw"
|
| 1630 |
+
|
| 1631 |
+
# required for color libtiff images
|
| 1632 |
+
ifd[PLANAR_CONFIGURATION] = 1
|
| 1633 |
+
|
| 1634 |
+
ifd[IMAGEWIDTH] = im.size[0]
|
| 1635 |
+
ifd[IMAGELENGTH] = im.size[1]
|
| 1636 |
+
|
| 1637 |
+
# write any arbitrary tags passed in as an ImageFileDirectory
|
| 1638 |
+
if "tiffinfo" in encoderinfo:
|
| 1639 |
+
info = encoderinfo["tiffinfo"]
|
| 1640 |
+
elif "exif" in encoderinfo:
|
| 1641 |
+
info = encoderinfo["exif"]
|
| 1642 |
+
if isinstance(info, bytes):
|
| 1643 |
+
exif = Image.Exif()
|
| 1644 |
+
exif.load(info)
|
| 1645 |
+
info = exif
|
| 1646 |
+
else:
|
| 1647 |
+
info = {}
|
| 1648 |
+
logger.debug("Tiffinfo Keys: %s", list(info))
|
| 1649 |
+
if isinstance(info, ImageFileDirectory_v1):
|
| 1650 |
+
info = info.to_v2()
|
| 1651 |
+
for key in info:
|
| 1652 |
+
if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
|
| 1653 |
+
ifd[key] = info.get_ifd(key)
|
| 1654 |
+
else:
|
| 1655 |
+
ifd[key] = info.get(key)
|
| 1656 |
+
try:
|
| 1657 |
+
ifd.tagtype[key] = info.tagtype[key]
|
| 1658 |
+
except Exception:
|
| 1659 |
+
pass # might not be an IFD. Might not have populated type
|
| 1660 |
+
|
| 1661 |
+
legacy_ifd = {}
|
| 1662 |
+
if hasattr(im, "tag"):
|
| 1663 |
+
legacy_ifd = im.tag.to_v2()
|
| 1664 |
+
|
| 1665 |
+
supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
|
| 1666 |
+
for tag in (
|
| 1667 |
+
# IFD offset that may not be correct in the saved image
|
| 1668 |
+
EXIFIFD,
|
| 1669 |
+
# Determined by the image format and should not be copied from legacy_ifd.
|
| 1670 |
+
SAMPLEFORMAT,
|
| 1671 |
+
):
|
| 1672 |
+
if tag in supplied_tags:
|
| 1673 |
+
del supplied_tags[tag]
|
| 1674 |
+
|
| 1675 |
+
# additions written by Greg Couch, gregc@cgl.ucsf.edu
|
| 1676 |
+
# inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
|
| 1677 |
+
if hasattr(im, "tag_v2"):
|
| 1678 |
+
# preserve tags from original TIFF image file
|
| 1679 |
+
for key in (
|
| 1680 |
+
RESOLUTION_UNIT,
|
| 1681 |
+
X_RESOLUTION,
|
| 1682 |
+
Y_RESOLUTION,
|
| 1683 |
+
IPTC_NAA_CHUNK,
|
| 1684 |
+
PHOTOSHOP_CHUNK,
|
| 1685 |
+
XMP,
|
| 1686 |
+
):
|
| 1687 |
+
if key in im.tag_v2:
|
| 1688 |
+
if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (
|
| 1689 |
+
TiffTags.BYTE,
|
| 1690 |
+
TiffTags.UNDEFINED,
|
| 1691 |
+
):
|
| 1692 |
+
del supplied_tags[key]
|
| 1693 |
+
else:
|
| 1694 |
+
ifd[key] = im.tag_v2[key]
|
| 1695 |
+
ifd.tagtype[key] = im.tag_v2.tagtype[key]
|
| 1696 |
+
|
| 1697 |
+
# preserve ICC profile (should also work when saving other formats
|
| 1698 |
+
# which support profiles as TIFF) -- 2008-06-06 Florian Hoech
|
| 1699 |
+
icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))
|
| 1700 |
+
if icc:
|
| 1701 |
+
ifd[ICCPROFILE] = icc
|
| 1702 |
+
|
| 1703 |
+
for key, name in [
|
| 1704 |
+
(IMAGEDESCRIPTION, "description"),
|
| 1705 |
+
(X_RESOLUTION, "resolution"),
|
| 1706 |
+
(Y_RESOLUTION, "resolution"),
|
| 1707 |
+
(X_RESOLUTION, "x_resolution"),
|
| 1708 |
+
(Y_RESOLUTION, "y_resolution"),
|
| 1709 |
+
(RESOLUTION_UNIT, "resolution_unit"),
|
| 1710 |
+
(SOFTWARE, "software"),
|
| 1711 |
+
(DATE_TIME, "date_time"),
|
| 1712 |
+
(ARTIST, "artist"),
|
| 1713 |
+
(COPYRIGHT, "copyright"),
|
| 1714 |
+
]:
|
| 1715 |
+
if name in encoderinfo:
|
| 1716 |
+
ifd[key] = encoderinfo[name]
|
| 1717 |
+
|
| 1718 |
+
dpi = encoderinfo.get("dpi")
|
| 1719 |
+
if dpi:
|
| 1720 |
+
ifd[RESOLUTION_UNIT] = 2
|
| 1721 |
+
ifd[X_RESOLUTION] = dpi[0]
|
| 1722 |
+
ifd[Y_RESOLUTION] = dpi[1]
|
| 1723 |
+
|
| 1724 |
+
if bits != (1,):
|
| 1725 |
+
ifd[BITSPERSAMPLE] = bits
|
| 1726 |
+
if len(bits) != 1:
|
| 1727 |
+
ifd[SAMPLESPERPIXEL] = len(bits)
|
| 1728 |
+
if extra is not None:
|
| 1729 |
+
ifd[EXTRASAMPLES] = extra
|
| 1730 |
+
if format != 1:
|
| 1731 |
+
ifd[SAMPLEFORMAT] = format
|
| 1732 |
+
|
| 1733 |
+
if PHOTOMETRIC_INTERPRETATION not in ifd:
|
| 1734 |
+
ifd[PHOTOMETRIC_INTERPRETATION] = photo
|
| 1735 |
+
elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:
|
| 1736 |
+
if im.mode == "1":
|
| 1737 |
+
inverted_im = im.copy()
|
| 1738 |
+
px = inverted_im.load()
|
| 1739 |
+
for y in range(inverted_im.height):
|
| 1740 |
+
for x in range(inverted_im.width):
|
| 1741 |
+
px[x, y] = 0 if px[x, y] == 255 else 255
|
| 1742 |
+
im = inverted_im
|
| 1743 |
+
else:
|
| 1744 |
+
im = ImageOps.invert(im)
|
| 1745 |
+
|
| 1746 |
+
if im.mode in ["P", "PA"]:
|
| 1747 |
+
lut = im.im.getpalette("RGB", "RGB;L")
|
| 1748 |
+
colormap = []
|
| 1749 |
+
colors = len(lut) // 3
|
| 1750 |
+
for i in range(3):
|
| 1751 |
+
colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]
|
| 1752 |
+
colormap += [0] * (256 - colors)
|
| 1753 |
+
ifd[COLORMAP] = colormap
|
| 1754 |
+
# data orientation
|
| 1755 |
+
w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]
|
| 1756 |
+
stride = len(bits) * ((w * bits[0] + 7) // 8)
|
| 1757 |
+
if ROWSPERSTRIP not in ifd:
|
| 1758 |
+
# aim for given strip size (64 KB by default) when using libtiff writer
|
| 1759 |
+
if libtiff:
|
| 1760 |
+
im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)
|
| 1761 |
+
rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)
|
| 1762 |
+
# JPEG encoder expects multiple of 8 rows
|
| 1763 |
+
if compression == "jpeg":
|
| 1764 |
+
rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)
|
| 1765 |
+
else:
|
| 1766 |
+
rows_per_strip = h
|
| 1767 |
+
if rows_per_strip == 0:
|
| 1768 |
+
rows_per_strip = 1
|
| 1769 |
+
ifd[ROWSPERSTRIP] = rows_per_strip
|
| 1770 |
+
strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]
|
| 1771 |
+
strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]
|
| 1772 |
+
if strip_byte_counts >= 2**16:
|
| 1773 |
+
ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
|
| 1774 |
+
ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (
|
| 1775 |
+
stride * h - strip_byte_counts * (strips_per_image - 1),
|
| 1776 |
+
)
|
| 1777 |
+
ifd[STRIPOFFSETS] = tuple(
|
| 1778 |
+
range(0, strip_byte_counts * strips_per_image, strip_byte_counts)
|
| 1779 |
+
) # this is adjusted by IFD writer
|
| 1780 |
+
# no compression by default:
|
| 1781 |
+
ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
|
| 1782 |
+
|
| 1783 |
+
if im.mode == "YCbCr":
|
| 1784 |
+
for tag, value in {
|
| 1785 |
+
YCBCRSUBSAMPLING: (1, 1),
|
| 1786 |
+
REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),
|
| 1787 |
+
}.items():
|
| 1788 |
+
ifd.setdefault(tag, value)
|
| 1789 |
+
|
| 1790 |
+
blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]
|
| 1791 |
+
if libtiff:
|
| 1792 |
+
if "quality" in encoderinfo:
|
| 1793 |
+
quality = encoderinfo["quality"]
|
| 1794 |
+
if not isinstance(quality, int) or quality < 0 or quality > 100:
|
| 1795 |
+
msg = "Invalid quality setting"
|
| 1796 |
+
raise ValueError(msg)
|
| 1797 |
+
if compression != "jpeg":
|
| 1798 |
+
msg = "quality setting only supported for 'jpeg' compression"
|
| 1799 |
+
raise ValueError(msg)
|
| 1800 |
+
ifd[JPEGQUALITY] = quality
|
| 1801 |
+
|
| 1802 |
+
logger.debug("Saving using libtiff encoder")
|
| 1803 |
+
logger.debug("Items: %s", sorted(ifd.items()))
|
| 1804 |
+
_fp = 0
|
| 1805 |
+
if hasattr(fp, "fileno"):
|
| 1806 |
+
try:
|
| 1807 |
+
fp.seek(0)
|
| 1808 |
+
_fp = os.dup(fp.fileno())
|
| 1809 |
+
except io.UnsupportedOperation:
|
| 1810 |
+
pass
|
| 1811 |
+
|
| 1812 |
+
# optional types for non core tags
|
| 1813 |
+
types = {}
|
| 1814 |
+
# STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
|
| 1815 |
+
# based on the data in the strip.
|
| 1816 |
+
# OSUBFILETYPE is deprecated.
|
| 1817 |
+
# The other tags expect arrays with a certain length (fixed or depending on
|
| 1818 |
+
# BITSPERSAMPLE, etc), passing arrays with a different length will result in
|
| 1819 |
+
# segfaults. Block these tags until we add extra validation.
|
| 1820 |
+
# SUBIFD may also cause a segfault.
|
| 1821 |
+
blocklist += [
|
| 1822 |
+
OSUBFILETYPE,
|
| 1823 |
+
REFERENCEBLACKWHITE,
|
| 1824 |
+
STRIPBYTECOUNTS,
|
| 1825 |
+
STRIPOFFSETS,
|
| 1826 |
+
TRANSFERFUNCTION,
|
| 1827 |
+
SUBIFD,
|
| 1828 |
+
]
|
| 1829 |
+
|
| 1830 |
+
# bits per sample is a single short in the tiff directory, not a list.
|
| 1831 |
+
atts = {BITSPERSAMPLE: bits[0]}
|
| 1832 |
+
# Merge the ones that we have with (optional) more bits from
|
| 1833 |
+
# the original file, e.g x,y resolution so that we can
|
| 1834 |
+
# save(load('')) == original file.
|
| 1835 |
+
for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
|
| 1836 |
+
# Libtiff can only process certain core items without adding
|
| 1837 |
+
# them to the custom dictionary.
|
| 1838 |
+
# Custom items are supported for int, float, unicode, string and byte
|
| 1839 |
+
# values. Other types and tuples require a tagtype.
|
| 1840 |
+
if tag not in TiffTags.LIBTIFF_CORE:
|
| 1841 |
+
if not getattr(Image.core, "libtiff_support_custom_tags", False):
|
| 1842 |
+
continue
|
| 1843 |
+
|
| 1844 |
+
if tag in ifd.tagtype:
|
| 1845 |
+
types[tag] = ifd.tagtype[tag]
|
| 1846 |
+
elif not (isinstance(value, (int, float, str, bytes))):
|
| 1847 |
+
continue
|
| 1848 |
+
else:
|
| 1849 |
+
type = TiffTags.lookup(tag).type
|
| 1850 |
+
if type:
|
| 1851 |
+
types[tag] = type
|
| 1852 |
+
if tag not in atts and tag not in blocklist:
|
| 1853 |
+
if isinstance(value, str):
|
| 1854 |
+
atts[tag] = value.encode("ascii", "replace") + b"\0"
|
| 1855 |
+
elif isinstance(value, IFDRational):
|
| 1856 |
+
atts[tag] = float(value)
|
| 1857 |
+
else:
|
| 1858 |
+
atts[tag] = value
|
| 1859 |
+
|
| 1860 |
+
if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:
|
| 1861 |
+
atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]
|
| 1862 |
+
|
| 1863 |
+
logger.debug("Converted items: %s", sorted(atts.items()))
|
| 1864 |
+
|
| 1865 |
+
# libtiff always expects the bytes in native order.
|
| 1866 |
+
# we're storing image byte order. So, if the rawmode
|
| 1867 |
+
# contains I;16, we need to convert from native to image
|
| 1868 |
+
# byte order.
|
| 1869 |
+
if im.mode in ("I;16B", "I;16"):
|
| 1870 |
+
rawmode = "I;16N"
|
| 1871 |
+
|
| 1872 |
+
# Pass tags as sorted list so that the tags are set in a fixed order.
|
| 1873 |
+
# This is required by libtiff for some tags. For example, the JPEGQUALITY
|
| 1874 |
+
# pseudo tag requires that the COMPRESS tag was already set.
|
| 1875 |
+
tags = list(atts.items())
|
| 1876 |
+
tags.sort()
|
| 1877 |
+
a = (rawmode, compression, _fp, filename, tags, types)
|
| 1878 |
+
encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
|
| 1879 |
+
encoder.setimage(im.im, (0, 0) + im.size)
|
| 1880 |
+
while True:
|
| 1881 |
+
# undone, change to self.decodermaxblock:
|
| 1882 |
+
errcode, data = encoder.encode(16 * 1024)[1:]
|
| 1883 |
+
if not _fp:
|
| 1884 |
+
fp.write(data)
|
| 1885 |
+
if errcode:
|
| 1886 |
+
break
|
| 1887 |
+
if _fp:
|
| 1888 |
+
try:
|
| 1889 |
+
os.close(_fp)
|
| 1890 |
+
except OSError:
|
| 1891 |
+
pass
|
| 1892 |
+
if errcode < 0:
|
| 1893 |
+
msg = f"encoder error {errcode} when writing image file"
|
| 1894 |
+
raise OSError(msg)
|
| 1895 |
+
|
| 1896 |
+
else:
|
| 1897 |
+
for tag in blocklist:
|
| 1898 |
+
del ifd[tag]
|
| 1899 |
+
offset = ifd.save(fp)
|
| 1900 |
+
|
| 1901 |
+
ImageFile._save(
|
| 1902 |
+
im, fp, [("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))]
|
| 1903 |
+
)
|
| 1904 |
+
|
| 1905 |
+
# -- helper for multi-page save --
|
| 1906 |
+
if "_debug_multipage" in encoderinfo:
|
| 1907 |
+
# just to access o32 and o16 (using correct byte order)
|
| 1908 |
+
im._debug_multipage = ifd
|
| 1909 |
+
|
| 1910 |
+
|
| 1911 |
+
class AppendingTiffWriter:
|
| 1912 |
+
fieldSizes = [
|
| 1913 |
+
0, # None
|
| 1914 |
+
1, # byte
|
| 1915 |
+
1, # ascii
|
| 1916 |
+
2, # short
|
| 1917 |
+
4, # long
|
| 1918 |
+
8, # rational
|
| 1919 |
+
1, # sbyte
|
| 1920 |
+
1, # undefined
|
| 1921 |
+
2, # sshort
|
| 1922 |
+
4, # slong
|
| 1923 |
+
8, # srational
|
| 1924 |
+
4, # float
|
| 1925 |
+
8, # double
|
| 1926 |
+
4, # ifd
|
| 1927 |
+
2, # unicode
|
| 1928 |
+
4, # complex
|
| 1929 |
+
8, # long8
|
| 1930 |
+
]
|
| 1931 |
+
|
| 1932 |
+
Tags = {
|
| 1933 |
+
273, # StripOffsets
|
| 1934 |
+
288, # FreeOffsets
|
| 1935 |
+
324, # TileOffsets
|
| 1936 |
+
519, # JPEGQTables
|
| 1937 |
+
520, # JPEGDCTables
|
| 1938 |
+
521, # JPEGACTables
|
| 1939 |
+
}
|
| 1940 |
+
|
| 1941 |
+
def __init__(self, fn, new=False):
|
| 1942 |
+
if hasattr(fn, "read"):
|
| 1943 |
+
self.f = fn
|
| 1944 |
+
self.close_fp = False
|
| 1945 |
+
else:
|
| 1946 |
+
self.name = fn
|
| 1947 |
+
self.close_fp = True
|
| 1948 |
+
try:
|
| 1949 |
+
self.f = open(fn, "w+b" if new else "r+b")
|
| 1950 |
+
except OSError:
|
| 1951 |
+
self.f = open(fn, "w+b")
|
| 1952 |
+
self.beginning = self.f.tell()
|
| 1953 |
+
self.setup()
|
| 1954 |
+
|
| 1955 |
+
def setup(self) -> None:
|
| 1956 |
+
# Reset everything.
|
| 1957 |
+
self.f.seek(self.beginning, os.SEEK_SET)
|
| 1958 |
+
|
| 1959 |
+
self.whereToWriteNewIFDOffset = None
|
| 1960 |
+
self.offsetOfNewPage = 0
|
| 1961 |
+
|
| 1962 |
+
self.IIMM = iimm = self.f.read(4)
|
| 1963 |
+
if not iimm:
|
| 1964 |
+
# empty file - first page
|
| 1965 |
+
self.isFirst = True
|
| 1966 |
+
return
|
| 1967 |
+
|
| 1968 |
+
self.isFirst = False
|
| 1969 |
+
if iimm == b"II\x2a\x00":
|
| 1970 |
+
self.setEndian("<")
|
| 1971 |
+
elif iimm == b"MM\x00\x2a":
|
| 1972 |
+
self.setEndian(">")
|
| 1973 |
+
else:
|
| 1974 |
+
msg = "Invalid TIFF file header"
|
| 1975 |
+
raise RuntimeError(msg)
|
| 1976 |
+
|
| 1977 |
+
self.skipIFDs()
|
| 1978 |
+
self.goToEnd()
|
| 1979 |
+
|
| 1980 |
+
def finalize(self) -> None:
|
| 1981 |
+
if self.isFirst:
|
| 1982 |
+
return
|
| 1983 |
+
|
| 1984 |
+
# fix offsets
|
| 1985 |
+
self.f.seek(self.offsetOfNewPage)
|
| 1986 |
+
|
| 1987 |
+
iimm = self.f.read(4)
|
| 1988 |
+
if not iimm:
|
| 1989 |
+
# Make it easy to finish a frame without committing to a new one.
|
| 1990 |
+
return
|
| 1991 |
+
|
| 1992 |
+
if iimm != self.IIMM:
|
| 1993 |
+
msg = "IIMM of new page doesn't match IIMM of first page"
|
| 1994 |
+
raise RuntimeError(msg)
|
| 1995 |
+
|
| 1996 |
+
ifd_offset = self.readLong()
|
| 1997 |
+
ifd_offset += self.offsetOfNewPage
|
| 1998 |
+
self.f.seek(self.whereToWriteNewIFDOffset)
|
| 1999 |
+
self.writeLong(ifd_offset)
|
| 2000 |
+
self.f.seek(ifd_offset)
|
| 2001 |
+
self.fixIFD()
|
| 2002 |
+
|
| 2003 |
+
def newFrame(self) -> None:
|
| 2004 |
+
# Call this to finish a frame.
|
| 2005 |
+
self.finalize()
|
| 2006 |
+
self.setup()
|
| 2007 |
+
|
| 2008 |
+
def __enter__(self) -> AppendingTiffWriter:
|
| 2009 |
+
return self
|
| 2010 |
+
|
| 2011 |
+
def __exit__(self, *args: object) -> None:
|
| 2012 |
+
if self.close_fp:
|
| 2013 |
+
self.close()
|
| 2014 |
+
|
| 2015 |
+
def tell(self) -> int:
|
| 2016 |
+
return self.f.tell() - self.offsetOfNewPage
|
| 2017 |
+
|
| 2018 |
+
def seek(self, offset, whence=io.SEEK_SET):
|
| 2019 |
+
if whence == os.SEEK_SET:
|
| 2020 |
+
offset += self.offsetOfNewPage
|
| 2021 |
+
|
| 2022 |
+
self.f.seek(offset, whence)
|
| 2023 |
+
return self.tell()
|
| 2024 |
+
|
| 2025 |
+
def goToEnd(self) -> None:
|
| 2026 |
+
self.f.seek(0, os.SEEK_END)
|
| 2027 |
+
pos = self.f.tell()
|
| 2028 |
+
|
| 2029 |
+
# pad to 16 byte boundary
|
| 2030 |
+
pad_bytes = 16 - pos % 16
|
| 2031 |
+
if 0 < pad_bytes < 16:
|
| 2032 |
+
self.f.write(bytes(pad_bytes))
|
| 2033 |
+
self.offsetOfNewPage = self.f.tell()
|
| 2034 |
+
|
| 2035 |
+
def setEndian(self, endian: str) -> None:
|
| 2036 |
+
self.endian = endian
|
| 2037 |
+
self.longFmt = f"{self.endian}L"
|
| 2038 |
+
self.shortFmt = f"{self.endian}H"
|
| 2039 |
+
self.tagFormat = f"{self.endian}HHL"
|
| 2040 |
+
|
| 2041 |
+
def skipIFDs(self) -> None:
|
| 2042 |
+
while True:
|
| 2043 |
+
ifd_offset = self.readLong()
|
| 2044 |
+
if ifd_offset == 0:
|
| 2045 |
+
self.whereToWriteNewIFDOffset = self.f.tell() - 4
|
| 2046 |
+
break
|
| 2047 |
+
|
| 2048 |
+
self.f.seek(ifd_offset)
|
| 2049 |
+
num_tags = self.readShort()
|
| 2050 |
+
self.f.seek(num_tags * 12, os.SEEK_CUR)
|
| 2051 |
+
|
| 2052 |
+
def write(self, data: bytes) -> int | None:
|
| 2053 |
+
return self.f.write(data)
|
| 2054 |
+
|
| 2055 |
+
def readShort(self) -> int:
|
| 2056 |
+
(value,) = struct.unpack(self.shortFmt, self.f.read(2))
|
| 2057 |
+
return value
|
| 2058 |
+
|
| 2059 |
+
def readLong(self) -> int:
|
| 2060 |
+
(value,) = struct.unpack(self.longFmt, self.f.read(4))
|
| 2061 |
+
return value
|
| 2062 |
+
|
| 2063 |
+
def rewriteLastShortToLong(self, value: int) -> None:
|
| 2064 |
+
self.f.seek(-2, os.SEEK_CUR)
|
| 2065 |
+
bytes_written = self.f.write(struct.pack(self.longFmt, value))
|
| 2066 |
+
if bytes_written is not None and bytes_written != 4:
|
| 2067 |
+
msg = f"wrote only {bytes_written} bytes but wanted 4"
|
| 2068 |
+
raise RuntimeError(msg)
|
| 2069 |
+
|
| 2070 |
+
def rewriteLastShort(self, value: int) -> None:
|
| 2071 |
+
self.f.seek(-2, os.SEEK_CUR)
|
| 2072 |
+
bytes_written = self.f.write(struct.pack(self.shortFmt, value))
|
| 2073 |
+
if bytes_written is not None and bytes_written != 2:
|
| 2074 |
+
msg = f"wrote only {bytes_written} bytes but wanted 2"
|
| 2075 |
+
raise RuntimeError(msg)
|
| 2076 |
+
|
| 2077 |
+
def rewriteLastLong(self, value: int) -> None:
|
| 2078 |
+
self.f.seek(-4, os.SEEK_CUR)
|
| 2079 |
+
bytes_written = self.f.write(struct.pack(self.longFmt, value))
|
| 2080 |
+
if bytes_written is not None and bytes_written != 4:
|
| 2081 |
+
msg = f"wrote only {bytes_written} bytes but wanted 4"
|
| 2082 |
+
raise RuntimeError(msg)
|
| 2083 |
+
|
| 2084 |
+
def writeShort(self, value: int) -> None:
|
| 2085 |
+
bytes_written = self.f.write(struct.pack(self.shortFmt, value))
|
| 2086 |
+
if bytes_written is not None and bytes_written != 2:
|
| 2087 |
+
msg = f"wrote only {bytes_written} bytes but wanted 2"
|
| 2088 |
+
raise RuntimeError(msg)
|
| 2089 |
+
|
| 2090 |
+
def writeLong(self, value: int) -> None:
|
| 2091 |
+
bytes_written = self.f.write(struct.pack(self.longFmt, value))
|
| 2092 |
+
if bytes_written is not None and bytes_written != 4:
|
| 2093 |
+
msg = f"wrote only {bytes_written} bytes but wanted 4"
|
| 2094 |
+
raise RuntimeError(msg)
|
| 2095 |
+
|
| 2096 |
+
def close(self) -> None:
|
| 2097 |
+
self.finalize()
|
| 2098 |
+
self.f.close()
|
| 2099 |
+
|
| 2100 |
+
def fixIFD(self) -> None:
|
| 2101 |
+
num_tags = self.readShort()
|
| 2102 |
+
|
| 2103 |
+
for i in range(num_tags):
|
| 2104 |
+
tag, field_type, count = struct.unpack(self.tagFormat, self.f.read(8))
|
| 2105 |
+
|
| 2106 |
+
field_size = self.fieldSizes[field_type]
|
| 2107 |
+
total_size = field_size * count
|
| 2108 |
+
is_local = total_size <= 4
|
| 2109 |
+
offset: int | None
|
| 2110 |
+
if not is_local:
|
| 2111 |
+
offset = self.readLong() + self.offsetOfNewPage
|
| 2112 |
+
self.rewriteLastLong(offset)
|
| 2113 |
+
|
| 2114 |
+
if tag in self.Tags:
|
| 2115 |
+
cur_pos = self.f.tell()
|
| 2116 |
+
|
| 2117 |
+
if is_local:
|
| 2118 |
+
self.fixOffsets(
|
| 2119 |
+
count, isShort=(field_size == 2), isLong=(field_size == 4)
|
| 2120 |
+
)
|
| 2121 |
+
self.f.seek(cur_pos + 4)
|
| 2122 |
+
else:
|
| 2123 |
+
self.f.seek(offset)
|
| 2124 |
+
self.fixOffsets(
|
| 2125 |
+
count, isShort=(field_size == 2), isLong=(field_size == 4)
|
| 2126 |
+
)
|
| 2127 |
+
self.f.seek(cur_pos)
|
| 2128 |
+
|
| 2129 |
+
offset = cur_pos = None
|
| 2130 |
+
|
| 2131 |
+
elif is_local:
|
| 2132 |
+
# skip the locally stored value that is not an offset
|
| 2133 |
+
self.f.seek(4, os.SEEK_CUR)
|
| 2134 |
+
|
| 2135 |
+
def fixOffsets(
|
| 2136 |
+
self, count: int, isShort: bool = False, isLong: bool = False
|
| 2137 |
+
) -> None:
|
| 2138 |
+
if not isShort and not isLong:
|
| 2139 |
+
msg = "offset is neither short nor long"
|
| 2140 |
+
raise RuntimeError(msg)
|
| 2141 |
+
|
| 2142 |
+
for i in range(count):
|
| 2143 |
+
offset = self.readShort() if isShort else self.readLong()
|
| 2144 |
+
offset += self.offsetOfNewPage
|
| 2145 |
+
if isShort and offset >= 65536:
|
| 2146 |
+
# offset is now too large - we must convert shorts to longs
|
| 2147 |
+
if count != 1:
|
| 2148 |
+
msg = "not implemented"
|
| 2149 |
+
raise RuntimeError(msg) # XXX TODO
|
| 2150 |
+
|
| 2151 |
+
# simple case - the offset is just one and therefore it is
|
| 2152 |
+
# local (not referenced with another offset)
|
| 2153 |
+
self.rewriteLastShortToLong(offset)
|
| 2154 |
+
self.f.seek(-10, os.SEEK_CUR)
|
| 2155 |
+
self.writeShort(TiffTags.LONG) # rewrite the type to LONG
|
| 2156 |
+
self.f.seek(8, os.SEEK_CUR)
|
| 2157 |
+
elif isShort:
|
| 2158 |
+
self.rewriteLastShort(offset)
|
| 2159 |
+
else:
|
| 2160 |
+
self.rewriteLastLong(offset)
|
| 2161 |
+
|
| 2162 |
+
|
| 2163 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 2164 |
+
encoderinfo = im.encoderinfo.copy()
|
| 2165 |
+
encoderconfig = im.encoderconfig
|
| 2166 |
+
append_images = list(encoderinfo.get("append_images", []))
|
| 2167 |
+
if not hasattr(im, "n_frames") and not append_images:
|
| 2168 |
+
return _save(im, fp, filename)
|
| 2169 |
+
|
| 2170 |
+
cur_idx = im.tell()
|
| 2171 |
+
try:
|
| 2172 |
+
with AppendingTiffWriter(fp) as tf:
|
| 2173 |
+
for ims in [im] + append_images:
|
| 2174 |
+
ims.encoderinfo = encoderinfo
|
| 2175 |
+
ims.encoderconfig = encoderconfig
|
| 2176 |
+
if not hasattr(ims, "n_frames"):
|
| 2177 |
+
nfr = 1
|
| 2178 |
+
else:
|
| 2179 |
+
nfr = ims.n_frames
|
| 2180 |
+
|
| 2181 |
+
for idx in range(nfr):
|
| 2182 |
+
ims.seek(idx)
|
| 2183 |
+
ims.load()
|
| 2184 |
+
_save(ims, tf, filename)
|
| 2185 |
+
tf.newFrame()
|
| 2186 |
+
finally:
|
| 2187 |
+
im.seek(cur_idx)
|
| 2188 |
+
|
| 2189 |
+
|
| 2190 |
+
#
|
| 2191 |
+
# --------------------------------------------------------------------
|
| 2192 |
+
# Register
|
| 2193 |
+
|
| 2194 |
+
Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
|
| 2195 |
+
Image.register_save(TiffImageFile.format, _save)
|
| 2196 |
+
Image.register_save_all(TiffImageFile.format, _save_all)
|
| 2197 |
+
|
| 2198 |
+
Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"])
|
| 2199 |
+
|
| 2200 |
+
Image.register_mime(TiffImageFile.format, "image/tiff")
|
.venv/lib/python3.11/site-packages/PIL/TiffTags.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# TIFF tags
|
| 6 |
+
#
|
| 7 |
+
# This module provides clear-text names for various well-known
|
| 8 |
+
# TIFF tags. the TIFF codec works just fine without it.
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) Secret Labs AB 1999.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
|
| 15 |
+
##
|
| 16 |
+
# This module provides constants and clear-text names for various
|
| 17 |
+
# well-known TIFF tags.
|
| 18 |
+
##
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from typing import NamedTuple
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class _TagInfo(NamedTuple):
|
| 25 |
+
value: int | None
|
| 26 |
+
name: str
|
| 27 |
+
type: int | None
|
| 28 |
+
length: int | None
|
| 29 |
+
enum: dict[str, int]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TagInfo(_TagInfo):
|
| 33 |
+
__slots__: list[str] = []
|
| 34 |
+
|
| 35 |
+
def __new__(cls, value=None, name="unknown", type=None, length=None, enum=None):
|
| 36 |
+
return super().__new__(cls, value, name, type, length, enum or {})
|
| 37 |
+
|
| 38 |
+
def cvt_enum(self, value):
|
| 39 |
+
# Using get will call hash(value), which can be expensive
|
| 40 |
+
# for some types (e.g. Fraction). Since self.enum is rarely
|
| 41 |
+
# used, it's usually better to test it first.
|
| 42 |
+
return self.enum.get(value, value) if self.enum else value
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def lookup(tag, group=None):
|
| 46 |
+
"""
|
| 47 |
+
:param tag: Integer tag number
|
| 48 |
+
:param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in
|
| 49 |
+
|
| 50 |
+
.. versionadded:: 8.3.0
|
| 51 |
+
|
| 52 |
+
:returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,
|
| 53 |
+
otherwise just populating the value and name from ``TAGS``.
|
| 54 |
+
If the tag is not recognized, "unknown" is returned for the name
|
| 55 |
+
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
if group is not None:
|
| 59 |
+
info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None
|
| 60 |
+
else:
|
| 61 |
+
info = TAGS_V2.get(tag)
|
| 62 |
+
return info or TagInfo(tag, TAGS.get(tag, "unknown"))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
##
|
| 66 |
+
# Map tag numbers to tag info.
|
| 67 |
+
#
|
| 68 |
+
# id: (Name, Type, Length[, enum_values])
|
| 69 |
+
#
|
| 70 |
+
# The length here differs from the length in the tiff spec. For
|
| 71 |
+
# numbers, the tiff spec is for the number of fields returned. We
|
| 72 |
+
# agree here. For string-like types, the tiff spec uses the length of
|
| 73 |
+
# field in bytes. In Pillow, we are using the number of expected
|
| 74 |
+
# fields, in general 1 for string-like types.
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
BYTE = 1
|
| 78 |
+
ASCII = 2
|
| 79 |
+
SHORT = 3
|
| 80 |
+
LONG = 4
|
| 81 |
+
RATIONAL = 5
|
| 82 |
+
SIGNED_BYTE = 6
|
| 83 |
+
UNDEFINED = 7
|
| 84 |
+
SIGNED_SHORT = 8
|
| 85 |
+
SIGNED_LONG = 9
|
| 86 |
+
SIGNED_RATIONAL = 10
|
| 87 |
+
FLOAT = 11
|
| 88 |
+
DOUBLE = 12
|
| 89 |
+
IFD = 13
|
| 90 |
+
LONG8 = 16
|
| 91 |
+
|
| 92 |
+
_tags_v2 = {
|
| 93 |
+
254: ("NewSubfileType", LONG, 1),
|
| 94 |
+
255: ("SubfileType", SHORT, 1),
|
| 95 |
+
256: ("ImageWidth", LONG, 1),
|
| 96 |
+
257: ("ImageLength", LONG, 1),
|
| 97 |
+
258: ("BitsPerSample", SHORT, 0),
|
| 98 |
+
259: (
|
| 99 |
+
"Compression",
|
| 100 |
+
SHORT,
|
| 101 |
+
1,
|
| 102 |
+
{
|
| 103 |
+
"Uncompressed": 1,
|
| 104 |
+
"CCITT 1d": 2,
|
| 105 |
+
"Group 3 Fax": 3,
|
| 106 |
+
"Group 4 Fax": 4,
|
| 107 |
+
"LZW": 5,
|
| 108 |
+
"JPEG": 6,
|
| 109 |
+
"PackBits": 32773,
|
| 110 |
+
},
|
| 111 |
+
),
|
| 112 |
+
262: (
|
| 113 |
+
"PhotometricInterpretation",
|
| 114 |
+
SHORT,
|
| 115 |
+
1,
|
| 116 |
+
{
|
| 117 |
+
"WhiteIsZero": 0,
|
| 118 |
+
"BlackIsZero": 1,
|
| 119 |
+
"RGB": 2,
|
| 120 |
+
"RGB Palette": 3,
|
| 121 |
+
"Transparency Mask": 4,
|
| 122 |
+
"CMYK": 5,
|
| 123 |
+
"YCbCr": 6,
|
| 124 |
+
"CieLAB": 8,
|
| 125 |
+
"CFA": 32803, # TIFF/EP, Adobe DNG
|
| 126 |
+
"LinearRaw": 32892, # Adobe DNG
|
| 127 |
+
},
|
| 128 |
+
),
|
| 129 |
+
263: ("Threshholding", SHORT, 1),
|
| 130 |
+
264: ("CellWidth", SHORT, 1),
|
| 131 |
+
265: ("CellLength", SHORT, 1),
|
| 132 |
+
266: ("FillOrder", SHORT, 1),
|
| 133 |
+
269: ("DocumentName", ASCII, 1),
|
| 134 |
+
270: ("ImageDescription", ASCII, 1),
|
| 135 |
+
271: ("Make", ASCII, 1),
|
| 136 |
+
272: ("Model", ASCII, 1),
|
| 137 |
+
273: ("StripOffsets", LONG, 0),
|
| 138 |
+
274: ("Orientation", SHORT, 1),
|
| 139 |
+
277: ("SamplesPerPixel", SHORT, 1),
|
| 140 |
+
278: ("RowsPerStrip", LONG, 1),
|
| 141 |
+
279: ("StripByteCounts", LONG, 0),
|
| 142 |
+
280: ("MinSampleValue", SHORT, 0),
|
| 143 |
+
281: ("MaxSampleValue", SHORT, 0),
|
| 144 |
+
282: ("XResolution", RATIONAL, 1),
|
| 145 |
+
283: ("YResolution", RATIONAL, 1),
|
| 146 |
+
284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),
|
| 147 |
+
285: ("PageName", ASCII, 1),
|
| 148 |
+
286: ("XPosition", RATIONAL, 1),
|
| 149 |
+
287: ("YPosition", RATIONAL, 1),
|
| 150 |
+
288: ("FreeOffsets", LONG, 1),
|
| 151 |
+
289: ("FreeByteCounts", LONG, 1),
|
| 152 |
+
290: ("GrayResponseUnit", SHORT, 1),
|
| 153 |
+
291: ("GrayResponseCurve", SHORT, 0),
|
| 154 |
+
292: ("T4Options", LONG, 1),
|
| 155 |
+
293: ("T6Options", LONG, 1),
|
| 156 |
+
296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),
|
| 157 |
+
297: ("PageNumber", SHORT, 2),
|
| 158 |
+
301: ("TransferFunction", SHORT, 0),
|
| 159 |
+
305: ("Software", ASCII, 1),
|
| 160 |
+
306: ("DateTime", ASCII, 1),
|
| 161 |
+
315: ("Artist", ASCII, 1),
|
| 162 |
+
316: ("HostComputer", ASCII, 1),
|
| 163 |
+
317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),
|
| 164 |
+
318: ("WhitePoint", RATIONAL, 2),
|
| 165 |
+
319: ("PrimaryChromaticities", RATIONAL, 6),
|
| 166 |
+
320: ("ColorMap", SHORT, 0),
|
| 167 |
+
321: ("HalftoneHints", SHORT, 2),
|
| 168 |
+
322: ("TileWidth", LONG, 1),
|
| 169 |
+
323: ("TileLength", LONG, 1),
|
| 170 |
+
324: ("TileOffsets", LONG, 0),
|
| 171 |
+
325: ("TileByteCounts", LONG, 0),
|
| 172 |
+
330: ("SubIFDs", LONG, 0),
|
| 173 |
+
332: ("InkSet", SHORT, 1),
|
| 174 |
+
333: ("InkNames", ASCII, 1),
|
| 175 |
+
334: ("NumberOfInks", SHORT, 1),
|
| 176 |
+
336: ("DotRange", SHORT, 0),
|
| 177 |
+
337: ("TargetPrinter", ASCII, 1),
|
| 178 |
+
338: ("ExtraSamples", SHORT, 0),
|
| 179 |
+
339: ("SampleFormat", SHORT, 0),
|
| 180 |
+
340: ("SMinSampleValue", DOUBLE, 0),
|
| 181 |
+
341: ("SMaxSampleValue", DOUBLE, 0),
|
| 182 |
+
342: ("TransferRange", SHORT, 6),
|
| 183 |
+
347: ("JPEGTables", UNDEFINED, 1),
|
| 184 |
+
# obsolete JPEG tags
|
| 185 |
+
512: ("JPEGProc", SHORT, 1),
|
| 186 |
+
513: ("JPEGInterchangeFormat", LONG, 1),
|
| 187 |
+
514: ("JPEGInterchangeFormatLength", LONG, 1),
|
| 188 |
+
515: ("JPEGRestartInterval", SHORT, 1),
|
| 189 |
+
517: ("JPEGLosslessPredictors", SHORT, 0),
|
| 190 |
+
518: ("JPEGPointTransforms", SHORT, 0),
|
| 191 |
+
519: ("JPEGQTables", LONG, 0),
|
| 192 |
+
520: ("JPEGDCTables", LONG, 0),
|
| 193 |
+
521: ("JPEGACTables", LONG, 0),
|
| 194 |
+
529: ("YCbCrCoefficients", RATIONAL, 3),
|
| 195 |
+
530: ("YCbCrSubSampling", SHORT, 2),
|
| 196 |
+
531: ("YCbCrPositioning", SHORT, 1),
|
| 197 |
+
532: ("ReferenceBlackWhite", RATIONAL, 6),
|
| 198 |
+
700: ("XMP", BYTE, 0),
|
| 199 |
+
33432: ("Copyright", ASCII, 1),
|
| 200 |
+
33723: ("IptcNaaInfo", UNDEFINED, 1),
|
| 201 |
+
34377: ("PhotoshopInfo", BYTE, 0),
|
| 202 |
+
# FIXME add more tags here
|
| 203 |
+
34665: ("ExifIFD", LONG, 1),
|
| 204 |
+
34675: ("ICCProfile", UNDEFINED, 1),
|
| 205 |
+
34853: ("GPSInfoIFD", LONG, 1),
|
| 206 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 207 |
+
37724: ("ImageSourceData", UNDEFINED, 1),
|
| 208 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 209 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 210 |
+
# MPInfo
|
| 211 |
+
45056: ("MPFVersion", UNDEFINED, 1),
|
| 212 |
+
45057: ("NumberOfImages", LONG, 1),
|
| 213 |
+
45058: ("MPEntry", UNDEFINED, 1),
|
| 214 |
+
45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
|
| 215 |
+
45060: ("TotalFrames", LONG, 1),
|
| 216 |
+
45313: ("MPIndividualNum", LONG, 1),
|
| 217 |
+
45569: ("PanOrientation", LONG, 1),
|
| 218 |
+
45570: ("PanOverlap_H", RATIONAL, 1),
|
| 219 |
+
45571: ("PanOverlap_V", RATIONAL, 1),
|
| 220 |
+
45572: ("BaseViewpointNum", LONG, 1),
|
| 221 |
+
45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
|
| 222 |
+
45574: ("BaselineLength", RATIONAL, 1),
|
| 223 |
+
45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
|
| 224 |
+
45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
|
| 225 |
+
45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
|
| 226 |
+
45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
|
| 227 |
+
45579: ("YawAngle", SIGNED_RATIONAL, 1),
|
| 228 |
+
45580: ("PitchAngle", SIGNED_RATIONAL, 1),
|
| 229 |
+
45581: ("RollAngle", SIGNED_RATIONAL, 1),
|
| 230 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 231 |
+
50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
|
| 232 |
+
50780: ("BestQualityScale", RATIONAL, 1),
|
| 233 |
+
50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
|
| 234 |
+
50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
|
| 235 |
+
}
|
| 236 |
+
TAGS_V2_GROUPS = {
|
| 237 |
+
# ExifIFD
|
| 238 |
+
34665: {
|
| 239 |
+
36864: ("ExifVersion", UNDEFINED, 1),
|
| 240 |
+
40960: ("FlashPixVersion", UNDEFINED, 1),
|
| 241 |
+
40965: ("InteroperabilityIFD", LONG, 1),
|
| 242 |
+
41730: ("CFAPattern", UNDEFINED, 1),
|
| 243 |
+
},
|
| 244 |
+
# GPSInfoIFD
|
| 245 |
+
34853: {
|
| 246 |
+
0: ("GPSVersionID", BYTE, 4),
|
| 247 |
+
1: ("GPSLatitudeRef", ASCII, 2),
|
| 248 |
+
2: ("GPSLatitude", RATIONAL, 3),
|
| 249 |
+
3: ("GPSLongitudeRef", ASCII, 2),
|
| 250 |
+
4: ("GPSLongitude", RATIONAL, 3),
|
| 251 |
+
5: ("GPSAltitudeRef", BYTE, 1),
|
| 252 |
+
6: ("GPSAltitude", RATIONAL, 1),
|
| 253 |
+
7: ("GPSTimeStamp", RATIONAL, 3),
|
| 254 |
+
8: ("GPSSatellites", ASCII, 0),
|
| 255 |
+
9: ("GPSStatus", ASCII, 2),
|
| 256 |
+
10: ("GPSMeasureMode", ASCII, 2),
|
| 257 |
+
11: ("GPSDOP", RATIONAL, 1),
|
| 258 |
+
12: ("GPSSpeedRef", ASCII, 2),
|
| 259 |
+
13: ("GPSSpeed", RATIONAL, 1),
|
| 260 |
+
14: ("GPSTrackRef", ASCII, 2),
|
| 261 |
+
15: ("GPSTrack", RATIONAL, 1),
|
| 262 |
+
16: ("GPSImgDirectionRef", ASCII, 2),
|
| 263 |
+
17: ("GPSImgDirection", RATIONAL, 1),
|
| 264 |
+
18: ("GPSMapDatum", ASCII, 0),
|
| 265 |
+
19: ("GPSDestLatitudeRef", ASCII, 2),
|
| 266 |
+
20: ("GPSDestLatitude", RATIONAL, 3),
|
| 267 |
+
21: ("GPSDestLongitudeRef", ASCII, 2),
|
| 268 |
+
22: ("GPSDestLongitude", RATIONAL, 3),
|
| 269 |
+
23: ("GPSDestBearingRef", ASCII, 2),
|
| 270 |
+
24: ("GPSDestBearing", RATIONAL, 1),
|
| 271 |
+
25: ("GPSDestDistanceRef", ASCII, 2),
|
| 272 |
+
26: ("GPSDestDistance", RATIONAL, 1),
|
| 273 |
+
27: ("GPSProcessingMethod", UNDEFINED, 0),
|
| 274 |
+
28: ("GPSAreaInformation", UNDEFINED, 0),
|
| 275 |
+
29: ("GPSDateStamp", ASCII, 11),
|
| 276 |
+
30: ("GPSDifferential", SHORT, 1),
|
| 277 |
+
},
|
| 278 |
+
# InteroperabilityIFD
|
| 279 |
+
40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
# Legacy Tags structure
|
| 283 |
+
# these tags aren't included above, but were in the previous versions
|
| 284 |
+
TAGS = {
|
| 285 |
+
347: "JPEGTables",
|
| 286 |
+
700: "XMP",
|
| 287 |
+
# Additional Exif Info
|
| 288 |
+
32932: "Wang Annotation",
|
| 289 |
+
33434: "ExposureTime",
|
| 290 |
+
33437: "FNumber",
|
| 291 |
+
33445: "MD FileTag",
|
| 292 |
+
33446: "MD ScalePixel",
|
| 293 |
+
33447: "MD ColorTable",
|
| 294 |
+
33448: "MD LabName",
|
| 295 |
+
33449: "MD SampleInfo",
|
| 296 |
+
33450: "MD PrepDate",
|
| 297 |
+
33451: "MD PrepTime",
|
| 298 |
+
33452: "MD FileUnits",
|
| 299 |
+
33550: "ModelPixelScaleTag",
|
| 300 |
+
33723: "IptcNaaInfo",
|
| 301 |
+
33918: "INGR Packet Data Tag",
|
| 302 |
+
33919: "INGR Flag Registers",
|
| 303 |
+
33920: "IrasB Transformation Matrix",
|
| 304 |
+
33922: "ModelTiepointTag",
|
| 305 |
+
34264: "ModelTransformationTag",
|
| 306 |
+
34377: "PhotoshopInfo",
|
| 307 |
+
34735: "GeoKeyDirectoryTag",
|
| 308 |
+
34736: "GeoDoubleParamsTag",
|
| 309 |
+
34737: "GeoAsciiParamsTag",
|
| 310 |
+
34850: "ExposureProgram",
|
| 311 |
+
34852: "SpectralSensitivity",
|
| 312 |
+
34855: "ISOSpeedRatings",
|
| 313 |
+
34856: "OECF",
|
| 314 |
+
34864: "SensitivityType",
|
| 315 |
+
34865: "StandardOutputSensitivity",
|
| 316 |
+
34866: "RecommendedExposureIndex",
|
| 317 |
+
34867: "ISOSpeed",
|
| 318 |
+
34868: "ISOSpeedLatitudeyyy",
|
| 319 |
+
34869: "ISOSpeedLatitudezzz",
|
| 320 |
+
34908: "HylaFAX FaxRecvParams",
|
| 321 |
+
34909: "HylaFAX FaxSubAddress",
|
| 322 |
+
34910: "HylaFAX FaxRecvTime",
|
| 323 |
+
36864: "ExifVersion",
|
| 324 |
+
36867: "DateTimeOriginal",
|
| 325 |
+
36868: "DateTimeDigitized",
|
| 326 |
+
37121: "ComponentsConfiguration",
|
| 327 |
+
37122: "CompressedBitsPerPixel",
|
| 328 |
+
37724: "ImageSourceData",
|
| 329 |
+
37377: "ShutterSpeedValue",
|
| 330 |
+
37378: "ApertureValue",
|
| 331 |
+
37379: "BrightnessValue",
|
| 332 |
+
37380: "ExposureBiasValue",
|
| 333 |
+
37381: "MaxApertureValue",
|
| 334 |
+
37382: "SubjectDistance",
|
| 335 |
+
37383: "MeteringMode",
|
| 336 |
+
37384: "LightSource",
|
| 337 |
+
37385: "Flash",
|
| 338 |
+
37386: "FocalLength",
|
| 339 |
+
37396: "SubjectArea",
|
| 340 |
+
37500: "MakerNote",
|
| 341 |
+
37510: "UserComment",
|
| 342 |
+
37520: "SubSec",
|
| 343 |
+
37521: "SubSecTimeOriginal",
|
| 344 |
+
37522: "SubsecTimeDigitized",
|
| 345 |
+
40960: "FlashPixVersion",
|
| 346 |
+
40961: "ColorSpace",
|
| 347 |
+
40962: "PixelXDimension",
|
| 348 |
+
40963: "PixelYDimension",
|
| 349 |
+
40964: "RelatedSoundFile",
|
| 350 |
+
40965: "InteroperabilityIFD",
|
| 351 |
+
41483: "FlashEnergy",
|
| 352 |
+
41484: "SpatialFrequencyResponse",
|
| 353 |
+
41486: "FocalPlaneXResolution",
|
| 354 |
+
41487: "FocalPlaneYResolution",
|
| 355 |
+
41488: "FocalPlaneResolutionUnit",
|
| 356 |
+
41492: "SubjectLocation",
|
| 357 |
+
41493: "ExposureIndex",
|
| 358 |
+
41495: "SensingMethod",
|
| 359 |
+
41728: "FileSource",
|
| 360 |
+
41729: "SceneType",
|
| 361 |
+
41730: "CFAPattern",
|
| 362 |
+
41985: "CustomRendered",
|
| 363 |
+
41986: "ExposureMode",
|
| 364 |
+
41987: "WhiteBalance",
|
| 365 |
+
41988: "DigitalZoomRatio",
|
| 366 |
+
41989: "FocalLengthIn35mmFilm",
|
| 367 |
+
41990: "SceneCaptureType",
|
| 368 |
+
41991: "GainControl",
|
| 369 |
+
41992: "Contrast",
|
| 370 |
+
41993: "Saturation",
|
| 371 |
+
41994: "Sharpness",
|
| 372 |
+
41995: "DeviceSettingDescription",
|
| 373 |
+
41996: "SubjectDistanceRange",
|
| 374 |
+
42016: "ImageUniqueID",
|
| 375 |
+
42032: "CameraOwnerName",
|
| 376 |
+
42033: "BodySerialNumber",
|
| 377 |
+
42034: "LensSpecification",
|
| 378 |
+
42035: "LensMake",
|
| 379 |
+
42036: "LensModel",
|
| 380 |
+
42037: "LensSerialNumber",
|
| 381 |
+
42112: "GDAL_METADATA",
|
| 382 |
+
42113: "GDAL_NODATA",
|
| 383 |
+
42240: "Gamma",
|
| 384 |
+
50215: "Oce Scanjob Description",
|
| 385 |
+
50216: "Oce Application Selector",
|
| 386 |
+
50217: "Oce Identification Number",
|
| 387 |
+
50218: "Oce ImageLogic Characteristics",
|
| 388 |
+
# Adobe DNG
|
| 389 |
+
50706: "DNGVersion",
|
| 390 |
+
50707: "DNGBackwardVersion",
|
| 391 |
+
50708: "UniqueCameraModel",
|
| 392 |
+
50709: "LocalizedCameraModel",
|
| 393 |
+
50710: "CFAPlaneColor",
|
| 394 |
+
50711: "CFALayout",
|
| 395 |
+
50712: "LinearizationTable",
|
| 396 |
+
50713: "BlackLevelRepeatDim",
|
| 397 |
+
50714: "BlackLevel",
|
| 398 |
+
50715: "BlackLevelDeltaH",
|
| 399 |
+
50716: "BlackLevelDeltaV",
|
| 400 |
+
50717: "WhiteLevel",
|
| 401 |
+
50718: "DefaultScale",
|
| 402 |
+
50719: "DefaultCropOrigin",
|
| 403 |
+
50720: "DefaultCropSize",
|
| 404 |
+
50721: "ColorMatrix1",
|
| 405 |
+
50722: "ColorMatrix2",
|
| 406 |
+
50723: "CameraCalibration1",
|
| 407 |
+
50724: "CameraCalibration2",
|
| 408 |
+
50725: "ReductionMatrix1",
|
| 409 |
+
50726: "ReductionMatrix2",
|
| 410 |
+
50727: "AnalogBalance",
|
| 411 |
+
50728: "AsShotNeutral",
|
| 412 |
+
50729: "AsShotWhiteXY",
|
| 413 |
+
50730: "BaselineExposure",
|
| 414 |
+
50731: "BaselineNoise",
|
| 415 |
+
50732: "BaselineSharpness",
|
| 416 |
+
50733: "BayerGreenSplit",
|
| 417 |
+
50734: "LinearResponseLimit",
|
| 418 |
+
50735: "CameraSerialNumber",
|
| 419 |
+
50736: "LensInfo",
|
| 420 |
+
50737: "ChromaBlurRadius",
|
| 421 |
+
50738: "AntiAliasStrength",
|
| 422 |
+
50740: "DNGPrivateData",
|
| 423 |
+
50778: "CalibrationIlluminant1",
|
| 424 |
+
50779: "CalibrationIlluminant2",
|
| 425 |
+
50784: "Alias Layer Metadata",
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
TAGS_V2: dict[int, TagInfo] = {}
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def _populate():
|
| 432 |
+
for k, v in _tags_v2.items():
|
| 433 |
+
# Populate legacy structure.
|
| 434 |
+
TAGS[k] = v[0]
|
| 435 |
+
if len(v) == 4:
|
| 436 |
+
for sk, sv in v[3].items():
|
| 437 |
+
TAGS[(k, sv)] = sk
|
| 438 |
+
|
| 439 |
+
TAGS_V2[k] = TagInfo(k, *v)
|
| 440 |
+
|
| 441 |
+
for tags in TAGS_V2_GROUPS.values():
|
| 442 |
+
for k, v in tags.items():
|
| 443 |
+
tags[k] = TagInfo(k, *v)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
_populate()
|
| 447 |
+
##
|
| 448 |
+
# Map type numbers to type names -- defined in ImageFileDirectory.
|
| 449 |
+
|
| 450 |
+
TYPES: dict[int, str] = {}
|
| 451 |
+
|
| 452 |
+
#
|
| 453 |
+
# These tags are handled by default in libtiff, without
|
| 454 |
+
# adding to the custom dictionary. From tif_dir.c, searching for
|
| 455 |
+
# case TIFFTAG in the _TIFFVSetField function:
|
| 456 |
+
# Line: item.
|
| 457 |
+
# 148: case TIFFTAG_SUBFILETYPE:
|
| 458 |
+
# 151: case TIFFTAG_IMAGEWIDTH:
|
| 459 |
+
# 154: case TIFFTAG_IMAGELENGTH:
|
| 460 |
+
# 157: case TIFFTAG_BITSPERSAMPLE:
|
| 461 |
+
# 181: case TIFFTAG_COMPRESSION:
|
| 462 |
+
# 202: case TIFFTAG_PHOTOMETRIC:
|
| 463 |
+
# 205: case TIFFTAG_THRESHHOLDING:
|
| 464 |
+
# 208: case TIFFTAG_FILLORDER:
|
| 465 |
+
# 214: case TIFFTAG_ORIENTATION:
|
| 466 |
+
# 221: case TIFFTAG_SAMPLESPERPIXEL:
|
| 467 |
+
# 228: case TIFFTAG_ROWSPERSTRIP:
|
| 468 |
+
# 238: case TIFFTAG_MINSAMPLEVALUE:
|
| 469 |
+
# 241: case TIFFTAG_MAXSAMPLEVALUE:
|
| 470 |
+
# 244: case TIFFTAG_SMINSAMPLEVALUE:
|
| 471 |
+
# 247: case TIFFTAG_SMAXSAMPLEVALUE:
|
| 472 |
+
# 250: case TIFFTAG_XRESOLUTION:
|
| 473 |
+
# 256: case TIFFTAG_YRESOLUTION:
|
| 474 |
+
# 262: case TIFFTAG_PLANARCONFIG:
|
| 475 |
+
# 268: case TIFFTAG_XPOSITION:
|
| 476 |
+
# 271: case TIFFTAG_YPOSITION:
|
| 477 |
+
# 274: case TIFFTAG_RESOLUTIONUNIT:
|
| 478 |
+
# 280: case TIFFTAG_PAGENUMBER:
|
| 479 |
+
# 284: case TIFFTAG_HALFTONEHINTS:
|
| 480 |
+
# 288: case TIFFTAG_COLORMAP:
|
| 481 |
+
# 294: case TIFFTAG_EXTRASAMPLES:
|
| 482 |
+
# 298: case TIFFTAG_MATTEING:
|
| 483 |
+
# 305: case TIFFTAG_TILEWIDTH:
|
| 484 |
+
# 316: case TIFFTAG_TILELENGTH:
|
| 485 |
+
# 327: case TIFFTAG_TILEDEPTH:
|
| 486 |
+
# 333: case TIFFTAG_DATATYPE:
|
| 487 |
+
# 344: case TIFFTAG_SAMPLEFORMAT:
|
| 488 |
+
# 361: case TIFFTAG_IMAGEDEPTH:
|
| 489 |
+
# 364: case TIFFTAG_SUBIFD:
|
| 490 |
+
# 376: case TIFFTAG_YCBCRPOSITIONING:
|
| 491 |
+
# 379: case TIFFTAG_YCBCRSUBSAMPLING:
|
| 492 |
+
# 383: case TIFFTAG_TRANSFERFUNCTION:
|
| 493 |
+
# 389: case TIFFTAG_REFERENCEBLACKWHITE:
|
| 494 |
+
# 393: case TIFFTAG_INKNAMES:
|
| 495 |
+
|
| 496 |
+
# Following pseudo-tags are also handled by default in libtiff:
|
| 497 |
+
# TIFFTAG_JPEGQUALITY 65537
|
| 498 |
+
|
| 499 |
+
# some of these are not in our TAGS_V2 dict and were included from tiff.h
|
| 500 |
+
|
| 501 |
+
# This list also exists in encode.c
|
| 502 |
+
LIBTIFF_CORE = {
|
| 503 |
+
255,
|
| 504 |
+
256,
|
| 505 |
+
257,
|
| 506 |
+
258,
|
| 507 |
+
259,
|
| 508 |
+
262,
|
| 509 |
+
263,
|
| 510 |
+
266,
|
| 511 |
+
274,
|
| 512 |
+
277,
|
| 513 |
+
278,
|
| 514 |
+
280,
|
| 515 |
+
281,
|
| 516 |
+
340,
|
| 517 |
+
341,
|
| 518 |
+
282,
|
| 519 |
+
283,
|
| 520 |
+
284,
|
| 521 |
+
286,
|
| 522 |
+
287,
|
| 523 |
+
296,
|
| 524 |
+
297,
|
| 525 |
+
321,
|
| 526 |
+
320,
|
| 527 |
+
338,
|
| 528 |
+
32995,
|
| 529 |
+
322,
|
| 530 |
+
323,
|
| 531 |
+
32998,
|
| 532 |
+
32996,
|
| 533 |
+
339,
|
| 534 |
+
32997,
|
| 535 |
+
330,
|
| 536 |
+
531,
|
| 537 |
+
530,
|
| 538 |
+
301,
|
| 539 |
+
532,
|
| 540 |
+
333,
|
| 541 |
+
# as above
|
| 542 |
+
269, # this has been in our tests forever, and works
|
| 543 |
+
65537,
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
|
| 547 |
+
LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
|
| 548 |
+
LIBTIFF_CORE.remove(323) # Tiled images
|
| 549 |
+
LIBTIFF_CORE.remove(333) # Ink Names either
|
| 550 |
+
|
| 551 |
+
# Note to advanced users: There may be combinations of these
|
| 552 |
+
# parameters and values that when added properly, will work and
|
| 553 |
+
# produce valid tiff images that may work in your application.
|
| 554 |
+
# It is safe to add and remove tags from this set from Pillow's point
|
| 555 |
+
# of view so long as you test against libtiff.
|
.venv/lib/python3.11/site-packages/PIL/WalImageFile.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# WAL file handling
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2003-04-23 fl created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2003 by Fredrik Lundh.
|
| 11 |
+
#
|
| 12 |
+
# See the README file for information on usage and redistribution.
|
| 13 |
+
#
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This reader is based on the specification available from:
|
| 17 |
+
https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
|
| 18 |
+
and has been tested with a few sample files found using google.
|
| 19 |
+
|
| 20 |
+
.. note::
|
| 21 |
+
This format cannot be automatically recognized, so the reader
|
| 22 |
+
is not registered for use with :py:func:`PIL.Image.open()`.
|
| 23 |
+
To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
from . import Image, ImageFile
|
| 28 |
+
from ._binary import i32le as i32
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class WalImageFile(ImageFile.ImageFile):
|
| 32 |
+
format = "WAL"
|
| 33 |
+
format_description = "Quake2 Texture"
|
| 34 |
+
|
| 35 |
+
def _open(self) -> None:
|
| 36 |
+
self._mode = "P"
|
| 37 |
+
|
| 38 |
+
# read header fields
|
| 39 |
+
header = self.fp.read(32 + 24 + 32 + 12)
|
| 40 |
+
self._size = i32(header, 32), i32(header, 36)
|
| 41 |
+
Image._decompression_bomb_check(self.size)
|
| 42 |
+
|
| 43 |
+
# load pixel data
|
| 44 |
+
offset = i32(header, 40)
|
| 45 |
+
self.fp.seek(offset)
|
| 46 |
+
|
| 47 |
+
# strings are null-terminated
|
| 48 |
+
self.info["name"] = header[:32].split(b"\0", 1)[0]
|
| 49 |
+
next_name = header[56 : 56 + 32].split(b"\0", 1)[0]
|
| 50 |
+
if next_name:
|
| 51 |
+
self.info["next_name"] = next_name
|
| 52 |
+
|
| 53 |
+
def load(self):
|
| 54 |
+
if not self.im:
|
| 55 |
+
self.im = Image.core.new(self.mode, self.size)
|
| 56 |
+
self.frombytes(self.fp.read(self.size[0] * self.size[1]))
|
| 57 |
+
self.putpalette(quake2palette)
|
| 58 |
+
return Image.Image.load(self)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def open(filename):
|
| 62 |
+
"""
|
| 63 |
+
Load texture from a Quake2 WAL texture file.
|
| 64 |
+
|
| 65 |
+
By default, a Quake2 standard palette is attached to the texture.
|
| 66 |
+
To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
|
| 67 |
+
|
| 68 |
+
:param filename: WAL file name, or an opened file handle.
|
| 69 |
+
:returns: An image instance.
|
| 70 |
+
"""
|
| 71 |
+
return WalImageFile(filename)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
quake2palette = (
|
| 75 |
+
# default palette taken from piffo 0.93 by Hans Häggström
|
| 76 |
+
b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
|
| 77 |
+
b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
|
| 78 |
+
b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
|
| 79 |
+
b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
|
| 80 |
+
b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
|
| 81 |
+
b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
|
| 82 |
+
b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
|
| 83 |
+
b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
|
| 84 |
+
b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
|
| 85 |
+
b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
|
| 86 |
+
b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
|
| 87 |
+
b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
|
| 88 |
+
b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
|
| 89 |
+
b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
|
| 90 |
+
b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
|
| 91 |
+
b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
|
| 92 |
+
b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
|
| 93 |
+
b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
|
| 94 |
+
b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
|
| 95 |
+
b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
|
| 96 |
+
b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
|
| 97 |
+
b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
|
| 98 |
+
b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
|
| 99 |
+
b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
|
| 100 |
+
b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
|
| 101 |
+
b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
|
| 102 |
+
b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
|
| 103 |
+
b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
|
| 104 |
+
b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
|
| 105 |
+
b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
|
| 106 |
+
b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
|
| 107 |
+
b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
|
| 108 |
+
b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
|
| 109 |
+
b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
|
| 110 |
+
b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
|
| 111 |
+
b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
|
| 112 |
+
b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
|
| 113 |
+
b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
|
| 114 |
+
b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
|
| 115 |
+
b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
|
| 116 |
+
b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
|
| 117 |
+
b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
|
| 118 |
+
b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
|
| 119 |
+
b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
|
| 120 |
+
b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
|
| 121 |
+
b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
|
| 122 |
+
b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
|
| 123 |
+
b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
|
| 124 |
+
)
|
.venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from typing import IO, Any
|
| 5 |
+
|
| 6 |
+
from . import Image, ImageFile
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from . import _webp
|
| 10 |
+
|
| 11 |
+
SUPPORTED = True
|
| 12 |
+
except ImportError:
|
| 13 |
+
SUPPORTED = False
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_VALID_WEBP_MODES = {"RGBX": True, "RGBA": True, "RGB": True}
|
| 17 |
+
|
| 18 |
+
_VALID_WEBP_LEGACY_MODES = {"RGB": True, "RGBA": True}
|
| 19 |
+
|
| 20 |
+
_VP8_MODES_BY_IDENTIFIER = {
|
| 21 |
+
b"VP8 ": "RGB",
|
| 22 |
+
b"VP8X": "RGBA",
|
| 23 |
+
b"VP8L": "RGBA", # lossless
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _accept(prefix: bytes) -> bool | str:
|
| 28 |
+
is_riff_file_format = prefix[:4] == b"RIFF"
|
| 29 |
+
is_webp_file = prefix[8:12] == b"WEBP"
|
| 30 |
+
is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
|
| 31 |
+
|
| 32 |
+
if is_riff_file_format and is_webp_file and is_valid_vp8_mode:
|
| 33 |
+
if not SUPPORTED:
|
| 34 |
+
return (
|
| 35 |
+
"image file could not be identified because WEBP support not installed"
|
| 36 |
+
)
|
| 37 |
+
return True
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class WebPImageFile(ImageFile.ImageFile):
|
| 42 |
+
format = "WEBP"
|
| 43 |
+
format_description = "WebP image"
|
| 44 |
+
__loaded = 0
|
| 45 |
+
__logical_frame = 0
|
| 46 |
+
|
| 47 |
+
def _open(self) -> None:
|
| 48 |
+
if not _webp.HAVE_WEBPANIM:
|
| 49 |
+
# Legacy mode
|
| 50 |
+
data, width, height, self._mode, icc_profile, exif = _webp.WebPDecode(
|
| 51 |
+
self.fp.read()
|
| 52 |
+
)
|
| 53 |
+
if icc_profile:
|
| 54 |
+
self.info["icc_profile"] = icc_profile
|
| 55 |
+
if exif:
|
| 56 |
+
self.info["exif"] = exif
|
| 57 |
+
self._size = width, height
|
| 58 |
+
self.fp = BytesIO(data)
|
| 59 |
+
self.tile = [("raw", (0, 0) + self.size, 0, self.mode)]
|
| 60 |
+
self.n_frames = 1
|
| 61 |
+
self.is_animated = False
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
# Use the newer AnimDecoder API to parse the (possibly) animated file,
|
| 65 |
+
# and access muxed chunks like ICC/EXIF/XMP.
|
| 66 |
+
self._decoder = _webp.WebPAnimDecoder(self.fp.read())
|
| 67 |
+
|
| 68 |
+
# Get info from decoder
|
| 69 |
+
width, height, loop_count, bgcolor, frame_count, mode = self._decoder.get_info()
|
| 70 |
+
self._size = width, height
|
| 71 |
+
self.info["loop"] = loop_count
|
| 72 |
+
bg_a, bg_r, bg_g, bg_b = (
|
| 73 |
+
(bgcolor >> 24) & 0xFF,
|
| 74 |
+
(bgcolor >> 16) & 0xFF,
|
| 75 |
+
(bgcolor >> 8) & 0xFF,
|
| 76 |
+
bgcolor & 0xFF,
|
| 77 |
+
)
|
| 78 |
+
self.info["background"] = (bg_r, bg_g, bg_b, bg_a)
|
| 79 |
+
self.n_frames = frame_count
|
| 80 |
+
self.is_animated = self.n_frames > 1
|
| 81 |
+
self._mode = "RGB" if mode == "RGBX" else mode
|
| 82 |
+
self.rawmode = mode
|
| 83 |
+
self.tile = []
|
| 84 |
+
|
| 85 |
+
# Attempt to read ICC / EXIF / XMP chunks from file
|
| 86 |
+
icc_profile = self._decoder.get_chunk("ICCP")
|
| 87 |
+
exif = self._decoder.get_chunk("EXIF")
|
| 88 |
+
xmp = self._decoder.get_chunk("XMP ")
|
| 89 |
+
if icc_profile:
|
| 90 |
+
self.info["icc_profile"] = icc_profile
|
| 91 |
+
if exif:
|
| 92 |
+
self.info["exif"] = exif
|
| 93 |
+
if xmp:
|
| 94 |
+
self.info["xmp"] = xmp
|
| 95 |
+
|
| 96 |
+
# Initialize seek state
|
| 97 |
+
self._reset(reset=False)
|
| 98 |
+
|
| 99 |
+
def _getexif(self) -> dict[str, Any] | None:
|
| 100 |
+
if "exif" not in self.info:
|
| 101 |
+
return None
|
| 102 |
+
return self.getexif()._get_merged_dict()
|
| 103 |
+
|
| 104 |
+
def seek(self, frame: int) -> None:
|
| 105 |
+
if not self._seek_check(frame):
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
# Set logical frame to requested position
|
| 109 |
+
self.__logical_frame = frame
|
| 110 |
+
|
| 111 |
+
def _reset(self, reset: bool = True) -> None:
|
| 112 |
+
if reset:
|
| 113 |
+
self._decoder.reset()
|
| 114 |
+
self.__physical_frame = 0
|
| 115 |
+
self.__loaded = -1
|
| 116 |
+
self.__timestamp = 0
|
| 117 |
+
|
| 118 |
+
def _get_next(self):
|
| 119 |
+
# Get next frame
|
| 120 |
+
ret = self._decoder.get_next()
|
| 121 |
+
self.__physical_frame += 1
|
| 122 |
+
|
| 123 |
+
# Check if an error occurred
|
| 124 |
+
if ret is None:
|
| 125 |
+
self._reset() # Reset just to be safe
|
| 126 |
+
self.seek(0)
|
| 127 |
+
msg = "failed to decode next frame in WebP file"
|
| 128 |
+
raise EOFError(msg)
|
| 129 |
+
|
| 130 |
+
# Compute duration
|
| 131 |
+
data, timestamp = ret
|
| 132 |
+
duration = timestamp - self.__timestamp
|
| 133 |
+
self.__timestamp = timestamp
|
| 134 |
+
|
| 135 |
+
# libwebp gives frame end, adjust to start of frame
|
| 136 |
+
timestamp -= duration
|
| 137 |
+
return data, timestamp, duration
|
| 138 |
+
|
| 139 |
+
def _seek(self, frame: int) -> None:
|
| 140 |
+
if self.__physical_frame == frame:
|
| 141 |
+
return # Nothing to do
|
| 142 |
+
if frame < self.__physical_frame:
|
| 143 |
+
self._reset() # Rewind to beginning
|
| 144 |
+
while self.__physical_frame < frame:
|
| 145 |
+
self._get_next() # Advance to the requested frame
|
| 146 |
+
|
| 147 |
+
def load(self):
|
| 148 |
+
if _webp.HAVE_WEBPANIM:
|
| 149 |
+
if self.__loaded != self.__logical_frame:
|
| 150 |
+
self._seek(self.__logical_frame)
|
| 151 |
+
|
| 152 |
+
# We need to load the image data for this frame
|
| 153 |
+
data, timestamp, duration = self._get_next()
|
| 154 |
+
self.info["timestamp"] = timestamp
|
| 155 |
+
self.info["duration"] = duration
|
| 156 |
+
self.__loaded = self.__logical_frame
|
| 157 |
+
|
| 158 |
+
# Set tile
|
| 159 |
+
if self.fp and self._exclusive_fp:
|
| 160 |
+
self.fp.close()
|
| 161 |
+
self.fp = BytesIO(data)
|
| 162 |
+
self.tile = [("raw", (0, 0) + self.size, 0, self.rawmode)]
|
| 163 |
+
|
| 164 |
+
return super().load()
|
| 165 |
+
|
| 166 |
+
def load_seek(self, pos: int) -> None:
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
def tell(self) -> int:
|
| 170 |
+
if not _webp.HAVE_WEBPANIM:
|
| 171 |
+
return super().tell()
|
| 172 |
+
|
| 173 |
+
return self.__logical_frame
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 177 |
+
encoderinfo = im.encoderinfo.copy()
|
| 178 |
+
append_images = list(encoderinfo.get("append_images", []))
|
| 179 |
+
|
| 180 |
+
# If total frame count is 1, then save using the legacy API, which
|
| 181 |
+
# will preserve non-alpha modes
|
| 182 |
+
total = 0
|
| 183 |
+
for ims in [im] + append_images:
|
| 184 |
+
total += getattr(ims, "n_frames", 1)
|
| 185 |
+
if total == 1:
|
| 186 |
+
_save(im, fp, filename)
|
| 187 |
+
return
|
| 188 |
+
|
| 189 |
+
background: int | tuple[int, ...] = (0, 0, 0, 0)
|
| 190 |
+
if "background" in encoderinfo:
|
| 191 |
+
background = encoderinfo["background"]
|
| 192 |
+
elif "background" in im.info:
|
| 193 |
+
background = im.info["background"]
|
| 194 |
+
if isinstance(background, int):
|
| 195 |
+
# GifImagePlugin stores a global color table index in
|
| 196 |
+
# info["background"]. So it must be converted to an RGBA value
|
| 197 |
+
palette = im.getpalette()
|
| 198 |
+
if palette:
|
| 199 |
+
r, g, b = palette[background * 3 : (background + 1) * 3]
|
| 200 |
+
background = (r, g, b, 255)
|
| 201 |
+
else:
|
| 202 |
+
background = (background, background, background, 255)
|
| 203 |
+
|
| 204 |
+
duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
|
| 205 |
+
loop = im.encoderinfo.get("loop", 0)
|
| 206 |
+
minimize_size = im.encoderinfo.get("minimize_size", False)
|
| 207 |
+
kmin = im.encoderinfo.get("kmin", None)
|
| 208 |
+
kmax = im.encoderinfo.get("kmax", None)
|
| 209 |
+
allow_mixed = im.encoderinfo.get("allow_mixed", False)
|
| 210 |
+
verbose = False
|
| 211 |
+
lossless = im.encoderinfo.get("lossless", False)
|
| 212 |
+
quality = im.encoderinfo.get("quality", 80)
|
| 213 |
+
alpha_quality = im.encoderinfo.get("alpha_quality", 100)
|
| 214 |
+
method = im.encoderinfo.get("method", 0)
|
| 215 |
+
icc_profile = im.encoderinfo.get("icc_profile") or ""
|
| 216 |
+
exif = im.encoderinfo.get("exif", "")
|
| 217 |
+
if isinstance(exif, Image.Exif):
|
| 218 |
+
exif = exif.tobytes()
|
| 219 |
+
xmp = im.encoderinfo.get("xmp", "")
|
| 220 |
+
if allow_mixed:
|
| 221 |
+
lossless = False
|
| 222 |
+
|
| 223 |
+
# Sensible keyframe defaults are from gif2webp.c script
|
| 224 |
+
if kmin is None:
|
| 225 |
+
kmin = 9 if lossless else 3
|
| 226 |
+
if kmax is None:
|
| 227 |
+
kmax = 17 if lossless else 5
|
| 228 |
+
|
| 229 |
+
# Validate background color
|
| 230 |
+
if (
|
| 231 |
+
not isinstance(background, (list, tuple))
|
| 232 |
+
or len(background) != 4
|
| 233 |
+
or not all(0 <= v < 256 for v in background)
|
| 234 |
+
):
|
| 235 |
+
msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"
|
| 236 |
+
raise OSError(msg)
|
| 237 |
+
|
| 238 |
+
# Convert to packed uint
|
| 239 |
+
bg_r, bg_g, bg_b, bg_a = background
|
| 240 |
+
background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0)
|
| 241 |
+
|
| 242 |
+
# Setup the WebP animation encoder
|
| 243 |
+
enc = _webp.WebPAnimEncoder(
|
| 244 |
+
im.size[0],
|
| 245 |
+
im.size[1],
|
| 246 |
+
background,
|
| 247 |
+
loop,
|
| 248 |
+
minimize_size,
|
| 249 |
+
kmin,
|
| 250 |
+
kmax,
|
| 251 |
+
allow_mixed,
|
| 252 |
+
verbose,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# Add each frame
|
| 256 |
+
frame_idx = 0
|
| 257 |
+
timestamp = 0
|
| 258 |
+
cur_idx = im.tell()
|
| 259 |
+
try:
|
| 260 |
+
for ims in [im] + append_images:
|
| 261 |
+
# Get # of frames in this image
|
| 262 |
+
nfr = getattr(ims, "n_frames", 1)
|
| 263 |
+
|
| 264 |
+
for idx in range(nfr):
|
| 265 |
+
ims.seek(idx)
|
| 266 |
+
ims.load()
|
| 267 |
+
|
| 268 |
+
# Make sure image mode is supported
|
| 269 |
+
frame = ims
|
| 270 |
+
rawmode = ims.mode
|
| 271 |
+
if ims.mode not in _VALID_WEBP_MODES:
|
| 272 |
+
alpha = (
|
| 273 |
+
"A" in ims.mode
|
| 274 |
+
or "a" in ims.mode
|
| 275 |
+
or (ims.mode == "P" and "A" in ims.im.getpalettemode())
|
| 276 |
+
)
|
| 277 |
+
rawmode = "RGBA" if alpha else "RGB"
|
| 278 |
+
frame = ims.convert(rawmode)
|
| 279 |
+
|
| 280 |
+
if rawmode == "RGB":
|
| 281 |
+
# For faster conversion, use RGBX
|
| 282 |
+
rawmode = "RGBX"
|
| 283 |
+
|
| 284 |
+
# Append the frame to the animation encoder
|
| 285 |
+
enc.add(
|
| 286 |
+
frame.tobytes("raw", rawmode),
|
| 287 |
+
round(timestamp),
|
| 288 |
+
frame.size[0],
|
| 289 |
+
frame.size[1],
|
| 290 |
+
rawmode,
|
| 291 |
+
lossless,
|
| 292 |
+
quality,
|
| 293 |
+
alpha_quality,
|
| 294 |
+
method,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
# Update timestamp and frame index
|
| 298 |
+
if isinstance(duration, (list, tuple)):
|
| 299 |
+
timestamp += duration[frame_idx]
|
| 300 |
+
else:
|
| 301 |
+
timestamp += duration
|
| 302 |
+
frame_idx += 1
|
| 303 |
+
|
| 304 |
+
finally:
|
| 305 |
+
im.seek(cur_idx)
|
| 306 |
+
|
| 307 |
+
# Force encoder to flush frames
|
| 308 |
+
enc.add(None, round(timestamp), 0, 0, "", lossless, quality, alpha_quality, 0)
|
| 309 |
+
|
| 310 |
+
# Get the final output from the encoder
|
| 311 |
+
data = enc.assemble(icc_profile, exif, xmp)
|
| 312 |
+
if data is None:
|
| 313 |
+
msg = "cannot write file as WebP (encoder returned None)"
|
| 314 |
+
raise OSError(msg)
|
| 315 |
+
|
| 316 |
+
fp.write(data)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 320 |
+
lossless = im.encoderinfo.get("lossless", False)
|
| 321 |
+
quality = im.encoderinfo.get("quality", 80)
|
| 322 |
+
alpha_quality = im.encoderinfo.get("alpha_quality", 100)
|
| 323 |
+
icc_profile = im.encoderinfo.get("icc_profile") or ""
|
| 324 |
+
exif = im.encoderinfo.get("exif", b"")
|
| 325 |
+
if isinstance(exif, Image.Exif):
|
| 326 |
+
exif = exif.tobytes()
|
| 327 |
+
if exif.startswith(b"Exif\x00\x00"):
|
| 328 |
+
exif = exif[6:]
|
| 329 |
+
xmp = im.encoderinfo.get("xmp", "")
|
| 330 |
+
method = im.encoderinfo.get("method", 4)
|
| 331 |
+
exact = 1 if im.encoderinfo.get("exact") else 0
|
| 332 |
+
|
| 333 |
+
if im.mode not in _VALID_WEBP_LEGACY_MODES:
|
| 334 |
+
im = im.convert("RGBA" if im.has_transparency_data else "RGB")
|
| 335 |
+
|
| 336 |
+
data = _webp.WebPEncode(
|
| 337 |
+
im.tobytes(),
|
| 338 |
+
im.size[0],
|
| 339 |
+
im.size[1],
|
| 340 |
+
lossless,
|
| 341 |
+
float(quality),
|
| 342 |
+
float(alpha_quality),
|
| 343 |
+
im.mode,
|
| 344 |
+
icc_profile,
|
| 345 |
+
method,
|
| 346 |
+
exact,
|
| 347 |
+
exif,
|
| 348 |
+
xmp,
|
| 349 |
+
)
|
| 350 |
+
if data is None:
|
| 351 |
+
msg = "cannot write file as WebP (encoder returned None)"
|
| 352 |
+
raise OSError(msg)
|
| 353 |
+
|
| 354 |
+
fp.write(data)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
|
| 358 |
+
if SUPPORTED:
|
| 359 |
+
Image.register_save(WebPImageFile.format, _save)
|
| 360 |
+
if _webp.HAVE_WEBPANIM:
|
| 361 |
+
Image.register_save_all(WebPImageFile.format, _save_all)
|
| 362 |
+
Image.register_extension(WebPImageFile.format, ".webp")
|
| 363 |
+
Image.register_mime(WebPImageFile.format, "image/webp")
|
.venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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-22 fl Turned into a stub driver
|
| 10 |
+
# 2004-02-23 fl Added EMF support
|
| 11 |
+
#
|
| 12 |
+
# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
|
| 13 |
+
# Copyright (c) Fredrik Lundh 1996.
|
| 14 |
+
#
|
| 15 |
+
# See the README file for information on usage and redistribution.
|
| 16 |
+
#
|
| 17 |
+
# WMF/EMF reference documentation:
|
| 18 |
+
# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf
|
| 19 |
+
# http://wvware.sourceforge.net/caolan/index.html
|
| 20 |
+
# http://wvware.sourceforge.net/caolan/ora-wmf.html
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from typing import IO
|
| 24 |
+
|
| 25 |
+
from . import Image, ImageFile
|
| 26 |
+
from ._binary import i16le as word
|
| 27 |
+
from ._binary import si16le as short
|
| 28 |
+
from ._binary import si32le as _long
|
| 29 |
+
|
| 30 |
+
_handler = None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def register_handler(handler: ImageFile.StubHandler | None) -> None:
|
| 34 |
+
"""
|
| 35 |
+
Install application-specific WMF image handler.
|
| 36 |
+
|
| 37 |
+
:param handler: Handler object.
|
| 38 |
+
"""
|
| 39 |
+
global _handler
|
| 40 |
+
_handler = handler
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if hasattr(Image.core, "drawwmf"):
|
| 44 |
+
# install default handler (windows only)
|
| 45 |
+
|
| 46 |
+
class WmfHandler(ImageFile.StubHandler):
|
| 47 |
+
def open(self, im: ImageFile.StubImageFile) -> None:
|
| 48 |
+
im._mode = "RGB"
|
| 49 |
+
self.bbox = im.info["wmf_bbox"]
|
| 50 |
+
|
| 51 |
+
def load(self, im: ImageFile.StubImageFile) -> Image.Image:
|
| 52 |
+
im.fp.seek(0) # rewind
|
| 53 |
+
return Image.frombytes(
|
| 54 |
+
"RGB",
|
| 55 |
+
im.size,
|
| 56 |
+
Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
|
| 57 |
+
"raw",
|
| 58 |
+
"BGR",
|
| 59 |
+
(im.size[0] * 3 + 3) & -4,
|
| 60 |
+
-1,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
register_handler(WmfHandler())
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
# --------------------------------------------------------------------
|
| 67 |
+
# Read WMF file
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _accept(prefix: bytes) -> bool:
|
| 71 |
+
return (
|
| 72 |
+
prefix[:6] == b"\xd7\xcd\xc6\x9a\x00\x00" or prefix[:4] == b"\x01\x00\x00\x00"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
##
|
| 77 |
+
# Image plugin for Windows metafiles.
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class WmfStubImageFile(ImageFile.StubImageFile):
|
| 81 |
+
format = "WMF"
|
| 82 |
+
format_description = "Windows Metafile"
|
| 83 |
+
|
| 84 |
+
def _open(self) -> None:
|
| 85 |
+
self._inch = None
|
| 86 |
+
|
| 87 |
+
# check placable header
|
| 88 |
+
s = self.fp.read(80)
|
| 89 |
+
|
| 90 |
+
if s[:6] == b"\xd7\xcd\xc6\x9a\x00\x00":
|
| 91 |
+
# placeable windows metafile
|
| 92 |
+
|
| 93 |
+
# get units per inch
|
| 94 |
+
self._inch = word(s, 14)
|
| 95 |
+
|
| 96 |
+
# get bounding box
|
| 97 |
+
x0 = short(s, 6)
|
| 98 |
+
y0 = short(s, 8)
|
| 99 |
+
x1 = short(s, 10)
|
| 100 |
+
y1 = short(s, 12)
|
| 101 |
+
|
| 102 |
+
# normalize size to 72 dots per inch
|
| 103 |
+
self.info["dpi"] = 72
|
| 104 |
+
size = (
|
| 105 |
+
(x1 - x0) * self.info["dpi"] // self._inch,
|
| 106 |
+
(y1 - y0) * self.info["dpi"] // self._inch,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 110 |
+
|
| 111 |
+
# sanity check (standard metafile header)
|
| 112 |
+
if s[22:26] != b"\x01\x00\t\x00":
|
| 113 |
+
msg = "Unsupported WMF file format"
|
| 114 |
+
raise SyntaxError(msg)
|
| 115 |
+
|
| 116 |
+
elif s[:4] == b"\x01\x00\x00\x00" and s[40:44] == b" EMF":
|
| 117 |
+
# enhanced metafile
|
| 118 |
+
|
| 119 |
+
# get bounding box
|
| 120 |
+
x0 = _long(s, 8)
|
| 121 |
+
y0 = _long(s, 12)
|
| 122 |
+
x1 = _long(s, 16)
|
| 123 |
+
y1 = _long(s, 20)
|
| 124 |
+
|
| 125 |
+
# get frame (in 0.01 millimeter units)
|
| 126 |
+
frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
|
| 127 |
+
|
| 128 |
+
size = x1 - x0, y1 - y0
|
| 129 |
+
|
| 130 |
+
# calculate dots per inch from bbox and frame
|
| 131 |
+
xdpi = 2540.0 * (x1 - y0) / (frame[2] - frame[0])
|
| 132 |
+
ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
|
| 133 |
+
|
| 134 |
+
self.info["wmf_bbox"] = x0, y0, x1, y1
|
| 135 |
+
|
| 136 |
+
if xdpi == ydpi:
|
| 137 |
+
self.info["dpi"] = xdpi
|
| 138 |
+
else:
|
| 139 |
+
self.info["dpi"] = xdpi, ydpi
|
| 140 |
+
|
| 141 |
+
else:
|
| 142 |
+
msg = "Unsupported file format"
|
| 143 |
+
raise SyntaxError(msg)
|
| 144 |
+
|
| 145 |
+
self._mode = "RGB"
|
| 146 |
+
self._size = size
|
| 147 |
+
|
| 148 |
+
loader = self._load()
|
| 149 |
+
if loader:
|
| 150 |
+
loader.open(self)
|
| 151 |
+
|
| 152 |
+
def _load(self) -> ImageFile.StubHandler | None:
|
| 153 |
+
return _handler
|
| 154 |
+
|
| 155 |
+
def load(self, dpi=None):
|
| 156 |
+
if dpi is not None and self._inch is not None:
|
| 157 |
+
self.info["dpi"] = dpi
|
| 158 |
+
x0, y0, x1, y1 = self.info["wmf_bbox"]
|
| 159 |
+
self._size = (
|
| 160 |
+
(x1 - x0) * self.info["dpi"] // self._inch,
|
| 161 |
+
(y1 - y0) * self.info["dpi"] // self._inch,
|
| 162 |
+
)
|
| 163 |
+
return super().load()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
|
| 167 |
+
if _handler is None or not hasattr(_handler, "save"):
|
| 168 |
+
msg = "WMF save handler not installed"
|
| 169 |
+
raise OSError(msg)
|
| 170 |
+
_handler.save(im, fp, filename)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
#
|
| 174 |
+
# --------------------------------------------------------------------
|
| 175 |
+
# Registry stuff
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
|
| 179 |
+
Image.register_save(WmfStubImageFile.format, _save)
|
| 180 |
+
|
| 181 |
+
Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])
|