allow pathlib.Path objects by allowing objects implementing read_bytes function

pull/149/head
Johannes Schauer Marin Rodrigues 2 years ago committed by Johannes Schauer Marin Rodrigues
parent ef7b9e739d
commit 272fe0433f

@ -146,6 +146,10 @@ The package can also be used as a library:
with open("name.pdf","wb") as f1, open("test.jpg") as f2:
f1.write(img2pdf.convert(f2))
# opening using pathlib
with open("name.pdf","wb") as f:
f.write(img2pdf.convert(pathlib.Path('test.jpg')))
# using in-memory image data
with open("name.pdf","wb") as f:
f.write(img2pdf.convert("\x89PNG...")
@ -188,6 +192,11 @@ The package can also be used as a library:
with open("name.pdf","wb") as f:
f.write(img2pdf.convert(glob.glob("/path/to/*.jpg")))
# convert all files matching a glob using pathlib.Path
from pathlib import Path
with open("name.pdf","wb") as f:
f.write(img2pdf.convert(*Path("/path").glob("**/*.jpg")))
# ignore invalid rotation values in the input images
with open("name.pdf","wb") as f:
f.write(img2pdf.convert('test.jpg'), rotation=img2pdf.Rotation.ifvalid)

@ -2529,11 +2529,16 @@ def convert(*images, **kwargs):
for img in images:
# img is allowed to be a path, a binary string representing image data
# or a file-like object (really anything that implements read())
try:
rawdata = img.read()
except AttributeError:
# or a pathlib.Path object (really anything that implements read_bytes())
rawdata = None
for fun in "read", "read_bytes":
try:
rawdata = getattr(img, fun)()
except AttributeError:
pass
if rawdata is None:
if not isinstance(img, (str, bytes)):
raise TypeError("Neither implements read() nor is str or bytes")
raise TypeError("Neither read(), read_bytes() nor is str or bytes")
# the thing doesn't have a read() function, so try if we can treat
# it as a file name
try:

Loading…
Cancel
Save