Meringue Thumbnail¤
This package provides functionality for generating image thumbnails. It supports resizing, cropping, format conversion, and various processing strategies based on a chain of jobs (commands).
The main functionality is based on the Thumbnailer class, which processes images using a configurable job chain — a sequence of properties and actions applied to an image.
Concept¤
The job chain is a list of string commands that are executed sequentially. Commands are divided into two types:
- Properties — set parameters for subsequent actions (e.g., target size, resize method). Properties are written in the format
key:value. - Actions — perform image transformations (e.g., resize, crop). Actions are written as a single word.
The order of commands matters: properties must be set before the actions that use them. The order of actions is also important — for example, resize followed by crop will first scale the image and then trim the canvas, while crop followed by resize will first trim and then scale, producing different results.
Available properties¤
s:<width>x<height>— sets the target size for subsequent actions. If one dimension is omitted (e.g.,s:400x), it will be calculated proportionally.maxw:<width>— sets the maximum width.maxh:<height>— sets the maximum height.c:<r> <g> <b> <a>— background color for cropping in RGBA format (e.g.,c:255 255 255 255).cm:<horizontal> <vertical>— crop anchor point. Horizontal:left,center,right. Vertical:top,center,bottom. Single valuecenteris also accepted.rm:<method>— resize method:cover(fill the target area),contain(fit within the target area),stretch(stretch to exact size).rs:<strategy>— resize strategy:standard,no_increase(do not upscale),no_reduce(do not downscale).
Available actions¤
resize— resizes the image according to the current target size and resize method/strategy.crop— crops or extends the canvas to the current target size, positioning the image according to the crop method.
Supported formats¤
The following image formats are supported: BMP, EPS, GIF, ICO, JPEG, PNG, TIFF, WEBP.
Setup¤
Add meringue.thumbnail to INSTALLED_APPS:
The package requires Pillow for image processing:
Usage¤
Shortcut¤
The simplest way to generate a thumbnail is using the get_thumbnail shortcut:
from pathlib import Path
from meringue.thumbnail.shortcuts import get_thumbnail
url = get_thumbnail(
file_path=Path("/path/to/image.jpg"),
job_chain=["s:300x200", "rm:cover", "resize", "crop"],
out_format="WEBP",
)
The file_path must point to an existing absolute source path. If the source file does not exist, a dummy image URL will be returned. The out_format argument is optional and defaults to THUMBNAIL_DEFAULT_FORMAT.
Additional keyword arguments are passed to ThumbnailImage.save, so you can override Pillow save options for a single thumbnail or force regeneration of an already saved thumbnail:
url = get_thumbnail(
file_path=Path("/path/to/image.jpg"),
job_chain=["s:300x200", "rm:cover", "resize", "crop"],
out_format="JPEG",
quality=90,
force=True,
)
If a thumbnail can't be made or is not ready yet, the shortcut returns a dummy image URL instead.
Dummy image¤
One broken or missing image must not break the whole page or API response, so the thumbnail fields (MImageField, MImageSetField), the get_thumbnail shortcut and the thumbnail template filter never raise thumbnail errors. Instead they return the URL of a dummy image made by get_dummy_image_url:
- the source file does not exist — logged as
ERRORwithout a traceback; - any other thumbnail error (a broken source image, a storage or S3 error, a wrong job chain, etc.) — logged as
ERRORwith the traceback and the source file name; - the thumbnail is being made by another process (see Cache) — not an error, logged as
DEBUG; it can be turned off withlocked_dummy=False.
MImageSetField returns the dummy for the whole set ([{"url": ..., "type": "image/png"}]) instead of a partially filled srcset.
The Thumbnailer and ThumbnailImage themselves never return the dummy: they raise exceptions (or set ThumbnailImage.locked), so the calling code decides what to do.
The dummy URL depends on DEBUG:
DEBUG = True— the URL is made from THUMBNAIL_DUMMYIMAGE_TEMPLATE (//dummyimage.com/{width}x{height}/9e9e9e/424242.pngby default). The size is taken from the lasts:<width>x<height>of the job chain (42x42if there is none), so the dummy has the size of the thumbnail and the layout does not break;DEBUG = False— the URL is made from THUMBNAIL_DUMMYIMAGE_URL ({static_url}images/noise.pngby default, so the project must provideimages/noise.pngin its static files).
Both settings support {static_url} (STATIC_URL at the moment of the call), {width} and {height} placeholders.
MERINGUE = {
"THUMBNAIL_DUMMYIMAGE_URL": "{static_url}img/no-image.svg",
# or a service that makes a dummy of the thumbnail size
# "THUMBNAIL_DUMMYIMAGE_URL": "https://cdn.example.com/dummy/{width}x{height}.png",
}
Use get_dummy_image_url to return the same dummy from your own shortcuts, fields or views:
from meringue.thumbnail.generators import DefaultThumbnailer
from meringue.thumbnail.dummy import get_dummy_image_url
job_chain = ["s:300x200", "rm:cover", "resize", "crop"]
try:
thumbnail = DefaultThumbnailer(product.image, job_chain=job_chain).get_thumbnail("WEBP")
url = get_dummy_image_url(job_chain) if thumbnail.locked else thumbnail.url
except Exception:
logger.exception("Failed to make a thumbnail for `%s`", product.image.name)
url = get_dummy_image_url(job_chain)
The job_chain argument is optional; it is used only to get the dummy size in DEBUG mode.
Note
_dummyimage is a deprecated alias of get_dummy_image_url and will be removed in the future.
Thumbnailer¤
For more control, you can use the Thumbnailer directly:
from meringue.thumbnail.generators import DefaultThumbnailer
thumbnailer = DefaultThumbnailer(
product.image, # model FieldFile
job_chain=["s:600x400", "resize", "s:400x400", "crop"],
)
thumbnail = thumbnailer.get_thumbnail("WEBP")
print(thumbnail.url)
The source image (image_path argument) is a model FieldFile (it works with any storage, including S3) or an absolute local Path.
The source image is read only if the thumbnail is not saved yet. It is read and decoded once per FieldFile, and every job chain is applied once for all output formats. So MImageSetField with two dimensions makes four thumbnails with one source read, one decode and two resizes.
The returned thumbnail file name is based on the source image path and the job chain. Save options passed through get_thumbnail() or Thumbnailer.get_thumbnail() do not change the generated file name. Use force=True when you need to overwrite an existing thumbnail with different save options.
Templatetags¤
thumbnail¤
Image processing filter. Applied to an image: an absolute local file path or a model
FieldFile (any storage, e.g. S3). Expects comma-separated
processing parameters as arguments. Actions are executed in the order they are specified.
For example:
s:600x400,resize,s:400x400,crop— first sets the target size to 600x400, then resizes the image to that size, then sets a new target size of 400x400, and finally crops the canvas to 400x400.crop,s:400x400— produces no result because the new size is specified after the crop action (swapping the order would crop the image to a 400x400 square).
Filter arguments:
s:<width>x<height>— sets the target size for subsequent actions.maxw:<width>— sets the maximum width.maxh:<height>— sets the maximum height.crop— changes the canvas size to the last specified target size.resize— resizes the image to the last specified target size.c:<color>— background fill color for crop in RGBA format (e.g.,c:255 255 255 255).cm:left|center|right top|bottom— crop anchor point.rm:cover|contain|stretch— resize method.rs:no_increase|standard|no_reduce— resize strategy.
The filter is applied to a model FieldFile (any storage, including S3) or to an absolute local path:
{% load m_thumbnails %}
<img src="{{ product.image|thumbnail:'s:300x200,rm:cover,resize,crop' }}" />
<img src="{{ image_path|thumbnail:'s:300x200,rm:cover,resize,crop' }}" />
DRF fields¤
For the Django REST Framework, the package provides two serializer fields:
MImageField¤
MImageField — a field that returns a URL to an optimized image. You can specify either size or job_chain:
from meringue.thumbnail.drf_fields import MImageField
class MySerializer(serializers.ModelSerializer):
photo = MImageField(size=(300, 200))
# or
photo = MImageField(job_chain=["s:300x200", "rm:cover", "rs:no_increase", "resize"])
When size is used, the field builds the following job chain:
The output format follows the source file extension.
MImageSetField¤
MImageSetField — a field that returns a set of images in different formats (original + WebP) and dimensions (1x, 2x, etc.) for use with the <picture> element. Under the hood, the image is processed once per dimension and then saved into multiple formats, which saves resources compared to running the full job chain separately for each format:
from meringue.thumbnail.drf_fields import MImageSetField
class MySerializer(serializers.ModelSerializer):
photo = MImageSetField(size=(300, 200), dimensions=(1, 2))
When size is used, MImageSetField builds a separate job chain for each dimension. The default base chain is ["rm:cover", "resize", "crop"], so the generated images match the requested size exactly. You can override the base chain or pass explicit chains:
class MySerializer(serializers.ModelSerializer):
photo = MImageSetField(
size=(300, 200),
dimensions=(1, 2),
base_job_chain=["rm:contain", "resize"],
)
# or
photo = MImageSetField(
job_chains={
1: ["s:300x200", "rm:cover", "resize", "crop"],
2: ["s:600x400", "rm:cover", "resize", "crop"],
},
)
If 1 is not included in dimensions, it is added automatically.
The response will contain an array of objects with srcset and type fields:
[
{"srcset": "/media/m/thumbnail/.../image.webp 1x, .../image.webp 2x", "type": "image/webp"},
{"srcset": "/media/m/thumbnail/.../image.jpg 1x, .../image.jpg 2x", "type": "image/jpeg"}
]
Storage¤
Thumbnails are saved to a separate storage configured via THUMBNAIL_DIR and THUMBNAIL_URL. The storage initialization can be customized through the THUMBNAIL_STORAGE_GETTER setting.
If the default storage is a django-storages S3 storage (S3Storage, S3Boto3Storage or a subclass), thumbnails are saved to the same bucket in <storage location>/m/thumbnail (the subdirectory is THUMBNAIL_DIR relative to MEDIA_ROOT). THUMBNAIL_URL is not used: thumbnail URLs are built by the storage itself (custom_domain, signed URLs, etc.).
STORAGES = {
"default": {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS": {"bucket_name": "my-bucket", "location": "media"},
},
# ...
}
# thumbnails: s3://my-bucket/media/m/thumbnail/...
Remote source storages¤
The thumbnail fields and the Thumbnailer read the source through FieldFile.storage, so they work with any storage, not only with local files. If django-storages with the S3 backend is installed, the S3 source is read with a single GET (S3Storage.open() makes HEAD + GET). django-storages is not required.
Several processes can write the same new thumbnail at the same time. S3 rejects parallel PUT of the same key with OperationAborted: such an error is logged as a warning and the usual thumbnail URL is returned.
Cache¤
Checking a thumbnail in a remote storage is a network request (HEAD for S3). Set THUMBNAIL_CACHE to a Django cache alias to keep the "thumbnail is saved" mark in the cache and to make every new thumbnail in one process only (the lock is taken with cache.add, the other processes return the URL without making the thumbnail). The cache is disabled by default.
CACHES = {
"default": {...},
"thumbnails": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
},
}
MERINGUE = {
"THUMBNAIL_CACHE": "thumbnails",
"THUMBNAIL_CACHE_TIMEOUT": 60 * 60 * 24 * 7, # the mark lifetime, `None` - forever
"THUMBNAIL_CACHE_LOCK_TIMEOUT": 60,
}
Warning
If thumbnails are deleted from the storage, clear the cache too: the URL of a marked thumbnail is returned without checking the storage until the mark expires.
While a thumbnail is being made by another process (the lock is taken, or S3 returned OperationAborted for a parallel PUT), the thumbnail file may not exist yet, and a browser could cache its URL as broken. So the thumbnail fields and the get_thumbnail shortcut return the dummy image instead (MImageSetField returns the dummy for the whole set if any of its thumbnails is not ready). The dummy has another URL, so the real thumbnail is shown on the next request. Turn it off where the URL is needed in advance:
MImageSetField(size=(300, 200), locked_dummy=False)
get_thumbnail(product.image, job_chain, locked_dummy=False)
When the Thumbnailer is used directly, check ThumbnailImage.locked.
Image optimization¤
The THUMBNAIL_IMAGE_OPTIMIZE_HANDLER setting can be used to optimize the generated image before it is saved to thumbnail storage. The handler receives the ThumbnailImage instance and an in-memory image file. It must return an in-memory image file.
MERINGUE = {
"THUMBNAIL_IMAGE_OPTIMIZE_HANDLER": "project.thumbnails.optimize_thumbnail",
}
from io import BytesIO
def optimize_thumbnail(thumbnail_image, image_file):
image_file.seek(0)
image_data = image_file.read()
optimized_data = optimize_image(image_data, thumbnail_image.out_format)
return BytesIO(optimized_data)
If the image should not be changed, return the original image_file.
By default, THUMBNAIL_IMAGE_OPTIMIZE_HANDLER uses the built-in optimize handler. Built-in optimizers are configured through THUMBNAIL_OPTIMIZERS. The default value is an empty dictionary, so no external optimizer is executed until it is explicitly configured.
Currently, the built-in handler supports oxipng for PNG files. The optimizer reads the generated thumbnail from memory and returns an optimized in-memory file before it is saved to storage:
You can override oxipng command-line options:
MERINGUE = {
"THUMBNAIL_OPTIMIZERS": {
"oxipng": {
"binary": "/usr/bin/oxipng",
"options": "-o 4 --strip all",
},
},
}
By default, oxipng is called with -o max --strip all --alpha. The options value replaces the default options and can also be a list of strings if you prefer to pass already-split command-line arguments. If binary is not set, or if the thumbnail is not PNG, the optimizer returns the original in-memory image unchanged.
Customization¤
The thumbnail system is highly customizable through settings:
- THUMBNAIL_GENERATOR_CLASS — custom thumbnailer class.
- THUMBNAIL_IMAGE_CLASS — custom thumbnail image class.
- THUMBNAIL_PROPERTIES — register custom properties.
- THUMBNAIL_ACTIONS — register custom actions.
- THUMBNAIL_DEFAULT_FORMAT — default output format (default: PNG).
- THUMBNAIL_DEFAULT_CROP_METHOD — default crop method.
- THUMBNAIL_DEFAULT_RESIZE_METHOD — default resize method (default: contain).
- THUMBNAIL_DEFAULT_RESIZE_STRATEGY — default resize strategy (default: standard).
- THUMBNAIL_DEFAULT_BG_COLOR — default background color.
- THUMBNAIL_SAVE_PARAMS_BY_FORMAT — format-specific save parameters (e.g., JPEG quality).
- THUMBNAIL_IMAGE_OPTIMIZE_HANDLER — in-memory optimization hook called before saving thumbnail to storage. It must return an in-memory image file.
- THUMBNAIL_OPTIMIZERS — built-in thumbnail optimizer settings.
- THUMBNAIL_DUMMYIMAGE_TEMPLATE — dummy image URL template in
DEBUGmode. - THUMBNAIL_DUMMYIMAGE_URL — dummy image URL when
DEBUGis off.