Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added type hints #8268

Merged
merged 1 commit into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2052,7 +2052,11 @@
msg = "illegal image mode"
raise ValueError(msg)
if isinstance(data, ImagePalette.ImagePalette):
palette = ImagePalette.raw(data.rawmode, data.palette)
if data.rawmode is not None:
palette = ImagePalette.raw(data.rawmode, data.palette)

Check warning on line 2056 in src/PIL/Image.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/Image.py#L2056

Added line #L2056 was not covered by tests
else:
palette = ImagePalette.ImagePalette(palette=data.palette)
palette.dirty = 1
else:
if not isinstance(data, bytes):
data = bytes(data)
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/ImageDraw2.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def polygon(self, xy: Coords, *options: Any) -> None:
"""
self.render("polygon", xy, *options)

def rectangle(self, xy: Coords, *options) -> None:
def rectangle(self, xy: Coords, *options: Any) -> None:
"""
Draws a rectangle.

Expand Down
6 changes: 3 additions & 3 deletions src/PIL/ImageFont.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,12 +269,12 @@ def load_from_bytes(f) -> None:
else:
load_from_bytes(font)

def __getstate__(self):
def __getstate__(self) -> list[Any]:
return [self.path, self.size, self.index, self.encoding, self.layout_engine]

def __setstate__(self, state):
def __setstate__(self, state: list[Any]) -> None:
path, size, index, encoding, layout_engine = state
self.__init__(path, size, index, encoding, layout_engine)
FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)

def getname(self) -> tuple[str | None, str | None]:
"""
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/ImagePalette.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def save(self, fp: str | IO[str]) -> None:
# Internal


def raw(rawmode, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
palette = ImagePalette()
palette.rawmode = rawmode
palette.palette = data
Expand Down
2 changes: 1 addition & 1 deletion src/PIL/Jpeg2KImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def reduce(self):
return self._reduce or super().reduce

@reduce.setter
def reduce(self, value):
def reduce(self, value: int) -> None:
self._reduce = value

def load(self) -> Image.core.PixelAccess | None:
Expand Down
45 changes: 26 additions & 19 deletions src/PIL/PdfImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import math
import os
import time
from typing import IO
from typing import IO, Any

from . import Image, ImageFile, ImageSequence, PdfParser, __version__, features

Expand All @@ -48,7 +48,12 @@
# (Internal) Image save plugin for the PDF format.


def _write_image(im, filename, existing_pdf, image_refs):
def _write_image(
im: Image.Image,
filename: str | bytes,
existing_pdf: PdfParser.PdfParser,
image_refs: list[PdfParser.IndirectReference],
) -> tuple[PdfParser.IndirectReference, str]:
# FIXME: Should replace ASCIIHexDecode with RunLengthDecode
# (packbits) or LZWDecode (tiff/lzw compression). Note that
# PDF 1.2 also supports Flatedecode (zip compression).
Expand All @@ -61,10 +66,10 @@

width, height = im.size

dict_obj = {"BitsPerComponent": 8}
dict_obj: dict[str, Any] = {"BitsPerComponent": 8}
if im.mode == "1":
if features.check("libtiff"):
filter = "CCITTFaxDecode"
decode_filter = "CCITTFaxDecode"
dict_obj["BitsPerComponent"] = 1
params = PdfParser.PdfArray(
[
Expand All @@ -79,22 +84,23 @@
]
)
else:
filter = "DCTDecode"
decode_filter = "DCTDecode"

Check warning on line 87 in src/PIL/PdfImagePlugin.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/PdfImagePlugin.py#L87

Added line #L87 was not covered by tests
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
procset = "ImageB" # grayscale
elif im.mode == "L":
filter = "DCTDecode"
decode_filter = "DCTDecode"
# params = f"<< /Predictor 15 /Columns {width-2} >>"
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
procset = "ImageB" # grayscale
elif im.mode == "LA":
filter = "JPXDecode"
decode_filter = "JPXDecode"
# params = f"<< /Predictor 15 /Columns {width-2} >>"
procset = "ImageB" # grayscale
dict_obj["SMaskInData"] = 1
elif im.mode == "P":
filter = "ASCIIHexDecode"
decode_filter = "ASCIIHexDecode"
palette = im.getpalette()
assert palette is not None
dict_obj["ColorSpace"] = [
PdfParser.PdfName("Indexed"),
PdfParser.PdfName("DeviceRGB"),
Expand All @@ -110,15 +116,15 @@
image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]
dict_obj["SMask"] = image_ref
elif im.mode == "RGB":
filter = "DCTDecode"
decode_filter = "DCTDecode"
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")
procset = "ImageC" # color images
elif im.mode == "RGBA":
filter = "JPXDecode"
decode_filter = "JPXDecode"
procset = "ImageC" # color images
dict_obj["SMaskInData"] = 1
elif im.mode == "CMYK":
filter = "DCTDecode"
decode_filter = "DCTDecode"
dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")
procset = "ImageC" # color images
decode = [1, 0, 1, 0, 1, 0, 1, 0]
Expand All @@ -131,31 +137,32 @@

op = io.BytesIO()

if filter == "ASCIIHexDecode":
if decode_filter == "ASCIIHexDecode":
ImageFile._save(im, op, [("hex", (0, 0) + im.size, 0, im.mode)])
elif filter == "CCITTFaxDecode":
elif decode_filter == "CCITTFaxDecode":
im.save(
op,
"TIFF",
compression="group4",
# use a single strip
strip_size=math.ceil(width / 8) * height,
)
elif filter == "DCTDecode":
elif decode_filter == "DCTDecode":
Image.SAVE["JPEG"](im, op, filename)
elif filter == "JPXDecode":
elif decode_filter == "JPXDecode":
del dict_obj["BitsPerComponent"]
Image.SAVE["JPEG2000"](im, op, filename)
else:
msg = f"unsupported PDF filter ({filter})"
msg = f"unsupported PDF filter ({decode_filter})"

Check warning on line 156 in src/PIL/PdfImagePlugin.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/PdfImagePlugin.py#L156

Added line #L156 was not covered by tests
raise ValueError(msg)

stream = op.getvalue()
if filter == "CCITTFaxDecode":
filter: PdfParser.PdfArray | PdfParser.PdfName
if decode_filter == "CCITTFaxDecode":
stream = stream[8:]
filter = PdfParser.PdfArray([PdfParser.PdfName(filter)])
filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)])
else:
filter = PdfParser.PdfName(filter)
filter = PdfParser.PdfName(decode_filter)

image_ref = image_refs.pop(0)
existing_pdf.write_obj(
Expand Down
Loading
Loading