wagtail / Willow

A wrapper that combines the functionality of multiple Python image libraries into one API
https://willow.wagtail.org/
BSD 3-Clause "New" or "Revised" License
273 stars 53 forks source link

Allow overriding of functions for specific file types #88

Open dbramwell opened 3 years ago

dbramwell commented 3 years ago

Recently I tried to make Wagtail use gifsicle when resizing gifs, rather than wand and imagemagik as it seemed to be quicker at it.

I thought I could do this by adding the following code with implementations of the functions that just called the gifsicle cli:

        registry.register_operation(GIFImageFile, "auto_orient", auto_orient)
        registry.register_operation(GIFImageFile, "resize", resize)
        registry.register_operation(GIFImageFile, "crop", crop)
        registry.register_operation(GIFImageFile, "save_as_gif", save_as_gif)

After some experimentation this approach worked as expected, however I then got intermittent errors with jpegs. Occasionally throwing an error here stating that cost was None.

This seems to boil down to the registry trying to figure out how it can convert a JPEGImageFile to a GIFImageFile, and adding the following has fixed it for our usecase:

        for image_class in registry.get_image_classes():
            if image_class is GIFImageFile:
                break
            registry.register_converter(image_class, GIFImageFile, None, float("inf"))

I'm unsure if you intended for register_operation to be used in this way, but it seems quite useful and am happy to work on a pull request to remove the need for the register_converter stuff and add tests.