allow pathlib.Path objects by allowing objects implementing read_bytes function
This commit is contained in:
parent
ef7b9e739d
commit
272fe0433f
2 changed files with 18 additions and 4 deletions
|
@ -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:
|
with open("name.pdf","wb") as f1, open("test.jpg") as f2:
|
||||||
f1.write(img2pdf.convert(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
|
# using in-memory image data
|
||||||
with open("name.pdf","wb") as f:
|
with open("name.pdf","wb") as f:
|
||||||
f.write(img2pdf.convert("\x89PNG...")
|
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:
|
with open("name.pdf","wb") as f:
|
||||||
f.write(img2pdf.convert(glob.glob("/path/to/*.jpg")))
|
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
|
# ignore invalid rotation values in the input images
|
||||||
with open("name.pdf","wb") as f:
|
with open("name.pdf","wb") as f:
|
||||||
f.write(img2pdf.convert('test.jpg'), rotation=img2pdf.Rotation.ifvalid)
|
f.write(img2pdf.convert('test.jpg'), rotation=img2pdf.Rotation.ifvalid)
|
||||||
|
|
|
@ -2529,11 +2529,16 @@ def convert(*images, **kwargs):
|
||||||
for img in images:
|
for img in images:
|
||||||
# img is allowed to be a path, a binary string representing image data
|
# img is allowed to be a path, a binary string representing image data
|
||||||
# or a file-like object (really anything that implements read())
|
# or a file-like object (really anything that implements read())
|
||||||
|
# or a pathlib.Path object (really anything that implements read_bytes())
|
||||||
|
rawdata = None
|
||||||
|
for fun in "read", "read_bytes":
|
||||||
try:
|
try:
|
||||||
rawdata = img.read()
|
rawdata = getattr(img, fun)()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
|
pass
|
||||||
|
if rawdata is None:
|
||||||
if not isinstance(img, (str, bytes)):
|
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
|
# the thing doesn't have a read() function, so try if we can treat
|
||||||
# it as a file name
|
# it as a file name
|
||||||
try:
|
try:
|
||||||
|
|
Loading…
Reference in a new issue