Search code examples
python-3.xwand

Python Wand error when trying to display simple empty image: 'no encode delegate for this image format'


I'm new to Wand, I tried the following very simple code, to display a red image:

from wand.color import Color
import wand.display

with Image(width=100, height=100, background=Color("red")) as img: 
    wand.display.display(img)

But I'm getting this error:

MissingDelegateError                      Traceback (most recent call last)
<ipython-input-24-6badc0244551> in <module>
    1 with Image(width=100, height=100, background=Color("red")) as img:
----> 2     wand.display.display(img)
    3 

~/dev/.venv/lib/python3.7/site-packages/wand/display.py in display(image, server_name)
    60         ext = '.' + image.format.lower()
    61         path = tempfile.mktemp(suffix=ext)
---> 62         image.save(filename=path)
    63         os.system(('start ' if system == 'Windows' else 'open ') + path)
    64     else:

~/dev/.venv/lib/python3.7/site-packages/wand/image.py in save(self, file, filename, adjoin)
8916                 r = library.MagickWriteImage(self.wand, filename)
8917             if not r:
-> 8918                 self.raise_exception()
8919 
8920 

~/dev/.venv/lib/python3.7/site-packages/wand/resource.py in raise_exception(self, stacklevel)
    228             warnings.warn(e, stacklevel=stacklevel + 1)
    229         elif isinstance(e, Exception):
--> 230             raise e
    231 
    232     def make_blob(self, format=None):

MissingDelegateError: no encode delegate for this image format `' @ error/constitute.c/WriteImage/1240

Looking at the stack trace, I realize Wand temporarily stores the image in a file before displaying it, so I tried adding the following line before calling display():

img.format = 'png'

And it works. Am I missing something here? Is this the expected way of displaying a simple image?


Solution

  • Am I missing something here? Is this the expected way of displaying a simple image?

    The solution you came up with is correct. For Windows / macOS, assumes you are not running an X11 server. It's far easier to write the Image to disk, and ask the OS to display it in your default image viewer.

    The problem

    When creating a canvas, or a pseudo image format (PLASMA: for example), the internal "image info" & coder have yet to be defined. Is your simple image CMYK, or RGB? What about palettes, endianness, & etc etc. ImageMagick is right to throw an exception until the user specifies, at a minimum, a coder / delegate to write with.

    The fix

    Luckily, with most open-source projects, this was reported and patched in Wand a month ago(?). Wand's display() method will hand over a PNG file to the OS in the event that a Image's coder (format) is not defined.

    Unluckily, with most open-source projects, it can take weeks for patch versions to be shipped & distributed. Best keep an eye on Wand's release notes