Merge pull request #8336 from radarhere/type_hint_imagefile

This commit is contained in:
Hugo van Kemenade 2024-09-04 14:56:23 +03:00 committed by GitHub
commit 8aa1e9209b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 156 additions and 81 deletions

View File

@ -238,7 +238,9 @@ class MockImageFile(ImageFile.ImageFile):
self.rawmode = "RGBA" self.rawmode = "RGBA"
self._mode = "RGBA" self._mode = "RGBA"
self._size = (200, 200) self._size = (200, 200)
self.tile = [("MOCK", (xoff, yoff, xoff + xsize, yoff + ysize), 32, None)] self.tile = [
ImageFile._Tile("MOCK", (xoff, yoff, xoff + xsize, yoff + ysize), 32, None)
]
class CodecsTest: class CodecsTest:
@ -268,7 +270,7 @@ class TestPyDecoder(CodecsTest):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
im = MockImageFile(buf) im = MockImageFile(buf)
im.tile = [("MOCK", None, 32, None)] im.tile = [ImageFile._Tile("MOCK", None, 32, None)]
im.load() im.load()
@ -281,12 +283,12 @@ class TestPyDecoder(CodecsTest):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
im = MockImageFile(buf) im = MockImageFile(buf)
im.tile = [("MOCK", (xoff, yoff, -10, yoff + ysize), 32, None)] im.tile = [ImageFile._Tile("MOCK", (xoff, yoff, -10, yoff + ysize), 32, None)]
with pytest.raises(ValueError): with pytest.raises(ValueError):
im.load() im.load()
im.tile = [("MOCK", (xoff, yoff, xoff + xsize, -10), 32, None)] im.tile = [ImageFile._Tile("MOCK", (xoff, yoff, xoff + xsize, -10), 32, None)]
with pytest.raises(ValueError): with pytest.raises(ValueError):
im.load() im.load()
@ -294,12 +296,20 @@ class TestPyDecoder(CodecsTest):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
im = MockImageFile(buf) im = MockImageFile(buf)
im.tile = [("MOCK", (xoff, yoff, xoff + xsize + 100, yoff + ysize), 32, None)] im.tile = [
ImageFile._Tile(
"MOCK", (xoff, yoff, xoff + xsize + 100, yoff + ysize), 32, None
)
]
with pytest.raises(ValueError): with pytest.raises(ValueError):
im.load() im.load()
im.tile = [("MOCK", (xoff, yoff, xoff + xsize, yoff + ysize + 100), 32, None)] im.tile = [
ImageFile._Tile(
"MOCK", (xoff, yoff, xoff + xsize, yoff + ysize + 100), 32, None
)
]
with pytest.raises(ValueError): with pytest.raises(ValueError):
im.load() im.load()
@ -336,7 +346,7 @@ class TestPyEncoder(CodecsTest):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
im = MockImageFile(buf) im = MockImageFile(buf)
im.tile = [("MOCK", None, 32, None)] im.tile = [ImageFile._Tile("MOCK", None, 32, None)]
fp = BytesIO() fp = BytesIO()
ImageFile._save(im, fp, [ImageFile._Tile("MOCK", None, 0, "RGB")]) ImageFile._save(im, fp, [ImageFile._Tile("MOCK", None, 0, "RGB")])

View File

@ -246,7 +246,9 @@ class DdsImageFile(ImageFile.ImageFile):
msg = f"Unimplemented pixel format {repr(fourcc)}" msg = f"Unimplemented pixel format {repr(fourcc)}"
raise NotImplementedError(msg) raise NotImplementedError(msg)
self.tile = [(self.decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))] self.tile = [
ImageFile._Tile(self.decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))
]
def load_seek(self, pos: int) -> None: def load_seek(self, pos: int) -> None:
pass pass

View File

@ -273,7 +273,7 @@ class BlpImageFile(ImageFile.ImageFile):
raise BLPFormatError(msg) raise BLPFormatError(msg)
self._mode = "RGBA" if self._blp_alpha_depth else "RGB" self._mode = "RGBA" if self._blp_alpha_depth else "RGB"
self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))] self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
class _BLPBaseDecoder(ImageFile.PyDecoder): class _BLPBaseDecoder(ImageFile.PyDecoder):
@ -372,7 +372,10 @@ class BLP1Decoder(_BLPBaseDecoder):
Image._decompression_bomb_check(image.size) Image._decompression_bomb_check(image.size)
if image.mode == "CMYK": if image.mode == "CMYK":
decoder_name, extents, offset, args = image.tile[0] decoder_name, extents, offset, args = image.tile[0]
image.tile = [(decoder_name, extents, offset, (args[0], "CMYK"))] assert isinstance(args, tuple)
image.tile = [
ImageFile._Tile(decoder_name, extents, offset, (args[0], "CMYK"))
]
r, g, b = image.convert("RGB").split() r, g, b = image.convert("RGB").split()
reversed_image = Image.merge("RGB", (b, g, r)) reversed_image = Image.merge("RGB", (b, g, r))
self.set_as_raw(reversed_image.tobytes()) self.set_as_raw(reversed_image.tobytes())

View File

@ -296,7 +296,7 @@ class BmpImageFile(ImageFile.ImageFile):
args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3)) args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
args.append(file_info["direction"]) args.append(file_info["direction"])
self.tile = [ self.tile = [
( ImageFile._Tile(
decoder_name, decoder_name,
(0, 0, file_info["width"], file_info["height"]), (0, 0, file_info["width"], file_info["height"]),
offset or self.fp.tell(), offset or self.fp.tell(),

View File

@ -17,7 +17,7 @@
# #
from __future__ import annotations from __future__ import annotations
from . import BmpImagePlugin, Image from . import BmpImagePlugin, Image, ImageFile
from ._binary import i16le as i16 from ._binary import i16le as i16
from ._binary import i32le as i32 from ._binary import i32le as i32
@ -64,7 +64,7 @@ class CurImageFile(BmpImagePlugin.BmpImageFile):
# patch up the bitmap height # patch up the bitmap height
self._size = self.size[0], self.size[1] // 2 self._size = self.size[0], self.size[1] // 2
d, e, o, a = self.tile[0] d, e, o, a = self.tile[0]
self.tile[0] = d, (0, 0) + self.size, o, a self.tile[0] = ImageFile._Tile(d, (0, 0) + self.size, o, a)
# #

View File

@ -367,7 +367,7 @@ class DdsImageFile(ImageFile.ImageFile):
mask_count = 3 mask_count = 3
masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4)) masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4))
self.tile = [("dds_rgb", extents, 0, (bitcount, masks))] self.tile = [ImageFile._Tile("dds_rgb", extents, 0, (bitcount, masks))]
return return
elif pfflags & DDPF.LUMINANCE: elif pfflags & DDPF.LUMINANCE:
if bitcount == 8: if bitcount == 8:

View File

@ -67,7 +67,7 @@ class FitsImageFile(ImageFile.ImageFile):
raise ValueError(msg) raise ValueError(msg)
offset += self.fp.tell() - 80 offset += self.fp.tell() - 80
self.tile = [(decoder_name, (0, 0) + self.size, offset, args)] self.tile = [ImageFile._Tile(decoder_name, (0, 0) + self.size, offset, args)]
def _get_size( def _get_size(
self, headers: dict[bytes, bytes], prefix: bytes self, headers: dict[bytes, bytes], prefix: bytes

View File

@ -159,7 +159,7 @@ class FliImageFile(ImageFile.ImageFile):
framesize = i32(s) framesize = i32(s)
self.decodermaxblock = framesize self.decodermaxblock = framesize
self.tile = [("fli", (0, 0) + self.size, self.__offset, None)] self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset, None)]
self.__offset += framesize self.__offset += framesize

View File

@ -166,7 +166,7 @@ class FpxImageFile(ImageFile.ImageFile):
if compression == 0: if compression == 0:
self.tile.append( self.tile.append(
( ImageFile._Tile(
"raw", "raw",
(x, y, x1, y1), (x, y, x1, y1),
i32(s, i) + 28, i32(s, i) + 28,
@ -177,7 +177,7 @@ class FpxImageFile(ImageFile.ImageFile):
elif compression == 1: elif compression == 1:
# FIXME: the fill decoder is not implemented # FIXME: the fill decoder is not implemented
self.tile.append( self.tile.append(
( ImageFile._Tile(
"fill", "fill",
(x, y, x1, y1), (x, y, x1, y1),
i32(s, i) + 28, i32(s, i) + 28,
@ -205,7 +205,7 @@ class FpxImageFile(ImageFile.ImageFile):
jpegmode = rawmode jpegmode = rawmode
self.tile.append( self.tile.append(
( ImageFile._Tile(
"jpeg", "jpeg",
(x, y, x1, y1), (x, y, x1, y1),
i32(s, i) + 28, i32(s, i) + 28,

View File

@ -93,9 +93,9 @@ class FtexImageFile(ImageFile.ImageFile):
if format == Format.DXT1: if format == Format.DXT1:
self._mode = "RGBA" self._mode = "RGBA"
self.tile = [("bcn", (0, 0) + self.size, 0, 1)] self.tile = [ImageFile._Tile("bcn", (0, 0) + self.size, 0, (1,))]
elif format == Format.UNCOMPRESSED: elif format == Format.UNCOMPRESSED:
self.tile = [("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))] self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))]
else: else:
msg = f"Invalid texture compression format: {repr(format)}" msg = f"Invalid texture compression format: {repr(format)}"
raise ValueError(msg) raise ValueError(msg)

View File

@ -72,7 +72,7 @@ class GdImageFile(ImageFile.ImageFile):
) )
self.tile = [ self.tile = [
( ImageFile._Tile(
"raw", "raw",
(0, 0) + self.size, (0, 0) + self.size,
7 + true_color_offset + 4 + 256 * 4, 7 + true_color_offset + 4 + 256 * 4,

View File

@ -407,7 +407,7 @@ class GifImageFile(ImageFile.ImageFile):
elif self.mode not in ("RGB", "RGBA"): elif self.mode not in ("RGB", "RGBA"):
transparency = frame_transparency transparency = frame_transparency
self.tile = [ self.tile = [
( ImageFile._Tile(
"gif", "gif",
(x0, y0, x1, y1), (x0, y0, x1, y1),
self.__offset, self.__offset,

View File

@ -228,7 +228,7 @@ class IcoFile:
# change tile dimension to only encompass XOR image # change tile dimension to only encompass XOR image
im._size = (im.size[0], int(im.size[1] / 2)) im._size = (im.size[0], int(im.size[1] / 2))
d, e, o, a = im.tile[0] d, e, o, a = im.tile[0]
im.tile[0] = d, (0, 0) + im.size, o, a im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a)
# figure out where AND mask image starts # figure out where AND mask image starts
if header.bpp == 32: if header.bpp == 32:

View File

@ -253,7 +253,11 @@ class ImImageFile(ImageFile.ImageFile):
# use bit decoder (if necessary) # use bit decoder (if necessary)
bits = int(self.rawmode[2:]) bits = int(self.rawmode[2:])
if bits not in [8, 16, 32]: if bits not in [8, 16, 32]:
self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))] self.tile = [
ImageFile._Tile(
"bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
)
]
return return
except ValueError: except ValueError:
pass pass
@ -263,13 +267,17 @@ class ImImageFile(ImageFile.ImageFile):
# ever stumbled upon such a file ;-) # ever stumbled upon such a file ;-)
size = self.size[0] * self.size[1] size = self.size[0] * self.size[1]
self.tile = [ self.tile = [
("raw", (0, 0) + self.size, offs, ("G", 0, -1)), ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)), ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)), ImageFile._Tile(
"raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
),
] ]
else: else:
# LabEye/IFUNC files # LabEye/IFUNC files
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
]
@property @property
def n_frames(self) -> int: def n_frames(self) -> int:
@ -295,7 +303,9 @@ class ImImageFile(ImageFile.ImageFile):
self.fp = self._fp self.fp = self._fp
self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
]
def tell(self) -> int: def tell(self) -> int:
return self.frame return self.frame

View File

@ -3641,7 +3641,10 @@ def merge(mode: str, bands: Sequence[Image]) -> Image:
def register_open( def register_open(
id: str, id: str,
factory: Callable[[IO[bytes], str | bytes], ImageFile.ImageFile], factory: (
Callable[[IO[bytes], str | bytes], ImageFile.ImageFile]
| type[ImageFile.ImageFile]
),
accept: Callable[[bytes], bool | str] | None = None, accept: Callable[[bytes], bool | str] | None = None,
) -> None: ) -> None:
""" """

View File

@ -34,12 +34,15 @@ import itertools
import os import os
import struct import struct
import sys import sys
from typing import IO, Any, NamedTuple from typing import IO, TYPE_CHECKING, Any, NamedTuple, cast
from . import Image from . import Image
from ._deprecate import deprecate from ._deprecate import deprecate
from ._util import is_path from ._util import is_path
if TYPE_CHECKING:
from ._typing import StrOrBytesPath
MAXBLOCK = 65536 MAXBLOCK = 65536
SAFEBLOCK = 1024 * 1024 SAFEBLOCK = 1024 * 1024
@ -107,32 +110,34 @@ class _Tile(NamedTuple):
class ImageFile(Image.Image): class ImageFile(Image.Image):
"""Base class for image file format handlers.""" """Base class for image file format handlers."""
def __init__(self, fp=None, filename=None): def __init__(
self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
) -> None:
super().__init__() super().__init__()
self._min_frame = 0 self._min_frame = 0
self.custom_mimetype = None self.custom_mimetype: str | None = None
self.tile = None self.tile: list[_Tile] = []
""" A list of tile descriptors, or ``None`` """ """ A list of tile descriptors, or ``None`` """
self.readonly = 1 # until we know better self.readonly = 1 # until we know better
self.decoderconfig = () self.decoderconfig: tuple[Any, ...] = ()
self.decodermaxblock = MAXBLOCK self.decodermaxblock = MAXBLOCK
if is_path(fp): if is_path(fp):
# filename # filename
self.fp = open(fp, "rb") self.fp = open(fp, "rb")
self.filename = fp self.filename = os.path.realpath(os.fspath(fp))
self._exclusive_fp = True self._exclusive_fp = True
else: else:
# stream # stream
self.fp = fp self.fp = cast(IO[bytes], fp)
self.filename = filename self.filename = filename if filename is not None else ""
# can be overridden # can be overridden
self._exclusive_fp = None self._exclusive_fp = False
try: try:
try: try:
@ -155,6 +160,9 @@ class ImageFile(Image.Image):
self.fp.close() self.fp.close()
raise raise
def _open(self) -> None:
pass
def get_format_mimetype(self) -> str | None: def get_format_mimetype(self) -> str | None:
if self.custom_mimetype: if self.custom_mimetype:
return self.custom_mimetype return self.custom_mimetype
@ -178,7 +186,7 @@ class ImageFile(Image.Image):
def load(self) -> Image.core.PixelAccess | None: def load(self) -> Image.core.PixelAccess | None:
"""Load image data based on tile list""" """Load image data based on tile list"""
if self.tile is None: if not self.tile and self._im is None:
msg = "cannot load this image" msg = "cannot load this image"
raise OSError(msg) raise OSError(msg)
@ -214,6 +222,7 @@ class ImageFile(Image.Image):
args = (args, 0, 1) args = (args, 0, 1)
if ( if (
decoder_name == "raw" decoder_name == "raw"
and isinstance(args, tuple)
and len(args) >= 3 and len(args) >= 3
and args[0] == self.mode and args[0] == self.mode
and args[0] in Image._MAPMODES and args[0] in Image._MAPMODES

View File

@ -58,7 +58,7 @@ class ImtImageFile(ImageFile.ImageFile):
if s == b"\x0C": if s == b"\x0C":
# image data begins # image data begins
self.tile = [ self.tile = [
( ImageFile._Tile(
"raw", "raw",
(0, 0) + self.size, (0, 0) + self.size,
self.fp.tell() - len(buffer), self.fp.tell() - len(buffer),

View File

@ -147,7 +147,9 @@ class IptcImageFile(ImageFile.ImageFile):
# tile # tile
if tag == (8, 10): if tag == (8, 10):
self.tile = [("iptc", (0, 0) + self.size, offset, compression)] self.tile = [
ImageFile._Tile("iptc", (0, 0) + self.size, offset, compression)
]
def load(self) -> Image.core.PixelAccess | None: def load(self) -> Image.core.PixelAccess | None:
if len(self.tile) != 1 or self.tile[0][0] != "iptc": if len(self.tile) != 1 or self.tile[0][0] != "iptc":

View File

@ -286,7 +286,7 @@ class Jpeg2KImageFile(ImageFile.ImageFile):
length = -1 length = -1
self.tile = [ self.tile = [
( ImageFile._Tile(
"jpeg2k", "jpeg2k",
(0, 0) + self.size, (0, 0) + self.size,
0, 0,
@ -338,8 +338,9 @@ class Jpeg2KImageFile(ImageFile.ImageFile):
# Update the reduce and layers settings # Update the reduce and layers settings
t = self.tile[0] t = self.tile[0]
assert isinstance(t[3], tuple)
t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4]) t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
self.tile = [(t[0], (0, 0) + self.size, t[2], t3)] self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)]
return ImageFile.ImageFile.load(self) return ImageFile.ImageFile.load(self)

View File

@ -372,7 +372,9 @@ class JpegImageFile(ImageFile.ImageFile):
rawmode = self.mode rawmode = self.mode
if self.mode == "CMYK": if self.mode == "CMYK":
rawmode = "CMYK;I" # assume adobe conventions rawmode = "CMYK;I" # assume adobe conventions
self.tile = [("jpeg", (0, 0) + self.size, 0, (rawmode, ""))] self.tile = [
ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, ""))
]
# self.__offset = self.fp.tell() # self.__offset = self.fp.tell()
break break
s = self.fp.read(1) s = self.fp.read(1)
@ -423,6 +425,7 @@ class JpegImageFile(ImageFile.ImageFile):
scale = 1 scale = 1
original_size = self.size original_size = self.size
assert isinstance(a, tuple)
if a[0] == "RGB" and mode in ["L", "YCbCr"]: if a[0] == "RGB" and mode in ["L", "YCbCr"]:
self._mode = mode self._mode = mode
a = mode, "" a = mode, ""
@ -432,6 +435,7 @@ class JpegImageFile(ImageFile.ImageFile):
for s in [8, 4, 2, 1]: for s in [8, 4, 2, 1]:
if scale >= s: if scale >= s:
break break
assert e is not None
e = ( e = (
e[0], e[0],
e[1], e[1],
@ -441,7 +445,7 @@ class JpegImageFile(ImageFile.ImageFile):
self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s) self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
scale = s scale = s
self.tile = [(d, e, o, a)] self.tile = [ImageFile._Tile(d, e, o, a)]
self.decoderconfig = (scale, 0) self.decoderconfig = (scale, 0)
box = (0, 0, original_size[0] / scale, original_size[1] / scale) box = (0, 0, original_size[0] / scale, original_size[1] / scale)
@ -854,7 +858,7 @@ def _save_cjpeg(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
## ##
# Factory for making JPEG and MPO instances # Factory for making JPEG and MPO instances
def jpeg_factory( def jpeg_factory(
fp: IO[bytes] | None = None, filename: str | bytes | None = None fp: IO[bytes], filename: str | bytes | None = None
) -> JpegImageFile | MpoImageFile: ) -> JpegImageFile | MpoImageFile:
im = JpegImageFile(fp, filename) im = JpegImageFile(fp, filename)
try: try:

View File

@ -67,7 +67,9 @@ class McIdasImageFile(ImageFile.ImageFile):
offset = w[34] + w[15] offset = w[34] + w[15]
stride = w[15] + w[10] * w[11] * w[14] stride = w[15] + w[10] * w[11] * w[14]
self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))
]
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -26,6 +26,7 @@ from typing import IO, Any, cast
from . import ( from . import (
Image, Image,
ImageFile,
ImageSequence, ImageSequence,
JpegImagePlugin, JpegImagePlugin,
TiffImagePlugin, TiffImagePlugin,
@ -145,7 +146,9 @@ class MpoImageFile(JpegImagePlugin.JpegImageFile):
if self.info.get("exif") != original_exif: if self.info.get("exif") != original_exif:
self._reload_exif() self._reload_exif()
self.tile = [("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])] self.tile = [
ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])
]
self.__frame = frame self.__frame = frame
def tell(self) -> int: def tell(self) -> int:

View File

@ -70,9 +70,9 @@ class MspImageFile(ImageFile.ImageFile):
self._size = i16(s, 4), i16(s, 6) self._size = i16(s, 4), i16(s, 6)
if s[:4] == b"DanM": if s[:4] == b"DanM":
self.tile = [("raw", (0, 0) + self.size, 32, ("1", 0, 1))] self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, ("1", 0, 1))]
else: else:
self.tile = [("MSP", (0, 0) + self.size, 32, None)] self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32, None)]
class MspDecoder(ImageFile.PyDecoder): class MspDecoder(ImageFile.PyDecoder):

View File

@ -47,7 +47,7 @@ class PcdImageFile(ImageFile.ImageFile):
self._mode = "RGB" self._mode = "RGB"
self._size = 768, 512 # FIXME: not correct for rotated images! self._size = 768, 512 # FIXME: not correct for rotated images!
self.tile = [("pcd", (0, 0) + self.size, 96 * 2048, None)] self.tile = [ImageFile._Tile("pcd", (0, 0) + self.size, 96 * 2048, None)]
def load_end(self) -> None: def load_end(self) -> None:
if self.tile_post_rotate: if self.tile_post_rotate:

View File

@ -128,7 +128,9 @@ class PcxImageFile(ImageFile.ImageFile):
bbox = (0, 0) + self.size bbox = (0, 0) + self.size
logger.debug("size: %sx%s", *self.size) logger.debug("size: %sx%s", *self.size)
self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] self.tile = [
ImageFile._Tile("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))
]
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -61,7 +61,9 @@ class PixarImageFile(ImageFile.ImageFile):
# FIXME: to be continued... # FIXME: to be continued...
# create tile descriptor (assuming "dumped") # create tile descriptor (assuming "dumped")
self.tile = [("raw", (0, 0) + self.size, 1024, (self.mode, 0, 1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, 1024, (self.mode, 0, 1))
]
# #

View File

@ -151,7 +151,9 @@ class PpmImageFile(ImageFile.ImageFile):
decoder_name = "ppm" decoder_name = "ppm"
args = rawmode if decoder_name == "raw" else (rawmode, maxval) args = rawmode if decoder_name == "raw" else (rawmode, maxval)
self.tile = [(decoder_name, (0, 0) + self.size, self.fp.tell(), args)] self.tile = [
ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args)
]
# #

View File

@ -277,8 +277,8 @@ def _layerinfo(
def _maketile( def _maketile(
file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int
) -> list[ImageFile._Tile] | None: ) -> list[ImageFile._Tile]:
tiles = None tiles = []
read = file.read read = file.read
compression = i16(read(2)) compression = i16(read(2))
@ -291,7 +291,6 @@ def _maketile(
if compression == 0: if compression == 0:
# #
# raw compression # raw compression
tiles = []
for channel in range(channels): for channel in range(channels):
layer = mode[channel] layer = mode[channel]
if mode == "CMYK": if mode == "CMYK":
@ -303,7 +302,6 @@ def _maketile(
# #
# packbits compression # packbits compression
i = 0 i = 0
tiles = []
bytecount = read(channels * ysize * 2) bytecount = read(channels * ysize * 2)
offset = file.tell() offset = file.tell()
for channel in range(channels): for channel in range(channels):

View File

@ -32,7 +32,7 @@ class QoiImageFile(ImageFile.ImageFile):
self._mode = "RGB" if channels == 3 else "RGBA" self._mode = "RGB" if channels == 3 else "RGBA"
self.fp.seek(1, os.SEEK_CUR) # colorspace self.fp.seek(1, os.SEEK_CUR) # colorspace
self.tile = [("qoi", (0, 0) + self._size, self.fp.tell(), None)] self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell(), None)]
class QoiDecoder(ImageFile.PyDecoder): class QoiDecoder(ImageFile.PyDecoder):

View File

@ -109,19 +109,28 @@ class SgiImageFile(ImageFile.ImageFile):
pagesize = xsize * ysize * bpc pagesize = xsize * ysize * bpc
if bpc == 2: if bpc == 2:
self.tile = [ self.tile = [
("SGI16", (0, 0) + self.size, headlen, (self.mode, 0, orientation)) ImageFile._Tile(
"SGI16",
(0, 0) + self.size,
headlen,
(self.mode, 0, orientation),
)
] ]
else: else:
self.tile = [] self.tile = []
offset = headlen offset = headlen
for layer in self.mode: for layer in self.mode:
self.tile.append( self.tile.append(
("raw", (0, 0) + self.size, offset, (layer, 0, orientation)) ImageFile._Tile(
"raw", (0, 0) + self.size, offset, (layer, 0, orientation)
)
) )
offset += pagesize offset += pagesize
elif compression == 1: elif compression == 1:
self.tile = [ self.tile = [
("sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)) ImageFile._Tile(
"sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)
)
] ]

View File

@ -154,7 +154,9 @@ class SpiderImageFile(ImageFile.ImageFile):
self.rawmode = "F;32F" self.rawmode = "F;32F"
self._mode = "F" self._mode = "F"
self.tile = [("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, offset, (self.rawmode, 0, 1))
]
self._fp = self.fp # FIXME: hack self._fp = self.fp # FIXME: hack
@property @property

View File

@ -124,9 +124,13 @@ class SunImageFile(ImageFile.ImageFile):
# (https://www.fileformat.info/format/sunraster/egff.htm) # (https://www.fileformat.info/format/sunraster/egff.htm)
if file_type in (0, 1, 3, 4, 5): if file_type in (0, 1, 3, 4, 5):
self.tile = [("raw", (0, 0) + self.size, offset, (rawmode, stride))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride))
]
elif file_type == 2: elif file_type == 2:
self.tile = [("sun_rle", (0, 0) + self.size, offset, rawmode)] self.tile = [
ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode)
]
else: else:
msg = "Unsupported Sun Raster file type" msg = "Unsupported Sun Raster file type"
raise SyntaxError(msg) raise SyntaxError(msg)

View File

@ -137,7 +137,7 @@ class TgaImageFile(ImageFile.ImageFile):
if imagetype & 8: if imagetype & 8:
# compressed # compressed
self.tile = [ self.tile = [
( ImageFile._Tile(
"tga_rle", "tga_rle",
(0, 0) + self.size, (0, 0) + self.size,
self.fp.tell(), self.fp.tell(),
@ -146,7 +146,7 @@ class TgaImageFile(ImageFile.ImageFile):
] ]
else: else:
self.tile = [ self.tile = [
( ImageFile._Tile(
"raw", "raw",
(0, 0) + self.size, (0, 0) + self.size,
self.fp.tell(), self.fp.tell(),

View File

@ -1126,7 +1126,7 @@ class TiffImageFile(ImageFile.ImageFile):
def __init__( def __init__(
self, self,
fp: StrOrBytesPath | IO[bytes] | None = None, fp: StrOrBytesPath | IO[bytes],
filename: str | bytes | None = None, filename: str | bytes | None = None,
) -> None: ) -> None:
self.tag_v2: ImageFileDirectory_v2 self.tag_v2: ImageFileDirectory_v2
@ -1298,7 +1298,7 @@ class TiffImageFile(ImageFile.ImageFile):
# (self._compression, (extents tuple), # (self._compression, (extents tuple),
# 0, (rawmode, self._compression, fp)) # 0, (rawmode, self._compression, fp))
extents = self.tile[0][1] extents = self.tile[0][1]
args = list(self.tile[0][3]) args = self.tile[0][3]
# To be nice on memory footprint, if there's a # To be nice on memory footprint, if there's a
# file descriptor, use that instead of reading # file descriptor, use that instead of reading
@ -1316,11 +1316,12 @@ class TiffImageFile(ImageFile.ImageFile):
fp = False fp = False
if fp: if fp:
args[2] = fp assert isinstance(args, tuple)
args_list = list(args)
args_list[2] = fp
args = tuple(args_list)
decoder = Image._getdecoder( decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)
self.mode, "libtiff", tuple(args), self.decoderconfig
)
try: try:
decoder.setimage(self.im, extents) decoder.setimage(self.im, extents)
except ValueError as e: except ValueError as e:
@ -1538,7 +1539,7 @@ class TiffImageFile(ImageFile.ImageFile):
# Offset in the tile tuple is 0, we go from 0,0 to # Offset in the tile tuple is 0, we go from 0,0 to
# w,h, and we only do this once -- eds # w,h, and we only do this once -- eds
a = (rawmode, self._compression, False, self.tag_v2.offset) a = (rawmode, self._compression, False, self.tag_v2.offset)
self.tile.append(("libtiff", (0, 0, xsize, ysize), 0, a)) self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2: elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
# striped image # striped image
@ -1571,7 +1572,7 @@ class TiffImageFile(ImageFile.ImageFile):
args = (tile_rawmode, int(stride), 1) args = (tile_rawmode, int(stride), 1)
self.tile.append( self.tile.append(
( ImageFile._Tile(
self._compression, self._compression,
(x, y, min(x + w, xsize), min(y + h, ysize)), (x, y, min(x + w, xsize), min(y + h, ysize)),
offset, offset,

View File

@ -142,7 +142,7 @@ class WebPImageFile(ImageFile.ImageFile):
if self.fp and self._exclusive_fp: if self.fp and self._exclusive_fp:
self.fp.close() self.fp.close()
self.fp = BytesIO(data) self.fp = BytesIO(data)
self.tile = [("raw", (0, 0) + self.size, 0, self.rawmode)] self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)]
return super().load() return super().load()

View File

@ -73,7 +73,11 @@ class XVThumbImageFile(ImageFile.ImageFile):
self.palette = ImagePalette.raw("RGB", PALETTE) self.palette = ImagePalette.raw("RGB", PALETTE)
self.tile = [("raw", (0, 0) + self.size, self.fp.tell(), (self.mode, 0, 1))] self.tile = [
ImageFile._Tile(
"raw", (0, 0) + self.size, self.fp.tell(), (self.mode, 0, 1)
)
]
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -67,7 +67,7 @@ class XbmImageFile(ImageFile.ImageFile):
self._mode = "1" self._mode = "1"
self._size = xsize, ysize self._size = xsize, ysize
self.tile = [("xbm", (0, 0) + self.size, m.end(), None)] self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end(), None)]
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:

View File

@ -101,7 +101,9 @@ class XpmImageFile(ImageFile.ImageFile):
self._mode = "P" self._mode = "P"
self.palette = ImagePalette.raw("RGB", b"".join(palette)) self.palette = ImagePalette.raw("RGB", b"".join(palette))
self.tile = [("raw", (0, 0) + self.size, self.fp.tell(), ("P", 0, 1))] self.tile = [
ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), ("P", 0, 1))
]
def load_read(self, read_bytes: int) -> bytes: def load_read(self, read_bytes: int) -> bytes:
# #