Merge branch 'main' into jpeg-app-segments

This commit is contained in:
Andrew Murray 2024-02-15 11:12:45 +11:00 committed by GitHub
commit 4d8567c1ab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
46 changed files with 280 additions and 195 deletions

View File

@ -12,6 +12,9 @@ exclude_also =
except ImportError except ImportError
if TYPE_CHECKING: if TYPE_CHECKING:
@abc.abstractmethod @abc.abstractmethod
# Empty bodies in protocols or abstract methods
^\s*def [a-zA-Z0-9_]+\(.*\)(\s*->.*)?:\s*\.\.\.(\s*#.*)?$
^\s*\.\.\.(\s*#.*)?$
[run] [run]
omit = omit =

View File

@ -244,7 +244,7 @@ def fromstring(data: bytes) -> Image.Image:
return Image.open(BytesIO(data)) return Image.open(BytesIO(data))
def tostring(im: Image.Image, string_format: str, **options: dict[str, Any]) -> bytes: def tostring(im: Image.Image, string_format: str, **options: Any) -> bytes:
out = BytesIO() out = BytesIO()
im.save(out, string_format, **options) im.save(out, string_format, **options)
return out.getvalue() return out.getvalue()

View File

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
from array import array from array import array
from types import ModuleType
import pytest import pytest
@ -8,6 +9,7 @@ from PIL import Image, ImageFilter
from .helper import assert_image_equal from .helper import assert_image_equal
numpy: ModuleType | None
try: try:
import numpy import numpy
except ImportError: except ImportError:
@ -397,6 +399,7 @@ class TestColorLut3DFilter:
@pytest.mark.skipif(numpy is None, reason="NumPy not installed") @pytest.mark.skipif(numpy is None, reason="NumPy not installed")
def test_numpy_sources(self) -> None: def test_numpy_sources(self) -> None:
assert numpy is not None
table = numpy.ones((5, 6, 7, 3), dtype=numpy.float16) table = numpy.ones((5, 6, 7, 3), dtype=numpy.float16)
with pytest.raises(ValueError, match="should have either channels"): with pytest.raises(ValueError, match="should have either channels"):
lut = ImageFilter.Color3DLUT((5, 6, 7), table) lut = ImageFilter.Color3DLUT((5, 6, 7), table)
@ -430,6 +433,7 @@ class TestColorLut3DFilter:
@pytest.mark.skipif(numpy is None, reason="NumPy not installed") @pytest.mark.skipif(numpy is None, reason="NumPy not installed")
def test_numpy_formats(self) -> None: def test_numpy_formats(self) -> None:
assert numpy is not None
g = Image.linear_gradient("L") g = Image.linear_gradient("L")
im = Image.merge( im = Image.merge(
"RGB", "RGB",

View File

@ -187,6 +187,6 @@ class TestEnvVars:
{"PILLOW_BLOCKS_MAX": "wat"}, {"PILLOW_BLOCKS_MAX": "wat"},
), ),
) )
def test_warnings(self, var) -> None: def test_warnings(self, var: dict[str, str]) -> None:
with pytest.warns(UserWarning): with pytest.warns(UserWarning):
Image._apply_env_variables(var) Image._apply_env_variables(var)

View File

@ -48,7 +48,7 @@ TEST_FILE_UNCOMPRESSED_RGB_WITH_ALPHA = "Tests/images/uncompressed_rgb.dds"
TEST_FILE_DX10_BC1_TYPELESS, TEST_FILE_DX10_BC1_TYPELESS,
), ),
) )
def test_sanity_dxt1_bc1(image_path) -> None: def test_sanity_dxt1_bc1(image_path: str) -> None:
"""Check DXT1 and BC1 images can be opened""" """Check DXT1 and BC1 images can be opened"""
with Image.open(TEST_FILE_DXT1.replace(".dds", ".png")) as target: with Image.open(TEST_FILE_DXT1.replace(".dds", ".png")) as target:
target = target.convert("RGBA") target = target.convert("RGBA")
@ -96,7 +96,7 @@ def test_sanity_dxt5() -> None:
TEST_FILE_BC4U, TEST_FILE_BC4U,
), ),
) )
def test_sanity_ati1_bc4u(image_path) -> None: def test_sanity_ati1_bc4u(image_path: str) -> None:
"""Check ATI1 and BC4U images can be opened""" """Check ATI1 and BC4U images can be opened"""
with Image.open(image_path) as im: with Image.open(image_path) as im:
@ -117,7 +117,7 @@ def test_sanity_ati1_bc4u(image_path) -> None:
TEST_FILE_DX10_BC4_TYPELESS, TEST_FILE_DX10_BC4_TYPELESS,
), ),
) )
def test_dx10_bc4(image_path) -> None: def test_dx10_bc4(image_path: str) -> None:
"""Check DX10 BC4 images can be opened""" """Check DX10 BC4 images can be opened"""
with Image.open(image_path) as im: with Image.open(image_path) as im:
@ -138,7 +138,7 @@ def test_dx10_bc4(image_path) -> None:
TEST_FILE_BC5U, TEST_FILE_BC5U,
), ),
) )
def test_sanity_ati2_bc5u(image_path) -> None: def test_sanity_ati2_bc5u(image_path: str) -> None:
"""Check ATI2 and BC5U images can be opened""" """Check ATI2 and BC5U images can be opened"""
with Image.open(image_path) as im: with Image.open(image_path) as im:
@ -162,7 +162,7 @@ def test_sanity_ati2_bc5u(image_path) -> None:
(TEST_FILE_BC5S, TEST_FILE_BC5S), (TEST_FILE_BC5S, TEST_FILE_BC5S),
), ),
) )
def test_dx10_bc5(image_path, expected_path) -> None: def test_dx10_bc5(image_path: str, expected_path: str) -> None:
"""Check DX10 BC5 images can be opened""" """Check DX10 BC5 images can be opened"""
with Image.open(image_path) as im: with Image.open(image_path) as im:
@ -176,7 +176,7 @@ def test_dx10_bc5(image_path, expected_path) -> None:
@pytest.mark.parametrize("image_path", (TEST_FILE_BC6H, TEST_FILE_BC6HS)) @pytest.mark.parametrize("image_path", (TEST_FILE_BC6H, TEST_FILE_BC6HS))
def test_dx10_bc6h(image_path) -> None: def test_dx10_bc6h(image_path: str) -> None:
"""Check DX10 BC6H/BC6HS images can be opened""" """Check DX10 BC6H/BC6HS images can be opened"""
with Image.open(image_path) as im: with Image.open(image_path) as im:
@ -257,7 +257,7 @@ def test_dx10_r8g8b8a8_unorm_srgb() -> None:
("RGBA", (800, 600), TEST_FILE_UNCOMPRESSED_RGB_WITH_ALPHA), ("RGBA", (800, 600), TEST_FILE_UNCOMPRESSED_RGB_WITH_ALPHA),
], ],
) )
def test_uncompressed(mode, size, test_file) -> None: def test_uncompressed(mode: str, size: tuple[int, int], test_file: str) -> None:
"""Check uncompressed images can be opened""" """Check uncompressed images can be opened"""
with Image.open(test_file) as im: with Image.open(test_file) as im:
@ -359,7 +359,7 @@ def test_unsupported_bitcount() -> None:
"Tests/images/unimplemented_pfflags.dds", "Tests/images/unimplemented_pfflags.dds",
), ),
) )
def test_not_implemented(test_file) -> None: def test_not_implemented(test_file: str) -> None:
with pytest.raises(NotImplementedError): with pytest.raises(NotImplementedError):
with Image.open(test_file): with Image.open(test_file):
pass pass
@ -381,7 +381,7 @@ def test_save_unsupported_mode(tmp_path: Path) -> None:
("RGBA", "Tests/images/pil123rgba.png"), ("RGBA", "Tests/images/pil123rgba.png"),
], ],
) )
def test_save(mode, test_file, tmp_path: Path) -> None: def test_save(mode: str, test_file: str, tmp_path: Path) -> None:
out = str(tmp_path / "temp.dds") out = str(tmp_path / "temp.dds")
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert im.mode == mode assert im.mode == mode

View File

@ -147,7 +147,7 @@ def test_seek() -> None:
], ],
) )
@pytest.mark.timeout(timeout=3) @pytest.mark.timeout(timeout=3)
def test_timeouts(test_file) -> None: def test_timeouts(test_file: str) -> None:
with open(test_file, "rb") as f: with open(test_file, "rb") as f:
with Image.open(f) as im: with Image.open(f) as im:
with pytest.raises(OSError): with pytest.raises(OSError):
@ -160,7 +160,7 @@ def test_timeouts(test_file) -> None:
"Tests/images/crash-5762152299364352.fli", "Tests/images/crash-5762152299364352.fli",
], ],
) )
def test_crash(test_file) -> None: def test_crash(test_file: str) -> None:
with open(test_file, "rb") as f: with open(test_file, "rb") as f:
with Image.open(f) as im: with Image.open(f) as im:
with pytest.raises(OSError): with pytest.raises(OSError):

View File

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import IO
import pytest import pytest
@ -55,15 +56,15 @@ def test_handler(tmp_path: Path) -> None:
loaded = False loaded = False
saved = False saved = False
def open(self, im) -> None: def open(self, im: Image.Image) -> None:
self.opened = True self.opened = True
def load(self, im): def load(self, im: Image.Image) -> Image.Image:
self.loaded = True self.loaded = True
im.fp.close() im.fp.close()
return Image.new("RGB", (1, 1)) return Image.new("RGB", (1, 1))
def save(self, im, fp, filename) -> None: def save(self, im: Image.Image, fp: IO[bytes], filename: str) -> None:
self.saved = True self.saved = True
handler = TestHandler() handler = TestHandler()

View File

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import IO
import pytest import pytest
@ -56,15 +57,15 @@ def test_handler(tmp_path: Path) -> None:
loaded = False loaded = False
saved = False saved = False
def open(self, im) -> None: def open(self, im: Image.Image) -> None:
self.opened = True self.opened = True
def load(self, im): def load(self, im: Image.Image) -> Image.Image:
self.loaded = True self.loaded = True
im.fp.close() im.fp.close()
return Image.new("RGB", (1, 1)) return Image.new("RGB", (1, 1))
def save(self, im, fp, filename) -> None: def save(self, im: Image.Image, fp: IO[bytes], filename: str) -> None:
self.saved = True self.saved = True
handler = TestHandler() handler = TestHandler()

View File

@ -5,6 +5,7 @@ import re
import warnings import warnings
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from types import ModuleType
from typing import Any from typing import Any
import pytest import pytest
@ -33,6 +34,7 @@ from .helper import (
skip_unless_feature, skip_unless_feature,
) )
ElementTree: ModuleType | None
try: try:
from defusedxml import ElementTree from defusedxml import ElementTree
except ImportError: except ImportError:
@ -465,25 +467,25 @@ class TestFileJpeg:
for subsampling in (-1, 3): # (default, invalid) for subsampling in (-1, 3): # (default, invalid)
im = self.roundtrip(hopper(), subsampling=subsampling) im = self.roundtrip(hopper(), subsampling=subsampling)
assert getsampling(im) == (2, 2, 1, 1, 1, 1) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
for subsampling in (0, "4:4:4"): for subsampling1 in (0, "4:4:4"):
im = self.roundtrip(hopper(), subsampling=subsampling) im = self.roundtrip(hopper(), subsampling=subsampling1)
assert getsampling(im) == (1, 1, 1, 1, 1, 1) assert getsampling(im) == (1, 1, 1, 1, 1, 1)
for subsampling in (1, "4:2:2"): for subsampling1 in (1, "4:2:2"):
im = self.roundtrip(hopper(), subsampling=subsampling) im = self.roundtrip(hopper(), subsampling=subsampling1)
assert getsampling(im) == (2, 1, 1, 1, 1, 1) assert getsampling(im) == (2, 1, 1, 1, 1, 1)
for subsampling in (2, "4:2:0", "4:1:1"): for subsampling1 in (2, "4:2:0", "4:1:1"):
im = self.roundtrip(hopper(), subsampling=subsampling) im = self.roundtrip(hopper(), subsampling=subsampling1)
assert getsampling(im) == (2, 2, 1, 1, 1, 1) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
# RGB colorspace # RGB colorspace
for subsampling in (-1, 0, "4:4:4"): for subsampling1 in (-1, 0, "4:4:4"):
# "4:4:4" doesn't really make sense for RGB, but the conversion # "4:4:4" doesn't really make sense for RGB, but the conversion
# to an integer happens at a higher level # to an integer happens at a higher level
im = self.roundtrip(hopper(), keep_rgb=True, subsampling=subsampling) im = self.roundtrip(hopper(), keep_rgb=True, subsampling=subsampling1)
assert getsampling(im) == (1, 1, 1, 1, 1, 1) assert getsampling(im) == (1, 1, 1, 1, 1, 1)
for subsampling in (1, "4:2:2", 2, "4:2:0", 3): for subsampling1 in (1, "4:2:2", 2, "4:2:0", 3):
with pytest.raises(OSError): with pytest.raises(OSError):
self.roundtrip(hopper(), keep_rgb=True, subsampling=subsampling) self.roundtrip(hopper(), keep_rgb=True, subsampling=subsampling1)
with pytest.raises(TypeError): with pytest.raises(TypeError):
self.roundtrip(hopper(), subsampling="1:1:1") self.roundtrip(hopper(), subsampling="1:1:1")

View File

@ -11,7 +11,7 @@ from PIL import Image
from .helper import assert_image_equal, hopper, magick_command from .helper import assert_image_equal, hopper, magick_command
def helper_save_as_palm(tmp_path: Path, mode) -> None: def helper_save_as_palm(tmp_path: Path, mode: str) -> None:
# Arrange # Arrange
im = hopper(mode) im = hopper(mode)
outfile = str(tmp_path / ("temp_" + mode + ".palm")) outfile = str(tmp_path / ("temp_" + mode + ".palm"))
@ -24,7 +24,7 @@ def helper_save_as_palm(tmp_path: Path, mode) -> None:
assert os.path.getsize(outfile) > 0 assert os.path.getsize(outfile) > 0
def open_with_magick(magick, tmp_path: Path, f): def open_with_magick(magick: list[str], tmp_path: Path, f: str) -> Image.Image:
outfile = str(tmp_path / "temp.png") outfile = str(tmp_path / "temp.png")
rc = subprocess.call( rc = subprocess.call(
magick + [f, outfile], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT magick + [f, outfile], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
@ -33,7 +33,7 @@ def open_with_magick(magick, tmp_path: Path, f):
return Image.open(outfile) return Image.open(outfile)
def roundtrip(tmp_path: Path, mode) -> None: def roundtrip(tmp_path: Path, mode: str) -> None:
magick = magick_command() magick = magick_command()
if not magick: if not magick:
return return
@ -66,6 +66,6 @@ def test_p_mode(tmp_path: Path) -> None:
@pytest.mark.parametrize("mode", ("L", "RGB")) @pytest.mark.parametrize("mode", ("L", "RGB"))
def test_oserror(tmp_path: Path, mode) -> None: def test_oserror(tmp_path: Path, mode: str) -> None:
with pytest.raises(OSError): with pytest.raises(OSError):
helper_save_as_palm(tmp_path, mode) helper_save_as_palm(tmp_path, mode)

View File

@ -19,7 +19,7 @@ TEST_TAR_FILE = "Tests/images/hopper.tar"
("jpg", "hopper.jpg", "JPEG"), ("jpg", "hopper.jpg", "JPEG"),
), ),
) )
def test_sanity(codec, test_path, format) -> None: def test_sanity(codec: str, test_path: str, format: str) -> None:
if features.check(codec): if features.check(codec):
with TarIO.TarIO(TEST_TAR_FILE, test_path) as tar: with TarIO.TarIO(TEST_TAR_FILE, test_path) as tar:
with Image.open(tar) as im: with Image.open(tar) as im:

View File

@ -2,6 +2,7 @@ from __future__ import annotations
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
from types import ModuleType
import pytest import pytest
@ -14,6 +15,7 @@ pytestmark = [
skip_unless_feature("webp_mux"), skip_unless_feature("webp_mux"),
] ]
ElementTree: ModuleType | None
try: try:
from defusedxml import ElementTree from defusedxml import ElementTree
except ImportError: except ImportError:

View File

@ -8,6 +8,7 @@ import sys
import tempfile import tempfile
import warnings import warnings
from pathlib import Path from pathlib import Path
from typing import IO
import pytest import pytest
@ -61,11 +62,11 @@ class TestImage:
"HSV", "HSV",
), ),
) )
def test_image_modes_success(self, mode) -> None: def test_image_modes_success(self, mode: str) -> None:
Image.new(mode, (1, 1)) Image.new(mode, (1, 1))
@pytest.mark.parametrize("mode", ("", "bad", "very very long")) @pytest.mark.parametrize("mode", ("", "bad", "very very long"))
def test_image_modes_fail(self, mode) -> None: def test_image_modes_fail(self, mode: str) -> None:
with pytest.raises(ValueError) as e: with pytest.raises(ValueError) as e:
Image.new(mode, (1, 1)) Image.new(mode, (1, 1))
assert str(e.value) == "unrecognized image mode" assert str(e.value) == "unrecognized image mode"
@ -100,7 +101,7 @@ class TestImage:
def test_repr_pretty(self) -> None: def test_repr_pretty(self) -> None:
class Pretty: class Pretty:
def text(self, text) -> None: def text(self, text: str) -> None:
self.pretty_output = text self.pretty_output = text
im = Image.new("L", (100, 100)) im = Image.new("L", (100, 100))
@ -162,8 +163,6 @@ class TestImage:
pass pass
def test_pathlib(self, tmp_path: Path) -> None: def test_pathlib(self, tmp_path: Path) -> None:
from PIL.Image import Path
with Image.open(Path("Tests/images/multipage-mmap.tiff")) as im: with Image.open(Path("Tests/images/multipage-mmap.tiff")) as im:
assert im.mode == "P" assert im.mode == "P"
assert im.size == (10, 10) assert im.size == (10, 10)
@ -184,7 +183,9 @@ class TestImage:
temp_file = str(tmp_path / "temp.jpg") temp_file = str(tmp_path / "temp.jpg")
class FP: class FP:
def write(self, b) -> None: name: str
def write(self, b: bytes) -> None:
pass pass
fp = FP() fp = FP()
@ -538,7 +539,7 @@ class TestImage:
"PILLOW_VALGRIND_TEST" in os.environ, reason="Valgrind is slower" "PILLOW_VALGRIND_TEST" in os.environ, reason="Valgrind is slower"
) )
@pytest.mark.parametrize("size", ((0, 100000000), (100000000, 0))) @pytest.mark.parametrize("size", ((0, 100000000), (100000000, 0)))
def test_empty_image(self, size) -> None: def test_empty_image(self, size: tuple[int, int]) -> None:
Image.new("RGB", size) Image.new("RGB", size)
def test_storage_neg(self) -> None: def test_storage_neg(self) -> None:
@ -565,7 +566,7 @@ class TestImage:
Image.linear_gradient(wrong_mode) Image.linear_gradient(wrong_mode)
@pytest.mark.parametrize("mode", ("L", "P", "I", "F")) @pytest.mark.parametrize("mode", ("L", "P", "I", "F"))
def test_linear_gradient(self, mode) -> None: def test_linear_gradient(self, mode: str) -> None:
# Arrange # Arrange
target_file = "Tests/images/linear_gradient.png" target_file = "Tests/images/linear_gradient.png"
@ -590,7 +591,7 @@ class TestImage:
Image.radial_gradient(wrong_mode) Image.radial_gradient(wrong_mode)
@pytest.mark.parametrize("mode", ("L", "P", "I", "F")) @pytest.mark.parametrize("mode", ("L", "P", "I", "F"))
def test_radial_gradient(self, mode) -> None: def test_radial_gradient(self, mode: str) -> None:
# Arrange # Arrange
target_file = "Tests/images/radial_gradient.png" target_file = "Tests/images/radial_gradient.png"
@ -665,7 +666,11 @@ class TestImage:
blank_p.palette = None blank_p.palette = None
blank_pa.palette = None blank_pa.palette = None
def _make_new(base_image, image, palette_result=None) -> None: def _make_new(
base_image: Image.Image,
image: Image.Image,
palette_result: ImagePalette.ImagePalette | None = None,
) -> None:
new_image = base_image._new(image.im) new_image = base_image._new(image.im)
assert new_image.mode == image.mode assert new_image.mode == image.mode
assert new_image.size == image.size assert new_image.size == image.size
@ -713,7 +718,7 @@ class TestImage:
def test_load_on_nonexclusive_multiframe(self) -> None: def test_load_on_nonexclusive_multiframe(self) -> None:
with open("Tests/images/frozenpond.mpo", "rb") as fp: with open("Tests/images/frozenpond.mpo", "rb") as fp:
def act(fp) -> None: def act(fp: IO[bytes]) -> None:
im = Image.open(fp) im = Image.open(fp)
im.load() im.load()
@ -906,12 +911,12 @@ class TestImage:
assert exif.get_ifd(0xA005) assert exif.get_ifd(0xA005)
@pytest.mark.parametrize("size", ((1, 0), (0, 1), (0, 0))) @pytest.mark.parametrize("size", ((1, 0), (0, 1), (0, 0)))
def test_zero_tobytes(self, size) -> None: def test_zero_tobytes(self, size: tuple[int, int]) -> None:
im = Image.new("RGB", size) im = Image.new("RGB", size)
assert im.tobytes() == b"" assert im.tobytes() == b""
@pytest.mark.parametrize("size", ((1, 0), (0, 1), (0, 0))) @pytest.mark.parametrize("size", ((1, 0), (0, 1), (0, 0)))
def test_zero_frombytes(self, size) -> None: def test_zero_frombytes(self, size: tuple[int, int]) -> None:
Image.frombytes("RGB", size, b"") Image.frombytes("RGB", size, b"")
im = Image.new("RGB", size) im = Image.new("RGB", size)
@ -996,7 +1001,7 @@ class TestImage:
"01r_00.pcx", "01r_00.pcx",
], ],
) )
def test_overrun(self, path) -> None: def test_overrun(self, path: str) -> None:
"""For overrun completeness, test as: """For overrun completeness, test as:
valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c
""" """
@ -1023,7 +1028,7 @@ class TestImage:
pass pass
assert not hasattr(im, "fp") assert not hasattr(im, "fp")
def test_close_graceful(self, caplog) -> None: def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:
with Image.open("Tests/images/hopper.jpg") as im: with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy() copy = im.copy()
with caplog.at_level(logging.DEBUG): with caplog.at_level(logging.DEBUG):
@ -1034,10 +1039,10 @@ class TestImage:
class MockEncoder: class MockEncoder:
pass args: tuple[str, ...]
def mock_encode(*args): def mock_encode(*args: str) -> MockEncoder:
encoder = MockEncoder() encoder = MockEncoder()
encoder.args = args encoder.args = args
return encoder return encoder

View File

@ -4,6 +4,7 @@ import os
import subprocess import subprocess
import sys import sys
import sysconfig import sysconfig
from types import ModuleType
import pytest import pytest
@ -23,6 +24,7 @@ else:
except ImportError: except ImportError:
cffi = None cffi = None
numpy: ModuleType | None
try: try:
import numpy import numpy
except ImportError: except ImportError:
@ -71,9 +73,10 @@ class TestImagePutPixel(AccessTest):
pix1 = im1.load() pix1 = im1.load()
pix2 = im2.load() pix2 = im2.load()
for x, y in ((0, "0"), ("0", 0)): with pytest.raises(TypeError):
with pytest.raises(TypeError): pix1[0, "0"]
pix1[x, y] with pytest.raises(TypeError):
pix1["0", 0]
for y in range(im1.size[1]): for y in range(im1.size[1]):
for x in range(im1.size[0]): for x in range(im1.size[0]):
@ -123,12 +126,13 @@ class TestImagePutPixel(AccessTest):
im = hopper() im = hopper()
pix = im.load() pix = im.load()
assert numpy is not None
assert pix[numpy.int32(1), numpy.int32(2)] == (18, 20, 59) assert pix[numpy.int32(1), numpy.int32(2)] == (18, 20, 59)
class TestImageGetPixel(AccessTest): class TestImageGetPixel(AccessTest):
@staticmethod @staticmethod
def color(mode): def color(mode: str) -> int | tuple[int, ...]:
bands = Image.getmodebands(mode) bands = Image.getmodebands(mode)
if bands == 1: if bands == 1:
return 1 return 1
@ -138,12 +142,13 @@ class TestImageGetPixel(AccessTest):
return (16, 32, 49) return (16, 32, 49)
return tuple(range(1, bands + 1)) return tuple(range(1, bands + 1))
def check(self, mode, expected_color=None) -> None: def check(self, mode: str, expected_color_int: int | None = None) -> None:
if self._need_cffi_access and mode.startswith("BGR;"): if self._need_cffi_access and mode.startswith("BGR;"):
pytest.skip("Support not added to deprecated module for BGR;* modes") pytest.skip("Support not added to deprecated module for BGR;* modes")
if not expected_color: expected_color = (
expected_color = self.color(mode) self.color(mode) if expected_color_int is None else expected_color_int
)
# check putpixel # check putpixel
im = Image.new(mode, (1, 1), None) im = Image.new(mode, (1, 1), None)
@ -222,7 +227,7 @@ class TestImageGetPixel(AccessTest):
"YCbCr", "YCbCr",
), ),
) )
def test_basic(self, mode) -> None: def test_basic(self, mode: str) -> None:
self.check(mode) self.check(mode)
def test_list(self) -> None: def test_list(self) -> None:
@ -231,14 +236,14 @@ class TestImageGetPixel(AccessTest):
@pytest.mark.parametrize("mode", ("I;16", "I;16B")) @pytest.mark.parametrize("mode", ("I;16", "I;16B"))
@pytest.mark.parametrize("expected_color", (2**15 - 1, 2**15, 2**15 + 1, 2**16 - 1)) @pytest.mark.parametrize("expected_color", (2**15 - 1, 2**15, 2**15 + 1, 2**16 - 1))
def test_signedness(self, mode, expected_color) -> None: def test_signedness(self, mode: str, expected_color: int) -> None:
# see https://github.com/python-pillow/Pillow/issues/452 # see https://github.com/python-pillow/Pillow/issues/452
# pixelaccess is using signed int* instead of uint* # pixelaccess is using signed int* instead of uint*
self.check(mode, expected_color) self.check(mode, expected_color)
@pytest.mark.parametrize("mode", ("P", "PA")) @pytest.mark.parametrize("mode", ("P", "PA"))
@pytest.mark.parametrize("color", ((255, 0, 0), (255, 0, 0, 255))) @pytest.mark.parametrize("color", ((255, 0, 0), (255, 0, 0, 255)))
def test_p_putpixel_rgb_rgba(self, mode, color) -> None: def test_p_putpixel_rgb_rgba(self, mode: str, color: tuple[int, ...]) -> None:
im = Image.new(mode, (1, 1)) im = Image.new(mode, (1, 1))
im.putpixel((0, 0), color) im.putpixel((0, 0), color)
@ -262,7 +267,7 @@ class TestCffiGetPixel(TestImageGetPixel):
class TestCffi(AccessTest): class TestCffi(AccessTest):
_need_cffi_access = True _need_cffi_access = True
def _test_get_access(self, im) -> None: def _test_get_access(self, im: Image.Image) -> None:
"""Do we get the same thing as the old pixel access """Do we get the same thing as the old pixel access
Using private interfaces, forcing a capi access and Using private interfaces, forcing a capi access and
@ -299,7 +304,7 @@ class TestCffi(AccessTest):
# im = Image.new('I;32B', (10, 10), 2**10) # im = Image.new('I;32B', (10, 10), 2**10)
# self._test_get_access(im) # self._test_get_access(im)
def _test_set_access(self, im, color) -> None: def _test_set_access(self, im: Image.Image, color: tuple[int, ...] | float) -> None:
"""Are we writing the correct bits into the image? """Are we writing the correct bits into the image?
Using private interfaces, forcing a capi access and Using private interfaces, forcing a capi access and
@ -359,7 +364,7 @@ class TestCffi(AccessTest):
assert px[i, 0] == 0 assert px[i, 0] == 0
@pytest.mark.parametrize("mode", ("P", "PA")) @pytest.mark.parametrize("mode", ("P", "PA"))
def test_p_putpixel_rgb_rgba(self, mode) -> None: def test_p_putpixel_rgb_rgba(self, mode: str) -> None:
for color in ((255, 0, 0), (255, 0, 0, 127 if mode == "PA" else 255)): for color in ((255, 0, 0), (255, 0, 0, 127 if mode == "PA" else 255)):
im = Image.new(mode, (1, 1)) im = Image.new(mode, (1, 1))
with pytest.warns(DeprecationWarning): with pytest.warns(DeprecationWarning):
@ -377,7 +382,7 @@ class TestImagePutPixelError(AccessTest):
INVALID_TYPES = ["foo", 1.0, None] INVALID_TYPES = ["foo", 1.0, None]
@pytest.mark.parametrize("mode", IMAGE_MODES1) @pytest.mark.parametrize("mode", IMAGE_MODES1)
def test_putpixel_type_error1(self, mode) -> None: def test_putpixel_type_error1(self, mode: str) -> None:
im = hopper(mode) im = hopper(mode)
for v in self.INVALID_TYPES: for v in self.INVALID_TYPES:
with pytest.raises(TypeError, match="color must be int or tuple"): with pytest.raises(TypeError, match="color must be int or tuple"):
@ -400,14 +405,16 @@ class TestImagePutPixelError(AccessTest):
), ),
), ),
) )
def test_putpixel_invalid_number_of_bands(self, mode, band_numbers, match) -> None: def test_putpixel_invalid_number_of_bands(
self, mode: str, band_numbers: tuple[int, ...], match: str
) -> None:
im = hopper(mode) im = hopper(mode)
for band_number in band_numbers: for band_number in band_numbers:
with pytest.raises(TypeError, match=match): with pytest.raises(TypeError, match=match):
im.putpixel((0, 0), (0,) * band_number) im.putpixel((0, 0), (0,) * band_number)
@pytest.mark.parametrize("mode", IMAGE_MODES2) @pytest.mark.parametrize("mode", IMAGE_MODES2)
def test_putpixel_type_error2(self, mode) -> None: def test_putpixel_type_error2(self, mode: str) -> None:
im = hopper(mode) im = hopper(mode)
for v in self.INVALID_TYPES: for v in self.INVALID_TYPES:
with pytest.raises( with pytest.raises(
@ -416,7 +423,7 @@ class TestImagePutPixelError(AccessTest):
im.putpixel((0, 0), v) im.putpixel((0, 0), v)
@pytest.mark.parametrize("mode", IMAGE_MODES1 + IMAGE_MODES2) @pytest.mark.parametrize("mode", IMAGE_MODES1 + IMAGE_MODES2)
def test_putpixel_overflow_error(self, mode) -> None: def test_putpixel_overflow_error(self, mode: str) -> None:
im = hopper(mode) im = hopper(mode)
with pytest.raises(OverflowError): with pytest.raises(OverflowError):
im.putpixel((0, 0), 2**80) im.putpixel((0, 0), 2**80)
@ -428,7 +435,7 @@ class TestEmbeddable:
def test_embeddable(self) -> None: def test_embeddable(self) -> None:
import ctypes import ctypes
from setuptools.command.build_ext import new_compiler from setuptools.command import build_ext
with open("embed_pil.c", "w", encoding="utf-8") as fh: with open("embed_pil.c", "w", encoding="utf-8") as fh:
fh.write( fh.write(
@ -457,7 +464,7 @@ int main(int argc, char* argv[])
% sys.prefix.replace("\\", "\\\\") % sys.prefix.replace("\\", "\\\\")
) )
compiler = new_compiler() compiler = getattr(build_ext, "new_compiler")()
compiler.add_include_dir(sysconfig.get_config_var("INCLUDEPY")) compiler.add_include_dir(sysconfig.get_config_var("INCLUDEPY"))
libdir = sysconfig.get_config_var("LIBDIR") or sysconfig.get_config_var( libdir = sysconfig.get_config_var("LIBDIR") or sysconfig.get_config_var(
@ -471,7 +478,7 @@ int main(int argc, char* argv[])
env["PATH"] = sys.prefix + ";" + env["PATH"] env["PATH"] = sys.prefix + ";" + env["PATH"]
# do not display the Windows Error Reporting dialog # do not display the Windows Error Reporting dialog
ctypes.windll.kernel32.SetErrorMode(0x0002) getattr(ctypes, "windll").kernel32.SetErrorMode(0x0002)
process = subprocess.Popen(["embed_pil.exe"], env=env) process = subprocess.Popen(["embed_pil.exe"], env=env)
process.communicate() process.communicate()

View File

@ -1,5 +1,7 @@
from __future__ import annotations from __future__ import annotations
from typing import Any
import pytest import pytest
from packaging.version import parse as parse_version from packaging.version import parse as parse_version
@ -13,7 +15,7 @@ im = hopper().resize((128, 100))
def test_toarray() -> None: def test_toarray() -> None:
def test(mode): def test(mode: str) -> tuple[tuple[int, ...], str, int]:
ai = numpy.array(im.convert(mode)) ai = numpy.array(im.convert(mode))
return ai.shape, ai.dtype.str, ai.nbytes return ai.shape, ai.dtype.str, ai.nbytes
@ -50,14 +52,14 @@ def test_fromarray() -> None:
class Wrapper: class Wrapper:
"""Class with API matching Image.fromarray""" """Class with API matching Image.fromarray"""
def __init__(self, img, arr_params) -> None: def __init__(self, img: Image.Image, arr_params: dict[str, Any]) -> None:
self.img = img self.img = img
self.__array_interface__ = arr_params self.__array_interface__ = arr_params
def tobytes(self): def tobytes(self) -> bytes:
return self.img.tobytes() return self.img.tobytes()
def test(mode): def test(mode: str) -> tuple[str, tuple[int, int], bool]:
i = im.convert(mode) i = im.convert(mode)
a = numpy.array(i) a = numpy.array(i)
# Make wrapper instance for image, new array interface # Make wrapper instance for image, new array interface

View File

@ -7,7 +7,12 @@ from .helper import fromstring, skip_unless_feature, tostring
pytestmark = skip_unless_feature("jpg") pytestmark = skip_unless_feature("jpg")
def draft_roundtrip(in_mode, in_size, req_mode, req_size): def draft_roundtrip(
in_mode: str,
in_size: tuple[int, int],
req_mode: str | None,
req_size: tuple[int, int] | None,
) -> Image.Image:
im = Image.new(in_mode, in_size) im = Image.new(in_mode, in_size)
data = tostring(im, "JPEG") data = tostring(im, "JPEG")
im = fromstring(data) im = fromstring(data)

View File

@ -4,7 +4,7 @@ from .helper import hopper
def test_entropy() -> None: def test_entropy() -> None:
def entropy(mode): def entropy(mode: str) -> float:
return hopper(mode).entropy() return hopper(mode).entropy()
assert round(abs(entropy("1") - 0.9138803254693582), 7) == 0 assert round(abs(entropy("1") - 0.9138803254693582), 7) == 0

View File

@ -36,7 +36,7 @@ from .helper import assert_image_equal, hopper
), ),
) )
@pytest.mark.parametrize("mode", ("L", "I", "RGB", "CMYK")) @pytest.mark.parametrize("mode", ("L", "I", "RGB", "CMYK"))
def test_sanity(filter_to_apply, mode) -> None: def test_sanity(filter_to_apply: ImageFilter.Filter, mode: str) -> None:
im = hopper(mode) im = hopper(mode)
if mode != "I" or isinstance(filter_to_apply, ImageFilter.BuiltinFilter): if mode != "I" or isinstance(filter_to_apply, ImageFilter.BuiltinFilter):
out = im.filter(filter_to_apply) out = im.filter(filter_to_apply)
@ -45,7 +45,7 @@ def test_sanity(filter_to_apply, mode) -> None:
@pytest.mark.parametrize("mode", ("L", "I", "RGB", "CMYK")) @pytest.mark.parametrize("mode", ("L", "I", "RGB", "CMYK"))
def test_sanity_error(mode) -> None: def test_sanity_error(mode: str) -> None:
with pytest.raises(TypeError): with pytest.raises(TypeError):
im = hopper(mode) im = hopper(mode)
im.filter("hello") im.filter("hello")
@ -53,7 +53,7 @@ def test_sanity_error(mode) -> None:
# crashes on small images # crashes on small images
@pytest.mark.parametrize("size", ((1, 1), (2, 2), (3, 3))) @pytest.mark.parametrize("size", ((1, 1), (2, 2), (3, 3)))
def test_crash(size) -> None: def test_crash(size: tuple[int, int]) -> None:
im = Image.new("RGB", size) im = Image.new("RGB", size)
im.filter(ImageFilter.SMOOTH) im.filter(ImageFilter.SMOOTH)
@ -67,7 +67,10 @@ def test_crash(size) -> None:
("RGB", ((4, 0, 0), (0, 0, 0))), ("RGB", ((4, 0, 0), (0, 0, 0))),
), ),
) )
def test_modefilter(mode, expected) -> None: def test_modefilter(
mode: str,
expected: tuple[int, int] | tuple[tuple[int, int, int], tuple[int, int, int]],
) -> None:
im = Image.new(mode, (3, 3), None) im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9))) im.putdata(list(range(9)))
# image is: # image is:
@ -90,7 +93,13 @@ def test_modefilter(mode, expected) -> None:
("F", (0.0, 4.0, 8.0)), ("F", (0.0, 4.0, 8.0)),
), ),
) )
def test_rankfilter(mode, expected) -> None: def test_rankfilter(
mode: str,
expected: (
tuple[float, float, float]
| tuple[tuple[int, int, int], tuple[int, int, int], tuple[int, int, int]]
),
) -> None:
im = Image.new(mode, (3, 3), None) im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9))) im.putdata(list(range(9)))
# image is: # image is:
@ -106,7 +115,7 @@ def test_rankfilter(mode, expected) -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"filter", (ImageFilter.MinFilter, ImageFilter.MedianFilter, ImageFilter.MaxFilter) "filter", (ImageFilter.MinFilter, ImageFilter.MedianFilter, ImageFilter.MaxFilter)
) )
def test_rankfilter_error(filter) -> None: def test_rankfilter_error(filter: ImageFilter.RankFilter) -> None:
with pytest.raises(ValueError): with pytest.raises(ValueError):
im = Image.new("P", (3, 3), None) im = Image.new("P", (3, 3), None)
im.putdata(list(range(9))) im.putdata(list(range(9)))
@ -137,7 +146,7 @@ def test_kernel_not_enough_coefficients() -> None:
@pytest.mark.parametrize("mode", ("L", "LA", "I", "RGB", "CMYK")) @pytest.mark.parametrize("mode", ("L", "LA", "I", "RGB", "CMYK"))
def test_consistency_3x3(mode) -> None: def test_consistency_3x3(mode: str) -> None:
with Image.open("Tests/images/hopper.bmp") as source: with Image.open("Tests/images/hopper.bmp") as source:
reference_name = "hopper_emboss" reference_name = "hopper_emboss"
reference_name += "_I.png" if mode == "I" else ".bmp" reference_name += "_I.png" if mode == "I" else ".bmp"
@ -163,7 +172,7 @@ def test_consistency_3x3(mode) -> None:
@pytest.mark.parametrize("mode", ("L", "LA", "I", "RGB", "CMYK")) @pytest.mark.parametrize("mode", ("L", "LA", "I", "RGB", "CMYK"))
def test_consistency_5x5(mode) -> None: def test_consistency_5x5(mode: str) -> None:
with Image.open("Tests/images/hopper.bmp") as source: with Image.open("Tests/images/hopper.bmp") as source:
reference_name = "hopper_emboss_more" reference_name = "hopper_emboss_more"
reference_name += "_I.png" if mode == "I" else ".bmp" reference_name += "_I.png" if mode == "I" else ".bmp"
@ -199,7 +208,7 @@ def test_consistency_5x5(mode) -> None:
(2, -2), (2, -2),
), ),
) )
def test_invalid_box_blur_filter(radius) -> None: def test_invalid_box_blur_filter(radius: int | tuple[int, int]) -> None:
with pytest.raises(ValueError): with pytest.raises(ValueError):
ImageFilter.BoxBlur(radius) ImageFilter.BoxBlur(radius)

View File

@ -6,7 +6,7 @@ from .helper import hopper
def test_extrema() -> None: def test_extrema() -> None:
def extrema(mode): def extrema(mode: str) -> tuple[int, int] | tuple[tuple[int, int], ...]:
return hopper(mode).getextrema() return hopper(mode).getextrema()
assert extrema("1") == (0, 255) assert extrema("1") == (0, 255)

View File

@ -6,7 +6,7 @@ from .helper import hopper
def test_palette() -> None: def test_palette() -> None:
def palette(mode): def palette(mode: str) -> list[int] | None:
p = hopper(mode).getpalette() p = hopper(mode).getpalette()
if p: if p:
return p[:10] return p[:10]

View File

@ -46,7 +46,7 @@ class TestImagingPaste:
self.assert_9points_image(im, expected) self.assert_9points_image(im, expected)
@CachedProperty @CachedProperty
def mask_1(self): def mask_1(self) -> Image.Image:
mask = Image.new("1", (self.size, self.size)) mask = Image.new("1", (self.size, self.size))
px = mask.load() px = mask.load()
for y in range(mask.height): for y in range(mask.height):
@ -55,11 +55,11 @@ class TestImagingPaste:
return mask return mask
@CachedProperty @CachedProperty
def mask_L(self): def mask_L(self) -> Image.Image:
return self.gradient_L.transpose(Image.Transpose.ROTATE_270) return self.gradient_L.transpose(Image.Transpose.ROTATE_270)
@CachedProperty @CachedProperty
def gradient_L(self): def gradient_L(self) -> Image.Image:
gradient = Image.new("L", (self.size, self.size)) gradient = Image.new("L", (self.size, self.size))
px = gradient.load() px = gradient.load()
for y in range(gradient.height): for y in range(gradient.height):
@ -68,7 +68,7 @@ class TestImagingPaste:
return gradient return gradient
@CachedProperty @CachedProperty
def gradient_RGB(self): def gradient_RGB(self) -> Image.Image:
return Image.merge( return Image.merge(
"RGB", "RGB",
[ [
@ -79,7 +79,7 @@ class TestImagingPaste:
) )
@CachedProperty @CachedProperty
def gradient_LA(self): def gradient_LA(self) -> Image.Image:
return Image.merge( return Image.merge(
"LA", "LA",
[ [
@ -89,7 +89,7 @@ class TestImagingPaste:
) )
@CachedProperty @CachedProperty
def gradient_RGBA(self): def gradient_RGBA(self) -> Image.Image:
return Image.merge( return Image.merge(
"RGBA", "RGBA",
[ [
@ -101,7 +101,7 @@ class TestImagingPaste:
) )
@CachedProperty @CachedProperty
def gradient_RGBa(self): def gradient_RGBa(self) -> Image.Image:
return Image.merge( return Image.merge(
"RGBa", "RGBa",
[ [

View File

@ -31,7 +31,7 @@ def test_sanity() -> None:
def test_long_integers() -> None: def test_long_integers() -> None:
# see bug-200802-systemerror # see bug-200802-systemerror
def put(value): def put(value: int) -> tuple[int, int, int, int]:
im = Image.new("RGBA", (1, 1)) im = Image.new("RGBA", (1, 1))
im.putdata([value]) im.putdata([value])
return im.getpixel((0, 0)) return im.getpixel((0, 0))
@ -58,7 +58,7 @@ def test_mode_with_L_with_float() -> None:
@pytest.mark.parametrize("mode", ("I", "I;16", "I;16L", "I;16B")) @pytest.mark.parametrize("mode", ("I", "I;16", "I;16L", "I;16B"))
def test_mode_i(mode) -> None: def test_mode_i(mode: str) -> None:
src = hopper("L") src = hopper("L")
data = list(src.getdata()) data = list(src.getdata())
im = Image.new(mode, src.size, 0) im = Image.new(mode, src.size, 0)
@ -79,7 +79,7 @@ def test_mode_F() -> None:
@pytest.mark.parametrize("mode", ("BGR;15", "BGR;16", "BGR;24")) @pytest.mark.parametrize("mode", ("BGR;15", "BGR;16", "BGR;24"))
def test_mode_BGR(mode) -> None: def test_mode_BGR(mode: str) -> None:
data = [(16, 32, 49), (32, 32, 98)] data = [(16, 32, 49), (32, 32, 98)]
im = Image.new(mode, (1, 2)) im = Image.new(mode, (1, 2))
im.putdata(data) im.putdata(data)

View File

@ -8,7 +8,7 @@ from .helper import assert_image_equal, assert_image_equal_tofile, hopper
def test_putpalette() -> None: def test_putpalette() -> None:
def palette(mode): def palette(mode: str) -> str | tuple[str, list[int]]:
im = hopper(mode).copy() im = hopper(mode).copy()
im.putpalette(list(range(256)) * 3) im.putpalette(list(range(256)) * 3)
p = im.getpalette() p = im.getpalette()
@ -81,7 +81,7 @@ def test_putpalette_with_alpha_values() -> None:
("RGBAX", (1, 2, 3, 4, 0)), ("RGBAX", (1, 2, 3, 4, 0)),
), ),
) )
def test_rgba_palette(mode, palette) -> None: def test_rgba_palette(mode: str, palette: tuple[int, ...]) -> None:
im = Image.new("P", (1, 1)) im = Image.new("P", (1, 1))
im.putpalette(palette, mode) im.putpalette(palette, mode)
assert im.getpalette() == [1, 2, 3] assert im.getpalette() == [1, 2, 3]

View File

@ -231,11 +231,13 @@ class TestImagingCoreResampleAccuracy:
class TestCoreResampleConsistency: class TestCoreResampleConsistency:
def make_case(self, mode: str, fill: tuple[int, int, int] | float): def make_case(
self, mode: str, fill: tuple[int, int, int] | float
) -> tuple[Image.Image, tuple[int, ...]]:
im = Image.new(mode, (512, 9), fill) im = Image.new(mode, (512, 9), fill)
return im.resize((9, 512), Image.Resampling.LANCZOS), im.load()[0, 0] return im.resize((9, 512), Image.Resampling.LANCZOS), im.load()[0, 0]
def run_case(self, case) -> None: def run_case(self, case: tuple[Image.Image, Image.Image]) -> None:
channel, color = case channel, color = case
px = channel.load() px = channel.load()
for x in range(channel.size[0]): for x in range(channel.size[0]):
@ -353,7 +355,7 @@ class TestCoreResampleAlphaCorrect:
class TestCoreResamplePasses: class TestCoreResamplePasses:
@contextmanager @contextmanager
def count(self, diff): def count(self, diff: int) -> Generator[None, None, None]:
count = Image.core.get_stats()["new_count"] count = Image.core.get_stats()["new_count"]
yield yield
assert Image.core.get_stats()["new_count"] - count == diff assert Image.core.get_stats()["new_count"] - count == diff

View File

@ -12,7 +12,13 @@ from .helper import (
) )
def rotate(im, mode, angle, center=None, translate=None) -> None: def rotate(
im: Image.Image,
mode: str,
angle: int,
center: tuple[int, int] | None = None,
translate: tuple[int, int] | None = None,
) -> None:
out = im.rotate(angle, center=center, translate=translate) out = im.rotate(angle, center=center, translate=translate)
assert out.mode == mode assert out.mode == mode
assert out.size == im.size # default rotate clips output assert out.size == im.size # default rotate clips output
@ -27,13 +33,13 @@ def rotate(im, mode, angle, center=None, translate=None) -> None:
@pytest.mark.parametrize("mode", ("1", "P", "L", "RGB", "I", "F")) @pytest.mark.parametrize("mode", ("1", "P", "L", "RGB", "I", "F"))
def test_mode(mode) -> None: def test_mode(mode: str) -> None:
im = hopper(mode) im = hopper(mode)
rotate(im, mode, 45) rotate(im, mode, 45)
@pytest.mark.parametrize("angle", (0, 90, 180, 270)) @pytest.mark.parametrize("angle", (0, 90, 180, 270))
def test_angle(angle) -> None: def test_angle(angle: int) -> None:
with Image.open("Tests/images/test-card.png") as im: with Image.open("Tests/images/test-card.png") as im:
rotate(im, im.mode, angle) rotate(im, im.mode, angle)
@ -42,7 +48,7 @@ def test_angle(angle) -> None:
@pytest.mark.parametrize("angle", (0, 45, 90, 180, 270)) @pytest.mark.parametrize("angle", (0, 45, 90, 180, 270))
def test_zero(angle) -> None: def test_zero(angle: int) -> None:
im = Image.new("RGB", (0, 0)) im = Image.new("RGB", (0, 0))
rotate(im, im.mode, angle) rotate(im, im.mode, angle)

View File

@ -111,7 +111,7 @@ def test_load_first_unless_jpeg() -> None:
with Image.open("Tests/images/hopper.jpg") as im: with Image.open("Tests/images/hopper.jpg") as im:
draft = im.draft draft = im.draft
def im_draft(mode, size): def im_draft(mode: str, size: tuple[int, int]):
result = draft(mode, size) result = draft(mode, size)
assert result is not None assert result is not None

View File

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import math import math
from typing import Callable
import pytest import pytest
@ -91,7 +92,7 @@ class TestImageTransform:
("LA", (76, 0)), ("LA", (76, 0)),
), ),
) )
def test_fill(self, mode, expected_pixel) -> None: def test_fill(self, mode: str, expected_pixel: tuple[int, ...]) -> None:
im = hopper(mode) im = hopper(mode)
(w, h) = im.size (w, h) = im.size
transformed = im.transform( transformed = im.transform(
@ -142,7 +143,9 @@ class TestImageTransform:
assert_image_equal(blank, transformed.crop((w // 2, 0, w, h // 2))) assert_image_equal(blank, transformed.crop((w // 2, 0, w, h // 2)))
assert_image_equal(blank, transformed.crop((0, h // 2, w // 2, h))) assert_image_equal(blank, transformed.crop((0, h // 2, w // 2, h)))
def _test_alpha_premult(self, op) -> None: def _test_alpha_premult(
self, op: Callable[[Image.Image, tuple[int, int]], Image.Image]
) -> None:
# create image with half white, half black, # create image with half white, half black,
# with the black half transparent. # with the black half transparent.
# do op, # do op,
@ -159,13 +162,13 @@ class TestImageTransform:
assert 40 * 10 == hist[-1] assert 40 * 10 == hist[-1]
def test_alpha_premult_resize(self) -> None: def test_alpha_premult_resize(self) -> None:
def op(im, sz): def op(im: Image.Image, sz: tuple[int, int]) -> Image.Image:
return im.resize(sz, Image.Resampling.BILINEAR) return im.resize(sz, Image.Resampling.BILINEAR)
self._test_alpha_premult(op) self._test_alpha_premult(op)
def test_alpha_premult_transform(self) -> None: def test_alpha_premult_transform(self) -> None:
def op(im, sz): def op(im: Image.Image, sz: tuple[int, int]) -> Image.Image:
(w, h) = im.size (w, h) = im.size
return im.transform( return im.transform(
sz, Image.Transform.EXTENT, (0, 0, w, h), Image.Resampling.BILINEAR sz, Image.Transform.EXTENT, (0, 0, w, h), Image.Resampling.BILINEAR
@ -173,7 +176,9 @@ class TestImageTransform:
self._test_alpha_premult(op) self._test_alpha_premult(op)
def _test_nearest(self, op, mode) -> None: def _test_nearest(
self, op: Callable[[Image.Image, tuple[int, int]], Image.Image], mode: str
) -> None:
# create white image with half transparent, # create white image with half transparent,
# do op, # do op,
# the image should remain white with half transparent # the image should remain white with half transparent
@ -196,15 +201,15 @@ class TestImageTransform:
) )
@pytest.mark.parametrize("mode", ("RGBA", "LA")) @pytest.mark.parametrize("mode", ("RGBA", "LA"))
def test_nearest_resize(self, mode) -> None: def test_nearest_resize(self, mode: str) -> None:
def op(im, sz): def op(im: Image.Image, sz: tuple[int, int]) -> Image.Image:
return im.resize(sz, Image.Resampling.NEAREST) return im.resize(sz, Image.Resampling.NEAREST)
self._test_nearest(op, mode) self._test_nearest(op, mode)
@pytest.mark.parametrize("mode", ("RGBA", "LA")) @pytest.mark.parametrize("mode", ("RGBA", "LA"))
def test_nearest_transform(self, mode) -> None: def test_nearest_transform(self, mode: str) -> None:
def op(im, sz): def op(im: Image.Image, sz: tuple[int, int]) -> Image.Image:
(w, h) = im.size (w, h) = im.size
return im.transform( return im.transform(
sz, Image.Transform.EXTENT, (0, 0, w, h), Image.Resampling.NEAREST sz, Image.Transform.EXTENT, (0, 0, w, h), Image.Resampling.NEAREST
@ -227,7 +232,9 @@ class TestImageTransform:
# Running by default, but I'd totally understand not doing it in # Running by default, but I'd totally understand not doing it in
# the future # the future
pattern = [Image.new("RGBA", (1024, 1024), (a, a, a, a)) for a in range(1, 65)] pattern: list[Image.Image] | None = [
Image.new("RGBA", (1024, 1024), (a, a, a, a)) for a in range(1, 65)
]
# Yeah. Watch some JIT optimize this out. # Yeah. Watch some JIT optimize this out.
pattern = None # noqa: F841 pattern = None # noqa: F841
@ -240,7 +247,7 @@ class TestImageTransform:
im.transform((100, 100), None) im.transform((100, 100), None)
@pytest.mark.parametrize("resample", (Image.Resampling.BOX, "unknown")) @pytest.mark.parametrize("resample", (Image.Resampling.BOX, "unknown"))
def test_unknown_resampling_filter(self, resample) -> None: def test_unknown_resampling_filter(self, resample: Image.Resampling | str) -> None:
with hopper() as im: with hopper() as im:
(w, h) = im.size (w, h) = im.size
with pytest.raises(ValueError): with pytest.raises(ValueError):
@ -250,7 +257,7 @@ class TestImageTransform:
class TestImageTransformAffine: class TestImageTransformAffine:
transform = Image.Transform.AFFINE transform = Image.Transform.AFFINE
def _test_image(self): def _test_image(self) -> Image.Image:
im = hopper("RGB") im = hopper("RGB")
return im.crop((10, 20, im.width - 10, im.height - 20)) return im.crop((10, 20, im.width - 10, im.height - 20))
@ -263,7 +270,7 @@ class TestImageTransformAffine:
(270, Image.Transpose.ROTATE_270), (270, Image.Transpose.ROTATE_270),
), ),
) )
def test_rotate(self, deg, transpose) -> None: def test_rotate(self, deg: int, transpose: Image.Transpose | None) -> None:
im = self._test_image() im = self._test_image()
angle = -math.radians(deg) angle = -math.radians(deg)
@ -313,7 +320,13 @@ class TestImageTransformAffine:
(Image.Resampling.BICUBIC, 1), (Image.Resampling.BICUBIC, 1),
), ),
) )
def test_resize(self, scale, epsilon_scale, resample, epsilon) -> None: def test_resize(
self,
scale: float,
epsilon_scale: float,
resample: Image.Resampling,
epsilon: int,
) -> None:
im = self._test_image() im = self._test_image()
size_up = int(round(im.width * scale)), int(round(im.height * scale)) size_up = int(round(im.width * scale)), int(round(im.height * scale))
@ -342,7 +355,14 @@ class TestImageTransformAffine:
(Image.Resampling.BICUBIC, 1), (Image.Resampling.BICUBIC, 1),
), ),
) )
def test_translate(self, x, y, epsilon_scale, resample, epsilon) -> None: def test_translate(
self,
x: float,
y: float,
epsilon_scale: float,
resample: Image.Resampling,
epsilon: float,
) -> None:
im = self._test_image() im = self._test_image()
size_up = int(round(im.width + x)), int(round(im.height + y)) size_up = int(round(im.width + x)), int(round(im.height + y))

View File

@ -208,7 +208,9 @@ def test_language() -> None:
), ),
ids=("None", "ltr", "rtl2", "rtl", "ttb"), ids=("None", "ltr", "rtl2", "rtl", "ttb"),
) )
def test_getlength(mode, text, direction, expected) -> None: def test_getlength(
mode: str, text: str, direction: str | None, expected: float
) -> None:
ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE)
im = Image.new(mode, (1, 1), 0) im = Image.new(mode, (1, 1), 0)
d = ImageDraw.Draw(im) d = ImageDraw.Draw(im)
@ -230,7 +232,7 @@ def test_getlength(mode, text, direction, expected) -> None:
("i" + ("\u030C" * 15) + "i", "i" + "\u032C" * 15 + "i", "\u035Cii", "i\u0305i"), ("i" + ("\u030C" * 15) + "i", "i" + "\u032C" * 15 + "i", "\u035Cii", "i\u0305i"),
ids=("caron-above", "caron-below", "double-breve", "overline"), ids=("caron-above", "caron-below", "double-breve", "overline"),
) )
def test_getlength_combine(mode, direction, text) -> None: def test_getlength_combine(mode: str, direction: str, text: str) -> None:
if text == "i\u0305i" and direction == "ttb": if text == "i\u0305i" and direction == "ttb":
pytest.skip("fails with this font") pytest.skip("fails with this font")
@ -250,7 +252,7 @@ def test_getlength_combine(mode, direction, text) -> None:
@pytest.mark.parametrize("anchor", ("lt", "mm", "rb", "sm")) @pytest.mark.parametrize("anchor", ("lt", "mm", "rb", "sm"))
def test_anchor_ttb(anchor) -> None: def test_anchor_ttb(anchor: str) -> None:
text = "f" text = "f"
path = f"Tests/images/test_anchor_ttb_{text}_{anchor}.png" path = f"Tests/images/test_anchor_ttb_{text}_{anchor}.png"
f = ImageFont.truetype("Tests/fonts/NotoSans-Regular.ttf", 120) f = ImageFont.truetype("Tests/fonts/NotoSans-Regular.ttf", 120)
@ -306,7 +308,9 @@ combine_tests = (
@pytest.mark.parametrize( @pytest.mark.parametrize(
"name, text, anchor, dir, epsilon", combine_tests, ids=[r[0] for r in combine_tests] "name, text, anchor, dir, epsilon", combine_tests, ids=[r[0] for r in combine_tests]
) )
def test_combine(name, text, dir, anchor, epsilon) -> None: def test_combine(
name: str, text: str, dir: str | None, anchor: str | None, epsilon: float
) -> None:
path = f"Tests/images/test_combine_{name}.png" path = f"Tests/images/test_combine_{name}.png"
f = ImageFont.truetype("Tests/fonts/NotoSans-Regular.ttf", 48) f = ImageFont.truetype("Tests/fonts/NotoSans-Regular.ttf", 48)
@ -337,7 +341,7 @@ def test_combine(name, text, dir, anchor, epsilon) -> None:
("rm", "right"), # pass with getsize ("rm", "right"), # pass with getsize
), ),
) )
def test_combine_multiline(anchor, align) -> None: def test_combine_multiline(anchor: str, align: str) -> None:
# test that multiline text uses getlength, not getsize or getbbox # test that multiline text uses getlength, not getsize or getbbox
path = f"Tests/images/test_combine_multiline_{anchor}_{align}.png" path = f"Tests/images/test_combine_multiline_{anchor}_{align}.png"

View File

@ -10,7 +10,7 @@ from PIL import Image, ImageMorph, _imagingmorph
from .helper import assert_image_equal_tofile, hopper from .helper import assert_image_equal_tofile, hopper
def string_to_img(image_string): def string_to_img(image_string: str) -> Image.Image:
"""Turn a string image representation into a binary image""" """Turn a string image representation into a binary image"""
rows = [s for s in image_string.replace(" ", "").split("\n") if len(s)] rows = [s for s in image_string.replace(" ", "").split("\n") if len(s)]
height = len(rows) height = len(rows)
@ -38,7 +38,7 @@ A = string_to_img(
) )
def img_to_string(im): def img_to_string(im: Image.Image) -> str:
"""Turn a (small) binary image into a string representation""" """Turn a (small) binary image into a string representation"""
chars = ".1" chars = ".1"
width, height = im.size width, height = im.size
@ -48,11 +48,11 @@ def img_to_string(im):
) )
def img_string_normalize(im): def img_string_normalize(im: str) -> str:
return img_to_string(string_to_img(im)) return img_to_string(string_to_img(im))
def assert_img_equal_img_string(a, b_string) -> None: def assert_img_equal_img_string(a: Image.Image, b_string: str) -> None:
assert img_to_string(a) == img_string_normalize(b_string) assert img_to_string(a) == img_string_normalize(b_string)
@ -63,7 +63,7 @@ def test_str_to_img() -> None:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"op", ("corner", "dilation4", "dilation8", "erosion4", "erosion8", "edge") "op", ("corner", "dilation4", "dilation8", "erosion4", "erosion8", "edge")
) )
def test_lut(op) -> None: def test_lut(op: str) -> None:
lb = ImageMorph.LutBuilder(op_name=op) lb = ImageMorph.LutBuilder(op_name=op)
assert lb.get_lut() is None assert lb.get_lut() is None

View File

@ -67,7 +67,7 @@ def test_getcolor_rgba_color_rgb_palette() -> None:
(255, ImagePalette.ImagePalette("RGB", list(range(256)) * 3)), (255, ImagePalette.ImagePalette("RGB", list(range(256)) * 3)),
], ],
) )
def test_getcolor_not_special(index, palette) -> None: def test_getcolor_not_special(index: int, palette: ImagePalette.ImagePalette) -> None:
im = Image.new("P", (1, 1)) im = Image.new("P", (1, 1))
# Do not use transparency index as a new color # Do not use transparency index as a new color

View File

@ -13,7 +13,9 @@ FONT_SIZE = 20
FONT_PATH = "Tests/fonts/DejaVuSans/DejaVuSans.ttf" FONT_PATH = "Tests/fonts/DejaVuSans/DejaVuSans.ttf"
def helper_pickle_file(tmp_path: Path, pickle, protocol, test_file, mode) -> None: def helper_pickle_file(
tmp_path: Path, protocol: int, test_file: str, mode: str | None
) -> None:
# Arrange # Arrange
with Image.open(test_file) as im: with Image.open(test_file) as im:
filename = str(tmp_path / "temp.pkl") filename = str(tmp_path / "temp.pkl")
@ -30,7 +32,7 @@ def helper_pickle_file(tmp_path: Path, pickle, protocol, test_file, mode) -> Non
assert im == loaded_im assert im == loaded_im
def helper_pickle_string(pickle, protocol, test_file, mode) -> None: def helper_pickle_string(protocol: int, test_file: str, mode: str | None) -> None:
with Image.open(test_file) as im: with Image.open(test_file) as im:
if mode: if mode:
im = im.convert(mode) im = im.convert(mode)
@ -64,10 +66,12 @@ def helper_pickle_string(pickle, protocol, test_file, mode) -> None:
], ],
) )
@pytest.mark.parametrize("protocol", range(0, pickle.HIGHEST_PROTOCOL + 1)) @pytest.mark.parametrize("protocol", range(0, pickle.HIGHEST_PROTOCOL + 1))
def test_pickle_image(tmp_path: Path, test_file, test_mode, protocol) -> None: def test_pickle_image(
tmp_path: Path, test_file: str, test_mode: str | None, protocol: int
) -> None:
# Act / Assert # Act / Assert
helper_pickle_string(pickle, protocol, test_file, test_mode) helper_pickle_string(protocol, test_file, test_mode)
helper_pickle_file(tmp_path, pickle, protocol, test_file, test_mode) helper_pickle_file(tmp_path, protocol, test_file, test_mode)
def test_pickle_la_mode_with_palette(tmp_path: Path) -> None: def test_pickle_la_mode_with_palette(tmp_path: Path) -> None:
@ -99,7 +103,9 @@ def test_pickle_tell() -> None:
assert unpickled_image.tell() == 0 assert unpickled_image.tell() == 0
def helper_assert_pickled_font_images(font1, font2) -> None: def helper_assert_pickled_font_images(
font1: ImageFont.FreeTypeFont, font2: ImageFont.FreeTypeFont
) -> None:
# Arrange # Arrange
im1 = Image.new(mode="RGBA", size=(300, 100)) im1 = Image.new(mode="RGBA", size=(300, 100))
im2 = Image.new(mode="RGBA", size=(300, 100)) im2 = Image.new(mode="RGBA", size=(300, 100))
@ -117,7 +123,7 @@ def helper_assert_pickled_font_images(font1, font2) -> None:
@skip_unless_feature("freetype2") @skip_unless_feature("freetype2")
@pytest.mark.parametrize("protocol", list(range(0, pickle.HIGHEST_PROTOCOL + 1))) @pytest.mark.parametrize("protocol", list(range(0, pickle.HIGHEST_PROTOCOL + 1)))
def test_pickle_font_string(protocol) -> None: def test_pickle_font_string(protocol: int) -> None:
# Arrange # Arrange
font = ImageFont.truetype(FONT_PATH, FONT_SIZE) font = ImageFont.truetype(FONT_PATH, FONT_SIZE)
@ -131,7 +137,7 @@ def test_pickle_font_string(protocol) -> None:
@skip_unless_feature("freetype2") @skip_unless_feature("freetype2")
@pytest.mark.parametrize("protocol", list(range(0, pickle.HIGHEST_PROTOCOL + 1))) @pytest.mark.parametrize("protocol", list(range(0, pickle.HIGHEST_PROTOCOL + 1)))
def test_pickle_font_file(tmp_path: Path, protocol) -> None: def test_pickle_font_file(tmp_path: Path, protocol: int) -> None:
# Arrange # Arrange
font = ImageFont.truetype(FONT_PATH, FONT_SIZE) font = ImageFont.truetype(FONT_PATH, FONT_SIZE)
filename = str(tmp_path / "temp.pkl") filename = str(tmp_path / "temp.pkl")

View File

@ -10,7 +10,7 @@ import pytest
from PIL import Image, PSDraw from PIL import Image, PSDraw
def _create_document(ps) -> None: def _create_document(ps: PSDraw.PSDraw) -> None:
title = "hopper" title = "hopper"
box = (1 * 72, 2 * 72, 7 * 72, 10 * 72) # in points box = (1 * 72, 2 * 72, 7 * 72, 10 * 72) # in points
@ -50,7 +50,7 @@ def test_draw_postscript(tmp_path: Path) -> None:
@pytest.mark.parametrize("buffer", (True, False)) @pytest.mark.parametrize("buffer", (True, False))
def test_stdout(buffer) -> None: def test_stdout(buffer: bool) -> None:
# Temporarily redirect stdout # Temporarily redirect stdout
old_stdout = sys.stdout old_stdout = sys.stdout

View File

@ -21,7 +21,7 @@ from PIL import Image
"Tests/images/crash-db8bfa78b19721225425530c5946217720d7df4e.sgi", "Tests/images/crash-db8bfa78b19721225425530c5946217720d7df4e.sgi",
], ],
) )
def test_crashes(test_file) -> None: def test_crashes(test_file: str) -> None:
with open(test_file, "rb") as f: with open(test_file, "rb") as f:
with Image.open(f) as im: with Image.open(f) as im:
with pytest.raises(OSError): with pytest.raises(OSError):

View File

@ -2,6 +2,7 @@ from __future__ import annotations
import shutil import shutil
from pathlib import Path from pathlib import Path
from typing import Callable
import pytest import pytest
@ -17,7 +18,12 @@ test_filenames = ("temp_';", 'temp_";', "temp_'\"|", "temp_'\"||", "temp_'\"&&")
@pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS") @pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS")
class TestShellInjection: class TestShellInjection:
def assert_save_filename_check(self, tmp_path: Path, src_img, save_func) -> None: def assert_save_filename_check(
self,
tmp_path: Path,
src_img: Image.Image,
save_func: Callable[[Image.Image, int, str], None],
) -> None:
for filename in test_filenames: for filename in test_filenames:
dest_file = str(tmp_path / filename) dest_file = str(tmp_path / filename)
save_func(src_img, 0, dest_file) save_func(src_img, 0, dest_file)

View File

@ -42,7 +42,7 @@ from .helper import on_ci
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
@pytest.mark.filterwarnings("ignore:Metadata warning") @pytest.mark.filterwarnings("ignore:Metadata warning")
@pytest.mark.filterwarnings("ignore:Truncated File Read") @pytest.mark.filterwarnings("ignore:Truncated File Read")
def test_tiff_crashes(test_file): def test_tiff_crashes(test_file: str) -> None:
try: try:
with Image.open(test_file) as im: with Image.open(test_file) as im:
im.load() im.load()

View File

@ -53,9 +53,9 @@ def test_nonetype() -> None:
def test_ifd_rational_save(tmp_path: Path) -> None: def test_ifd_rational_save(tmp_path: Path) -> None:
methods = (True, False) methods = [True]
if not features.check("libtiff"): if features.check("libtiff"):
methods = (False,) methods.append(False)
for libtiff in methods: for libtiff in methods:
TiffImagePlugin.WRITE_LIBTIFF = libtiff TiffImagePlugin.WRITE_LIBTIFF = libtiff

View File

@ -1,29 +1,16 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path, PurePath
import pytest import pytest
from PIL import _util from PIL import _util
def test_is_path() -> None: @pytest.mark.parametrize(
# Arrange "test_path", ["filename.ext", Path("filename.ext"), PurePath("filename.ext")]
fp = "filename.ext" )
def test_is_path(test_path) -> None:
# Act
it_is = _util.is_path(fp)
# Assert
assert it_is
def test_path_obj_is_path() -> None:
# Arrange
from pathlib import Path
test_path = Path("filename.ext")
# Act # Act
it_is = _util.is_path(test_path) it_is = _util.is_path(test_path)

View File

@ -1,5 +1,5 @@
Internal Reference Docs Internal Reference
======================= ==================
.. toctree:: .. toctree::
:maxdepth: 2 :maxdepth: 2

View File

@ -33,6 +33,14 @@ Internal Modules
Provides a convenient way to import type hints that are not available Provides a convenient way to import type hints that are not available
on some Python versions. on some Python versions.
.. py:class:: StrOrBytesPath
Typing alias.
.. py:class:: SupportsRead
An object that supports the read method.
.. py:data:: TypeGuard .. py:data:: TypeGuard
:value: typing.TypeGuard :value: typing.TypeGuard

View File

@ -3,7 +3,7 @@
File Handling in Pillow File Handling in Pillow
======================= =======================
When opening a file as an image, Pillow requires a filename, ``pathlib.Path`` When opening a file as an image, Pillow requires a filename, ``os.PathLike``
object, or a file-like object. Pillow uses the filename or ``Path`` to open a object, or a file-like object. Pillow uses the filename or ``Path`` to open a
file, so for the rest of this article, they will all be treated as a file-like file, so for the rest of this article, they will all be treated as a file-like
object. object.

View File

@ -27,11 +27,12 @@
""" """
from __future__ import annotations from __future__ import annotations
from io import BytesIO from typing import IO
from . import ImageFile, ImagePalette, UnidentifiedImageError from . import ImageFile, ImagePalette, UnidentifiedImageError
from ._binary import i16be as i16 from ._binary import i16be as i16
from ._binary import i32be as i32 from ._binary import i32be as i32
from ._typing import StrOrBytesPath
class GdImageFile(ImageFile.ImageFile): class GdImageFile(ImageFile.ImageFile):
@ -80,7 +81,7 @@ class GdImageFile(ImageFile.ImageFile):
] ]
def open(fp: BytesIO, mode: str = "r") -> GdImageFile: def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
""" """
Load texture from a GD image file. Load texture from a GD image file.

View File

@ -40,7 +40,6 @@ import tempfile
import warnings import warnings
from collections.abc import Callable, MutableMapping from collections.abc import Callable, MutableMapping
from enum import IntEnum from enum import IntEnum
from pathlib import Path
from types import ModuleType from types import ModuleType
from typing import IO, TYPE_CHECKING, Any from typing import IO, TYPE_CHECKING, Any
@ -2383,7 +2382,7 @@ class Image:
implement the ``seek``, ``tell``, and ``write`` implement the ``seek``, ``tell``, and ``write``
methods, and be opened in binary mode. methods, and be opened in binary mode.
:param fp: A filename (string), pathlib.Path object or file object. :param fp: A filename (string), os.PathLike object or file object.
:param format: Optional format override. If omitted, the :param format: Optional format override. If omitted, the
format to use is determined from the filename extension. format to use is determined from the filename extension.
If a file object was used instead of a filename, this If a file object was used instead of a filename, this
@ -2398,11 +2397,8 @@ class Image:
filename: str | bytes = "" filename: str | bytes = ""
open_fp = False open_fp = False
if isinstance(fp, Path): if is_path(fp):
filename = str(fp) filename = os.path.realpath(os.fspath(fp))
open_fp = True
elif isinstance(fp, (str, bytes)):
filename = fp
open_fp = True open_fp = True
elif fp == sys.stdout: elif fp == sys.stdout:
try: try:
@ -3225,7 +3221,7 @@ def open(fp, mode="r", formats=None) -> Image:
:py:meth:`~PIL.Image.Image.load` method). See :py:meth:`~PIL.Image.Image.load` method). See
:py:func:`~PIL.Image.new`. See :ref:`file-handling`. :py:func:`~PIL.Image.new`. See :ref:`file-handling`.
:param fp: A filename (string), pathlib.Path object or a file object. :param fp: A filename (string), os.PathLike object or a file object.
The file object must implement ``file.read``, The file object must implement ``file.read``,
``file.seek``, and ``file.tell`` methods, ``file.seek``, and ``file.tell`` methods,
and be opened in binary mode. The file object will also seek to zero and be opened in binary mode. The file object will also seek to zero

View File

@ -33,10 +33,10 @@ import sys
import warnings import warnings
from enum import IntEnum from enum import IntEnum
from io import BytesIO from io import BytesIO
from pathlib import Path
from typing import BinaryIO from typing import BinaryIO
from . import Image from . import Image
from ._typing import StrOrBytesPath
from ._util import is_directory, is_path from ._util import is_directory, is_path
@ -193,7 +193,7 @@ class FreeTypeFont:
def __init__( def __init__(
self, self,
font: bytes | str | Path | BinaryIO | None = None, font: StrOrBytesPath | BinaryIO | None = None,
size: float = 10, size: float = 10,
index: int = 0, index: int = 0,
encoding: str = "", encoding: str = "",
@ -230,8 +230,7 @@ class FreeTypeFont:
) )
if is_path(font): if is_path(font):
if isinstance(font, Path): font = os.path.realpath(os.fspath(font))
font = str(font)
if sys.platform == "win32": if sys.platform == "win32":
font_bytes_path = font if isinstance(font, bytes) else font.encode() font_bytes_path = font if isinstance(font, bytes) else font.encode()
try: try:

View File

@ -14,17 +14,16 @@
# #
from __future__ import annotations from __future__ import annotations
from io import BytesIO
from . import Image, ImageFile from . import Image, ImageFile
from ._binary import i8 from ._binary import i8
from ._typing import SupportsRead
# #
# Bitstream parser # Bitstream parser
class BitStream: class BitStream:
def __init__(self, fp: BytesIO) -> None: def __init__(self, fp: SupportsRead[bytes]) -> None:
self.fp = fp self.fp = fp
self.bits = 0 self.bits = 0
self.bitbuffer = 0 self.bitbuffer = 0

View File

@ -1,7 +1,8 @@
from __future__ import annotations from __future__ import annotations
import os
import sys import sys
from typing import Sequence, Union from typing import Protocol, Sequence, TypeVar, Union
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
from typing import TypeGuard from typing import TypeGuard
@ -19,4 +20,14 @@ else:
Coords = Union[Sequence[float], Sequence[Sequence[float]]] Coords = Union[Sequence[float], Sequence[Sequence[float]]]
__all__ = ["TypeGuard"] _T_co = TypeVar("_T_co", covariant=True)
class SupportsRead(Protocol[_T_co]):
def read(self, __length: int = ...) -> _T_co: ...
StrOrBytesPath = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"]
__all__ = ["TypeGuard", "StrOrBytesPath", "SupportsRead"]

View File

@ -1,17 +1,16 @@
from __future__ import annotations from __future__ import annotations
import os import os
from pathlib import Path
from typing import Any, NoReturn from typing import Any, NoReturn
from ._typing import TypeGuard from ._typing import StrOrBytesPath, TypeGuard
def is_path(f: Any) -> TypeGuard[bytes | str | Path]: def is_path(f: Any) -> TypeGuard[StrOrBytesPath]:
return isinstance(f, (bytes, str, Path)) return isinstance(f, (bytes, str, os.PathLike))
def is_directory(f: Any) -> TypeGuard[bytes | str | Path]: def is_directory(f: Any) -> TypeGuard[StrOrBytesPath]:
"""Checks if an object is a string, and that it points to a directory.""" """Checks if an object is a string, and that it points to a directory."""
return is_path(f) and os.path.isdir(f) return is_path(f) and os.path.isdir(f)