From 272fe0433fd3bbbb839153b8d1af957136aac0f9 Mon Sep 17 00:00:00 2001 From: Johannes Schauer Marin Rodrigues Date: Sat, 2 Jul 2022 21:19:28 +0200 Subject: [PATCH] allow pathlib.Path objects by allowing objects implementing read_bytes function --- README.md | 9 +++++++++ src/img2pdf.py | 13 +++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 81bec1a..8d33a36 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/img2pdf.py b/src/img2pdf.py index 1954d66..ed5a6f3 100755 --- a/src/img2pdf.py +++ b/src/img2pdf.py @@ -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: