Opening images

Images can be either opened from a file or an existing Pillow/Wand object.

From a file

To open an image, call Image.open() passing in a file-like object that contains the image data.

from willow.image import Image

with open('test.jpg', 'rb') as f:
    i = Image.open(f)

    isinstance(i, Image)

    from willow.image import ImageFile, JPEGImageFile
    isinstance(i, ImageFile)
    isinstance(i, JPEGImageFile)

If it succeeded, this will return a subclass of ImageFile (which itself is a subclass of Image).

The ImageFile subclass it chooses depends on the format of the image ( detected by inspecting the file header). In this case, it used JPEGImageFile as the image we loaded was in JPEG format.

Using different image classes for different formats allows Willow to decide which plugin to use for performing operations on the image. For example, Willow will always favor Wand for resizing GIF images but will always favor Pillow for resizing JPEG and PNG images.

From an existing Pillow object

You can create a Willow Image from an existing PIL.Image object by creating an instance of the PillowImage class (passing the PIL.Image object as the only parameter):

from willow.plugins.pillow import PillowImage

pillow_image = PIL.Image.open(...)

i = PillowImage(pillow_image)

isinstance(i, PillowImage)

from willow.image import Image
isinstance(i, Image)

The same can be done with Wand and OpenCV, which use the WandImage and OpenCVColorImage classes respectively.