Skip to content

Page.insertImage fails with keep_proportion=False #728

@epitavy

Description

@epitavy

My config:

  • Operating system: Linux with Ubuntu 20.04.1 LTS
  • Python version: 3.8.5
  • PyMuPDF version: 1.18.4, installed with pip 20.0.2

I have an application that generates QRcode, which are available under stream byte. I don't want to save these on disk. I want to insert these QR codes on an single pdf pages and I use the insertImage of the Page class. My code is the following:

>>> doc = fitz.Document()
>>> doc.newPage()
>>> page = doc.loadPage(0)
>>> type(img)
<class 'PIL.Image.Image'>
>>> img_stream = img.tobytes()
>>> type(img_stream)
<class 'bytes'>
>>> rect = fitz.Rect(0, 0, 290, 290)
>>> page.insertImage(rect, stream=img_stream)
File "/home/user/.venv/lib/python3.8/site-packages/fitz/utils.py", line 331, in insertImage
    w, h = img_prof["width"], img_prof["height"]
TypeError: 'NoneType' object is not subscriptable
>>> page.insertImage(rect, stream=img_stream, keep_proportion=False)
File "/home/user/.venv/lib/python3.8/site-packages/fitz/utils.py", line 364, in insertImage
    xref = doc.InsertedImages.get(digest, 0)  # reuse any previously inserted image
UnboundLocalError: local variable 'digest' referenced before assignment

I expected some explicit error message or the function to work and add my image in the page.

I first thought that I got errors because the byte stream is not exactly as expected but I looked a bit in the code and it seems that some checks are missing.
It appears to me that page.insertImage(rect, stream=img_stream) fails because TOOLS.image_profile(stream, keep_image=True) in utils.py returns None.
This piece of code is not called whith keep_proportion=False, so I made a second attempt with page.insertImage(rect, stream=img_stream, keep_proportion=False) and this time it fails because digest in only defined when keep_proportion=True.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions