generated from allenai/python-package-template
-
Notifications
You must be signed in to change notification settings - Fork 964
Closed
Labels
bugSomething isn't workingSomething isn't working
Description
🐛 Describe the bug
Description
Thanks for this project, but I found an error while converting the following image. The error is as follows:
Error 500: {"detail":"Error converting image(s) to PDF: Image with transparency and a bit depth of 16.\nThis is unsupported due to PIL limitations.\nIf you accept a lossy conversion, you can manually convert your images to 8 bit using `convert -depth 8` from imagemagick\nerror: Refusing to work with multiple >8bit channels.\n"}
Example Image
This is a PNG with alpha channel or 16-bit per channel depth, I'm not sure if you can reproduce the error after saving it.
Fix
Update the image_utils.convert_image_to_pdf_bytes function to handle these image type:
def convert_image_to_pdf_bytes(image_files: Union[str, List[str]]) -> bytes:
if isinstance(image_files, str):
image_files = [image_files]
elif not isinstance(image_files, list) or not image_files:
raise ValueError("image_files must be a non-empty string or list of strings")
for image_file in image_files:
if not os.path.exists(image_file):
raise ValueError(f"File does not exist: {image_file}")
temp_dir = tempfile.mkdtemp()
cleaned_files = []
try:
for image_path in image_files:
with Image.open(image_path) as img:
if img.mode == "RGBA":
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3])
img = background
elif img.mode == "LA":
img = img.convert("L")
elif img.mode != "RGB":
img = img.convert("RGB")
base_name = os.path.splitext(os.path.basename(image_path))[0]
clean_path = os.path.join(temp_dir, f"{base_name}_cleaned.png")
img.save(clean_path, format="PNG")
cleaned_files.append(clean_path)
result = subprocess.run(
["img2pdf"] + cleaned_files,
check=True,
capture_output=True
)
return result.stdout
except subprocess.CalledProcessError as e:
error_msg = e.stderr.decode('utf-8').strip()
raise RuntimeError(f"Error converting image(s) to PDF: {error_msg}") from e
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
Versions
Python 3.11.11
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
Nancis1130 commentedon May 29, 2025
And, this image couldn't be converted fully. The conversion result is below: