Reputation: 31
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.
Upvotes: 3
Views: 897
Reputation: 29031
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.
Upvotes: 1