Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a binary image stored in database into a word document using python-docx?

Im trying to add images to a word document using python-docx. Im using python3. And the binary is stored i a BLOB column. I can view the image inside Sequel Pro, so it doesn't seems to be a db error.

I have added the gif's and png's to the DB using UPDATE games SET data = LOAD_FILE('~/pictures/image.gif') WHERE id = 1

Im iterating over a bunch of rows. And I have tried using bin() function. Then i got some advice to try the IO package.

import io
document.add_picture(io.BytesIO(item["data"]))

item["data"] is the image binary.

Byt unfortunately this throws me the error:

  File "/usr/local/lib/python3.7/site-packages/docx/image/image.py", line 199, in _ImageHeaderFactory
    raise UnrecognizedImageError
docx.image.exceptions.UnrecognizedImageError

The expected result would be that i can add images to Word with python-docx. I have had this issue with image files, and got things working when using ImageMagic to just convert the images. $ convert image.png image.png. So one option might be so save a temp file and convert it? But that seems like and unnecessary hassle.

like image 697
horan Avatar asked May 12 '26 12:05

horan


1 Answers

All this error means is that python-docx does not recognize the header on the image binary. ImageMagick is more sophisticated about what it will recognize and is able to work out the type. Note that it does save that header differently on writing, to a more conventional form which python-docx is able to pick up just fine.

Most images import without a problem, but there is a lot of variability in image headers, even for something like PNG.

In any case, your images stray far enough from conventional header layout to not be recognized and you'll need to pre-process them before adding them to the document.

like image 191
scanny Avatar answered May 15 '26 02:05

scanny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!