在 Python 中生成 rendition

由 Wagtail {% image %} 模板标签生成的原始图片的渲染版本被称为“rendition”, 它们在首次调用时会作为新的图片文件存入站点的 [media]/images 目录。

图片 rendition 也可以通过原生的 get_rendition() 方法从 Python 动态生成,例如:

newimage = myimage.get_rendition("fill-300x150|jpegquality-60")

如果 myimage 的文件名是 foo.jpg,就会生成一个名为 foo.fill-300x150.jpegquality-60.jpg 的新 rendition 图片文件,并保存到站点的 [media]/images 目录。 参数选项与 {% image %} 模板标签的过滤规格完全相同,应以 | 分隔。

生成的 Rendition 对象会带有该图片版本特有的属性,例如 url、width 和 height。因此,像下面这样的写法可以用在 API 生成器里:

url = myimage.get_rendition("fill-300x186|jpegquality-60").url

属于生成该 Rendition 的原始图片的属性(例如 title),可以 通过 Rendition 的 image 属性访问:

    >>> newimage.image.title
    'Blue Sky'
    >>> newimage.image.is_landscape()
    True

另见:如何在模板中使用图片

为同一张图片生成多个 rendition

你可以用原生的 get_renditions() 方法从 Python 为同一张图片生成多个 rendition。它接受任意数量的“规格”字符串或 Filter 实例,并会以比逐个生成高效得多的方式生成一组匹配的 rendition。例如:

image.get_renditions("width-600", "height-400", "fill-300x186|jpegquality-60")

返回值是一个以传给该方法的各个规格为键的 rendition 字典。上面示例的返回值看起来像这样:

{
    "width-600": <Rendition: Rendition object (7)>,
    "height-400": <Rendition: Rendition object (8)>,
    "fill-300x186|jpegquality-60": <Rendition: Rendition object (9)>,
}

如果任何规格中包含 preserve-svg 指令,生成的字典键将是该 rendition 最终使用的过滤规格(省略 preserve-svg 指令,以及在图片是 SVG 时的任何非 SVG 安全操作),而不是最初传入的那个。这可能导致列表中的多个规格解析成同一个最终值——例如,如果列表中包含 width-400|format-jpeg|preserve-svg 和 width-400|format-webp|preserve-svg,当作用于 SVG 图片时它们都会归约为 width-400。在这种情况下,返回值的条目数会少于原始列表。

缓存图片 rendition

Wagtail 会缓存图片 rendition 的查找,这可以改善包含大量图片的页面的性能。

默认情况下,Wagtail 会尝试使用名为 "renditions" 的缓存。如果不存在这样的缓存,它会回退到使用默认缓存。

重新生成已有的 rendition

你也可以直接在控制台中使用图片管理命令来重新生成 rendition:

./manage.py wagtail_update_image_renditions

你可以从 wagtail_update_image_renditions 了解更多关于该命令的内容

预取图片 rendition

当使用 queryset 渲染图片列表或带图片的对象列表时,你可以用一次额外的查询预取所需的 rendition。对于很长的条目列表,或者每个条目要使用多个 rendition 的情形,这可以带来显著的性能提升。

图片 QuerySet

在处理 Image QuerySet 时,你可以利用 Wagtail 内置的 prefetch_renditions queryset 方法来预取所需的 rendition。

例如,假设你正在渲染某个用户上传的所有图片列表:

def get_images_uploaded_by_user(user):
    return ImageModel.objects.filter(uploaded_by_user=user)

上面的写法稍作修改,就可以预取所返回图片的 rendition:

def get_images_uploaded_by_user(user):
    return ImageModel.objects.filter(uploaded_by_user=user).prefetch_renditions()

即使我们可能并不需要它们,上面的写法也会预取所有 rendition。

如果你项目中的图片往往有非常多 rendition,而你事先知道需要哪些,你也许可以考虑给 prefetch_renditions 方法指定一组过滤器,只选出渲染所需的那部分 rendition。例如:

def get_images_uploaded_by_user(user):
    # 只指定渲染所需的 rendition
    return ImageModel.objects.filter(uploaded_by_user=user).prefetch_renditions(
        "fill-700x586", "min-600x400", "max-940x680"
    )

非图片 QuerySet

如果你处理的是非图片模型,你可以利用 Django 内置的 prefetch_related() queryset 方法来预取 rendition。

例如,假设你正在渲染一个事件列表(每个事件都有缩略图)。你的代码可能像这样:

def get_events():
    return EventPage.objects.live().select_related("listing_image")

上面的写法稍作修改,就可以预取列表图片的 rendition:

def get_events():
    return (
        EventPage.objects.live()
        .select_related("listing_image")
        .prefetch_related("listing_image__renditions")
    )

如果你事先知道需要哪些 rendition,你可以过滤要使用的 rendition queryset:

from django.db.models import Prefetch
from wagtail.images import get_image_model


def get_events():
    Image = get_image_model()
    filters = ["fill-300x186", "fill-600x400", "fill-940x680"]

    # 用 `Prefetch` 只获取所需的 rendition
    prefetch_images_and_renditions = Prefetch(
        "listing_image", queryset=Image.objects.prefetch_renditions(*filters)
    )
    return EventPage.objects.live().prefetch_related(prefetch_images_and_renditions)

涉及 rendition 生成的模型方法

以下 AbstractImage 模型方法参与查找和生成 rendition。如果使用自定义图片模型,你可以在模型上覆盖其中任一方法,以定制其行为:

class wagtail.images.models.AbstractImage
get_rendition(filter: Filter | str) → AbstractRendition

Returns a Rendition instance with a file field value (an image) reflecting the supplied filter value and focal point values from this object.

Note: If using custom image models, an instance of the custom rendition model will be returned.

find_existing_rendition(filter: Filter) → AbstractRendition

Returns an existing Rendition instance with a file field value (an image) reflecting the supplied filter value and focal point values from this object.

If no such rendition exists, a DoesNotExist error is raised for the relevant model.

Note: If using custom image models, an instance of the custom rendition model will be returned.

create_rendition(filter: Filter) → AbstractRendition

Creates and returns a Rendition instance with a file field value (an image) reflecting the supplied filter value and focal point values from this object.

This method is usually called by Image.get_rendition(), after first checking that a suitable rendition does not already exist.

Note: If using custom image models, an instance of the custom rendition model will be returned.

get_renditions(*filters: Filter | str) → dict[str, AbstractRendition]

Returns a dict of Rendition instances with image files reflecting the supplied filters, keyed by filter spec patterns.

Note: If using custom image models, instances of the custom rendition model will be returned.

find_existing_renditions(*filters: Filter) → dict[Filter, AbstractRendition]

Returns a dictionary of existing Rendition instances with file values (images) reflecting the supplied filters and the focal point values from this object.

Filters for which an existing rendition cannot be found are omitted from the return value. If none of the requested renditions have been created before, the return value will be an empty dict.

create_renditions(*filters: Filter) → dict[Filter, AbstractRendition]

Creates multiple Rendition instances with image files reflecting the supplied filters, and returns them as a dict keyed by the relevant Filter instance. Where suitable renditions already exist in the database, they will be returned instead, so as not to create duplicates.

This method is usually called by Image.get_renditions(), after first checking that a suitable rendition does not already exist.

Note: If using custom image models, an instance of the custom rendition model will be returned.

generate_rendition_file(filter: Filter, *, source: django.core.files.File = None) → django.core.files.File

Generates an in-memory image matching the supplied filter value and focal point value from this object, wraps it in a File object with a suitable filename, and returns it. The return value is used as the file field value for rendition objects saved by AbstractImage.create_rendition().

If the contents of self.file has already been read into memory, the source keyword can be used to provide a reference to the in-memory File, bypassing the need to reload the image contents from storage.

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.