Skip to content

Use plugin method directly when saving PDFs#9547

Open
radarhere wants to merge 1 commit intopython-pillow:mainfrom
radarhere:plugins
Open

Use plugin method directly when saving PDFs#9547
radarhere wants to merge 1 commit intopython-pillow:mainfrom
radarhere:plugins

Conversation

@radarhere
Copy link
Copy Markdown
Member

@radarhere radarhere commented Apr 6, 2026

Resolves #9545

from PIL import Image
im = Image.new("RGB", (1, 1))
im.save("out.pdf")

currently raises

Traceback (most recent call last):
  File "demo.py", line 3, in <module>
    im.save("out.pdf")
  File "PIL/Image.py", line 2713, in save
    save_handler(self, fp, filename)
  File "PIL/PdfImagePlugin.py", line 262, in _save
    image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)
  File "PIL/PdfImagePlugin.py", line 151, in _write_image
    Image.SAVE["JPEG"](im, op, filename)
KeyError: 'JPEG'

The problem is that at line 151 (and for mode RGBA at line 154) JpegImagePlugin (and Jpeg2KImagePlugin) haven't necessarily been imported.

elif decode_filter == "DCTDecode":
Image.SAVE["JPEG"](im, op, filename)
elif decode_filter == "JPXDecode":
del dict_obj["BitsPerComponent"]
Image.SAVE["JPEG2000"](im, op, filename)

One solution would be to import the plugins, so that register_save() is called, and still use Image.SAVE. However, lint raises an error that the imported plugins are not used.

I think it is better to actually call the plugin method directly, like MpoImagePlugin does.

from . import JpegImagePlugin

JpegImagePlugin._save(im, op, filename)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KeyError: 'JPEG' when saving RGB images to PDF without explicit format argument

1 participant