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
ImageFieldFileobject).- 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
Thumbnailmodel 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
Filefor 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_storagebyname.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 aThumbnailFileSystemStorageif there is no such storage.remote_source –
Trueiffileis not a file insource_storage. The database cache is then bypassed and everyget_thumbnail()call generates a new thumbnail.generate – Whether
get_thumbnail()generates missing thumbnails, unless told otherwise by itsgenerateargument.
Subclasses can set these attributes to override the settings of the same name in upper case (e.g.
THUMBNAIL_NAMERforthumbnail_namer);Noneuses the setting: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
ThumbnailFilecontaining a thumbnail image.The thumbnail image is generated using the
thumbnail_optionsdictionary.
- get_existing_thumbnail(thumbnail_options)
Return a
ThumbnailFilecontaining an existing thumbnail for a set of thumbnail options, orNoneif 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
formatthumbnail option, the source extension if it is inTHUMBNAIL_PRESERVE_EXTENSIONS, theTHUMBNAIL_TRANSPARENCY_EXTENSIONiftransparentis true, or theTHUMBNAIL_EXTENSION.Falls back to
default('jpg') if the chosen extension is empty, e.g. for a source without an extension andTHUMBNAIL_PRESERVE_EXTENSIONS = True, or an emptyTHUMBNAIL_EXTENSION/THUMBNAIL_TRANSPARENCY_EXTENSION.
- get_thumb_hash()
Return the
thumb_hashstored for this source, orNoneif there is noSourcerecord (yet).
- get_thumbnail(thumbnail_options, save=True, generate=None, silent_template_exception=False)
Return a
ThumbnailFilecontaining a thumbnail.If a matching thumbnail already exists, it will simply be returned.
By default (unless the
Thumbnailerwas instanciated withgenerate=False), thumbnails that don’t exist are generated. OtherwiseNoneis returned.Force the generation behaviour by setting the
generateparam to eitherTrueorFalseas required.The new thumbnail image is generated using the
thumbnail_optionsdictionary. If thesaveargument isTrue(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_optionsDict or
ThumbnailOptionsof thumbnail options (e.g.{'size': (100, 100), 'crop': True}). Normalised throughget_options()andresolve_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)sin basedir/subdir.transparentIf 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 storagelocationprefix and leading slashes removed; remote storages withoutlocationare 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 optionallocation.
Derived from settings (thumbnailer attributes
thumbnail_*, defaulting to theTHUMBNAIL_*settings):THUMBNAIL_BASEDIR/THUMBNAIL_SUBDIR: directories before and after the source directory;%(opts)sis replaced by the prepared options joined with_.THUMBNAIL_PREFIX: prepended to the file name.THUMBNAIL_NAMER: dotted path or callable producing the file name, seeeasy_thumbnails.namers.THUMBNAIL_EXTENSION,THUMBNAIL_TRANSPARENCY_EXTENSION: output extension (falls back tojpgif empty).THUMBNAIL_PRESERVE_EXTENSIONS:Trueor 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_namesIterable of alias names, looked up for the target of this thumbnailer like
thumbnailer[alias]does.
Raises a
KeyErrorif 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
Thumbnailrecords are fetched together with theirThumbnailDimensions(and theSource), so the following calls toget_thumbnail()for the same options need no further queries for existing thumbnails, and their dimensions are available without reading the file (ifTHUMBNAIL_CACHE_DIMENSIONSis 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_listIterable of dicts or
ThumbnailOptions, as forget_thumbnail(). Options of aliases must containALIAS, seeprefetch_aliases().
- resolve_quality(thumbnail_options, transparent=False)
Return
thumbnail_optionswith the quality to save a thumbnail with.A
qualitythumbnail option is kept, unless it isNone. Otherwise a copy is returned, withqualityset to thequalityentry ofTHUMBNAIL_IMAGE_SAVE_OPTIONSfor the output format (seeget_output_extension(), whichtransparentis passed to). If that format has no default quality, thequalitykey is removed.
- save_thumbnail(thumbnail)
Save a thumbnail to the thumbnail_storage.
Also triggers the
thumbnail_createdsignal 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
ThumbnailFieldifresize_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
FieldFileinstance.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
Thumbnailerfor a source file.The
objargument is usually either one of the following:FieldFileinstance (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).
Storageinstance - therelative_nameargument must also be provided.
Or it could be:
A file-like instance - the
relative_nameargument 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
objis aThumbnailerinstance, it will just be returned. If it’s an object with aneasy_thumbnails_thumbnailerthen 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
Thumbnailerinstances, includingThumbnailerFieldFile. Wrap the files of plain Django file fields withget_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.