# UnrecognizedImageError - Image Insertion Error - Python-docx

## 01 June 2019 - 1 answer

I am trying to insert an wmf file to docx using python-docx which is producing the following traceback.

Traceback (most recent call last):
write_docx(ppt_data, False)
File "C:\Python34\lib\site-packages\docx\document.py", line 72, in add_picture
File "C:\Python34\lib\site-packages\docx\text\run.py", line 62, in add_picture
inline = self.part.new_pic_inline(image_path_or_stream, width, height)
File "C:\Python34\lib\site-packages\docx\parts\story.py", line 56, in new_pic_inline
File "C:\Python34\lib\site-packages\docx\parts\story.py", line 29, in get_or_add_image
File "C:\Python34\lib\site-packages\docx\package.py", line 31, in get_or_add_image_part
File "C:\Python34\lib\site-packages\docx\package.py", line 74, in get_or_add_image_part
image = Image.from_file(image_descriptor)
File "C:\Python34\lib\site-packages\docx\image\image.py", line 55, in from_file
return cls._from_stream(stream, blob, filename)
File "C:\Python34\lib\site-packages\docx\image\image.py", line 176, in _from_stream
File "C:\Python34\lib\site-packages\docx\image\image.py", line 199, in _ImageHeaderFactory
raise UnrecognizedImageError
docx.image.exceptions.UnrecognizedImageError


The image file is in .wmf format.

Any help or suggestion appreciated.

python-docx identifies the type of an image-file by "recognizing" its distinctive header. In this way it can distinguish JPEG from PNG, from TIFF, etc. This is much more reliable than mapping a filename extension and much more convenient than requiring the user to tell you the type. It's a pretty common approach.

This error indicates python-docx is not finding a header it recognizes. Windows Metafile format (WMF) can be tricky this way, there's a lot of leeway in the proprietary spec and variation in file specimens in the field.

To fix this, I recommend you read the file with something that does recognize it (I would start with Pillow) and have it "convert" it into the same or another format, hopefully correcting the header in the process.

First I would try just reading it and saving it as WMF (or perhaps EMF if that's an option). This might be enough to do the trick. If you have to change to an intermediate format and then back, that could be lossy, but maybe better than nothing.

ImageMagick might be another good choice to try because it probably has better coverage than Pillow does.