Preserve image metadata with Wagtail rendered images

I would like to find a way to preserve some or all of the image metadata when Wagtail generates renditions from the original.

I have found the following reference in the Wagtail documentation about the function <generate_rendition_file>:

NOTE: The responsibility of generating the new image from the original falls to the supplied filter object. If you want to do anything custom with rendition images (for example, to preserve metadata from the original image), you might want to consider swapping out filter for an instance of a custom Filter subclass of your design.

It mentions the use of a filter, but as I am new to Django and Wagtail, I have not been able to determine how or where this would be used.

This is an example of my code creating the renditions:

      {% image picture max-800x600 format-webp preserve-svg as picture_image %}
      {% image picture max-1600x1600 format-webp preserve-svg as original_image %}

I would appreciate any help or guidance to figure this out.

I managed to implement a solution which worked for me, and may others might find it useful too.

In the end, I abandoned the idea of preserving metadata, since I only wanted to set specific exif tags, that are common to all images.

The summarised steps are as follows:

Create a custom image model (there's plenty of existing guidance on that)

I copied the existing code for get_rendition and simply added a call to another method which sets the exif values. The change looks like this:

    try:
        rendition = self.find_existing_rendition(filter)
    except Rendition.DoesNotExist:
        rendition = self.create_rendition(filter)
        # Reuse this rendition if requested again from this object
        self._add_to_prefetched_renditions(rendition)
        #only set exif for new renditions
        self.set_custom_exif(rendition)      

Setting the exif values used the standard Pillow library.

I copied shortcuts.py into my app. I made a minor change to get_rendition_or_not_found:

replacing return image.get_rendition(specs) with return CustomImage.get_custom_rendition(image, specs)

In retrospect, may this step wasn't required, as wagtailimages_tags may have used my new shortcuts.py, but in any case I copied and renamed 'wagtailimages_tags' into my app.

I changed the following import to refer to my new shortcuts.py:

from wagtail.images.shortcuts import (
get_rendition_or_not_found,
get_renditions_or_not_found,
)

Lastly, I simply replaced references to wagtailimages_tags with the name of my revised tag file, in each of the relevant templates which create renditions.

I am certain this solution is likely not the most elegant, but it gave me a result I could live with, at least until a better one comes along.

Back to Top