Thumbnail Files and Generators

Following is some basic documentation of the classes and methods related to thumbnail files and lower level generation.

class easy_thumbnails.files.ThumbnailFile(name, file=None, storage=None, thumbnail_options=None, *args, **kwargs)

A thumbnailed file.

This can be used just like a Django model instance’s property for a file field (i.e. an ImageFieldFile object).

property image

Get a PIL Image instance of this file.

The image is cached to avoid the file needing to be read again if the function is called again.

set_image_dimensions(thumbnail)

Set image dimensions from the cached dimensions of a Thumbnail model instance.

tag(alt='', use_size=None, **attrs)

Return a standard XHTML <img ... /> tag for this field.

Parameters:
  • alt – The alt="" text for the tag. Defaults to ''.

  • use_size – Whether to get the size of the thumbnail image for use in the tag attributes. If None (default), the size will only be used it if won’t result in a remote file retrieval.

All other keyword parameters are added as (properly escaped) extra attributes to the img tag.

class easy_thumbnails.files.Thumbnailer(file=None, name=None, source_storage=None, thumbnail_storage=None, remote_source=False, generate=True, *args, **kwargs)

A Django File for a source image, which generates thumbnails of it and keeps track of them in the database cache.

Use get_thumbnailer() to get an instance rather than creating one directly. get_thumbnail() returns an existing thumbnail or generates a new one, thumbnailer['alias'] does the same for a thumbnail alias.

Parameters:
  • file – An optional file-like object to read the source from. If not given, the source is opened from source_storage by name.

  • name – The name of the source, relative to source_storage. Thumbnail names are derived from it.

  • source_storage – The storage of the source. Defaults to Django’s default_storage.

  • thumbnail_storage – The storage thumbnails are saved to. Defaults to the storage named by THUMBNAIL_DEFAULT_STORAGE_ALIAS, or a ThumbnailFileSystemStorage if there is no such storage.

  • remote_source – True if file is not a file in source_storage. The database cache is then bypassed and every get_thumbnail() call generates a new thumbnail.

  • generate – Whether get_thumbnail() generates missing thumbnails, unless told otherwise by its generate argument.

Subclasses can set these attributes to override the settings of the same name in upper case (e.g. THUMBNAIL_NAMER for thumbnail_namer); None uses the setting:

  • source_generators, thumbnail_processors

  • thumbnail_basedir, thumbnail_subdir, thumbnail_prefix, thumbnail_extension, thumbnail_preserve_extensions, thumbnail_transparency_extension, thumbnail_check_cache_miss, thumbnail_namer

generate_thumbnail(thumbnail_options, silent_template_exception=False)

Return an unsaved ThumbnailFile containing a thumbnail image.

The thumbnail image is generated using the thumbnail_options dictionary.

get_existing_thumbnail(thumbnail_options)

Return a ThumbnailFile containing an existing thumbnail for a set of thumbnail options, or None if not found.

get_options(thumbnail_options, **kwargs)

Get the thumbnail options that includes the default options for this thumbnailer (and the project-wide default options).

The default quality of the output format is not added here, as it depends on whether the thumbnail is transparent (see resolve_quality()).

get_output_extension(thumbnail_options, transparent=False, default='jpg')

Return the file extension (without dot) of a thumbnail.

In order of precedence, this is the format thumbnail option, the source extension if it is in THUMBNAIL_PRESERVE_EXTENSIONS, the THUMBNAIL_TRANSPARENCY_EXTENSION if transparent is true, or the THUMBNAIL_EXTENSION.

Falls back to default ('jpg') if the chosen extension is empty, e.g. for a source without an extension and THUMBNAIL_PRESERVE_EXTENSIONS = True, or an empty THUMBNAIL_EXTENSION / THUMBNAIL_TRANSPARENCY_EXTENSION.

get_thumb_hash()

Return the thumb_hash stored for this source, or None if there is no Source record (yet).

get_thumbnail(thumbnail_options, save=True, generate=None, silent_template_exception=False)

Return a ThumbnailFile containing a thumbnail.

If a matching thumbnail already exists, it will simply be returned.

By default (unless the Thumbnailer was instanciated with generate=False), thumbnails that don’t exist are generated. Otherwise None is returned.

Force the generation behaviour by setting the generate param to either True or False as required.

The new thumbnail image is generated using the thumbnail_options dictionary. If the save argument is True (default), the generated thumbnail will be saved too.

get_thumbnail_name(thumbnail_options, transparent=False)

Return the storage-relative path for a thumbnail of this file.

The path has the form <basedir>/<source dir>/<subdir>/<prefix><namer output>.

Arguments:

thumbnail_options

Dict or ThumbnailOptions of thumbnail options (e.g. {'size': (100, 100), 'crop': True}). Normalised through get_options() and resolve_quality(), so the default quality of the output format is added if missing. The result is passed to the namer, and its prepared form is substituted for %(opts)s in basedir/subdir.

transparent

If true, the transparency extension is used for the file extension (and its default quality) instead of the regular one (unless the source extension is preserved). get_existing_thumbnail() calls this with both values to look up either variant.

Derived from the file itself:

  • self.name: its parent directory is mirrored in the result (with the source storage location prefix and leading slashes removed; remote storages without location are used as is), its file name is passed to the namer, and its lowercased extension decides whether the extension is preserved.

  • self.source_storage: only for its optional location.

Derived from settings (thumbnailer attributes thumbnail_*, defaulting to the THUMBNAIL_* settings):

  • THUMBNAIL_BASEDIR / THUMBNAIL_SUBDIR: directories before and after the source directory; %(opts)s is replaced by the prepared options joined with _.

  • THUMBNAIL_PREFIX: prepended to the file name.

  • THUMBNAIL_NAMER: dotted path or callable producing the file name, see easy_thumbnails.namers.

  • THUMBNAIL_EXTENSION, THUMBNAIL_TRANSPARENCY_EXTENSION: output extension (falls back to jpg if empty).

  • THUMBNAIL_PRESERVE_EXTENSIONS: True or a list of source extensions that keep their own extension.

Returns the path as a string; it is not checked for existence.

prefetch_aliases(aliases_names)

Like prefetch_thumbnails() for thumbnail aliases.

Arguments:

aliases_names

Iterable of alias names, looked up for the target of this thumbnailer like thumbnailer[alias] does.

Raises a KeyError if one of the aliases does not exist.

To prefetch the thumbnails of several files with a single query, use the prefetch_aliases() function.

prefetch_thumbnails(thumbnail_options_list)

Fetch the database records of several thumbnails with a single query.

The Thumbnail records are fetched together with their ThumbnailDimensions (and the Source), so the following calls to get_thumbnail() for the same options need no further queries for existing thumbnails, and their dimensions are available without reading the file (if THUMBNAIL_CACHE_DIMENSIONS is enabled).

Thumbnails that are missing are generated as usual.

The records are kept on this instance, so use it for the following calls. Prefetching again replaces the records fetched before.

Arguments:

thumbnail_options_list

Iterable of dicts or ThumbnailOptions, as for get_thumbnail(). Options of aliases must contain ALIAS, see prefetch_aliases().

resolve_quality(thumbnail_options, transparent=False)

Return thumbnail_options with the quality to save a thumbnail with.

A quality thumbnail option is kept, unless it is None. Otherwise a copy is returned, with quality set to the quality entry of THUMBNAIL_IMAGE_SAVE_OPTIONS for the output format (see get_output_extension(), which transparent is passed to). If that format has no default quality, the quality key is removed.

save_thumbnail(thumbnail)

Save a thumbnail to the thumbnail_storage.

Also triggers the thumbnail_created signal and caches the thumbnail values and dimensions for future lookups.

source_generators = None

A list of source generators to use. If None, will use the default generators defined in settings.

thumbnail_exists(thumbnail_name)

Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail.

If the source and thumbnail file storages are local, their file modification times are used. Otherwise the database cached modification times are used.

thumbnail_processors = None

A list of thumbnail processors. If None, will use the default processors defined in settings.

class easy_thumbnails.files.ThumbnailerFieldFile(*args, **kwargs)

A field file which provides some methods for generating (and returning) thumbnail images.

delete(*args, **kwargs)

Delete the image, along with any generated thumbnails.

delete_thumbnails(source_cache=None)

Delete any thumbnails generated from the source image.

Parameters:

source_cache – An optional argument only used for optimisation where the source cache instance is already known.

Returns:

The number of files deleted.

get_thumbnails(*args, **kwargs)

Return an iterator which returns ThumbnailFile instances.

save(name, content, *args, **kwargs)

Save the file, also saving a reference to the thumbnail cache Source model.

class easy_thumbnails.files.ThumbnailerImageFieldFile(*args, **kwargs)

A field file which provides some methods for generating (and returning) thumbnail images.

save(name, content, *args, **kwargs)

Save the image.

The image will be resized down using a ThumbnailField if resize_source (a dictionary of thumbnail options) is provided by the field.

easy_thumbnails.files.database_get_image_dimensions(file, close=False)

Returns the (width, height) of an image, given ThumbnailFile. Set ‘close’ to True to close the file at the end if it is initially in an open state.

Will attempt to get the dimensions from the file itself if they aren’t in the db.

easy_thumbnails.files.generate_all_aliases(fieldfile, include_global)

Generate all of a file’s aliases.

Parameters:
  • fieldfile – A FieldFile instance.

  • include_global – A boolean which determines whether to generate thumbnails for project-wide aliases in addition to field, model, and app specific aliases.

easy_thumbnails.files.get_thumbnailer(obj, relative_name=None)

Get a Thumbnailer for a source file.

The obj argument is usually either one of the following:

  • FieldFile instance (i.e. a model instance file/image field property).

  • A string, which will be used as the relative name (the source will be set to the default storage).

  • Storage instance - the relative_name argument must also be provided.

Or it could be:

  • A file-like instance - the relative_name argument must also be provided.

    In this case, the thumbnailer won’t use or create a cached reference to the thumbnail (i.e. a new thumbnail will be created for every Thumbnailer.get_thumbnail() call).

If obj is a Thumbnailer instance, it will just be returned. If it’s an object with an easy_thumbnails_thumbnailer then the attribute is simply returned under the assumption it is a Thumbnailer instance)

easy_thumbnails.files.prefetch_aliases(thumbnailers, aliases_names=None)

Fetch the thumbnails of several files with a single query.

Like Thumbnailer.prefetch_aliases(), which needs a query per file. Accessing the aliases of these thumbnailers afterwards needs no further queries for existing thumbnails. Thumbnails that are missing are generated as usual.

A query is needed per combination of source and thumbnail storage, so files of one field use a single query.

The thumbnails are kept on the given instances, so use these instances to access the aliases, and prefetching them again replaces the thumbnails fetched before.

Parameters:
  • thumbnailers – Iterable of Thumbnailer instances, including ThumbnailerFieldFile. Wrap the files of plain Django file fields with get_thumbnailer(). Empty files and remote sources are skipped.

  • aliases_names – Iterable of alias names (optional). By default all aliases of the target of each thumbnailer are fetched.

Raises:

KeyError – If one of the given aliases does not exist for the target of one of the thumbnailers.