Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Images

An image is a file with a little more: its width and height are known, it is often shown at several sizes (a thumbnail, a cover), and it often has a row of its own (a title, credits) linked to the objects it illustrates. The images feature covers these three needs:

  • its size, read on upload: the behaviour Image (or Dimensions) reads the width and height of each image sent and writes them in their columns;
  • galleries and logos: the behaviours Images and Logo give a resource the actions that add, change and remove its images;
  • resized copies: Sizes, on the storage, answers …/logo--cover_256.webp from …/logo.png, made the first time it is asked for.

Coming from Django: the first is ImageField with width_field and height_field. The resized copies are what easy-thumbnails or sorl-thumbnail do, except that the size is asked for in the URL rather than in a template tag.

A behaviour is a piece of a resource that several resources share (columns, what a write sets, actions). It is explained in Behaviours.

Setting it up

Turn on the Cargo feature images. It brings in storage and behaviours, the image crate and libwebp:

# Cargo.toml of the application
rind = { version = "…", features = ["images"] }

The images are stored by the storage plugin, so the application needs one (Files). For resized copies, give it Sizes:

#![allow(unused)]
fn main() {
// sample/src/lib.rs
        .with(
            rind::storage::Storage::from_env()
                .expect("RIND_STORAGE")
                .sizes(rind::images::Sizes::new()),
        )
}

There is no environment variable of its own.

Reading an image’s size on upload

The simplest case is an image column on a model, with its width and height beside it. The field group rind::images::image gives the three columns (image, image_width, image_height), and the behaviour Image fills the last two:

#![allow(unused)]
fn main() {
use rind::images::Image;

#[rind::with_fields(rind::images::image)]   // image, image_width, image_height
#[derive(Debug, Clone, Model)]
#[model(table = "shop_product")]
pub struct Product { /* … */ }

#[derive(Resource)]
#[resource(model = Product, /* … */ behaviours(Image))]
pub struct ProductResource;
}

On every write that sends the file, Image reads the width and height from it and sets them. A write that removes the file empties them. This is what Django’s ImageField does with width_field and height_field.

A file that is not a JPEG, PNG, GIF or WebP image is refused with a 400, and Django’s message:

{"image": ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}

Some details:

  • The type is read from the file’s content, not from its name. A JPEG named .png is read as a JPEG.
  • The size is the one stored in the file, before any EXIF orientation is applied. This is what PIL reads, so it matches what Django recorded.
  • The file is read from the request, not again from the storage. When a client sends the key of a file already stored (instead of a file), it is read from the storage; a key that is not there is refused with “This file is not in the storage.”

Columns of other names

When the columns have other names, or when you also want the image’s type, name them with a Picture and use Dimensions<P>. The railway’s images do this:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/images.rs
use rind::images::{Dimensions, Picture};

/// The columns `Dimensions` reads and writes.
pub struct ImageFile;

impl Picture for ImageFile {
    const FILE: &'static str = "file";
    const WIDTH: &'static str = "width";
    const HEIGHT: &'static str = "height";
    const TYPE: &'static str = "mimetype";   // optional: `image/png`
}

#[derive(Resource)]
#[resource(model = Image, path = "images", out = ImageOut, input = ImageIn, delete,
           behaviours(Dimensions<ImageFile>))]
// …
pub struct ImageResource;
}

TYPE is optional; leave it out when the model does not keep the type. (Image is simply Dimensions on the columns of the field group.)

rind::images::probe(&bytes) gives the width, height and type of an image, or None, for code of your own.

Often an image is more than a column. It has a row of its own, with a title, credits, an order, and objects point to it. In the railway, the images are rows of network_image. A line has a logo (a foreign key to an image) and a gallery (a many-to-many to images):

#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[m2m(name = images, model = Image, through = "network_line_images", from = "line_id", to = "image_id")]
pub struct Line {
    // …
    #[fk(Image, on_delete = set_null, name = logo)]
    pub logo_id: Option<i64>,
}
}

The images are a resource of their own (ImageResource, above). Two behaviours then give the lines’ resource the actions that change its images. Each is configured by a small type that says which tables and columns to use:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
use rind::images::{Gallery, Images, Logo, LogoField};

/// A line's gallery: `network_line_images`.
pub struct LineImages;

impl Gallery for LineImages {
    type Images = ImageResource;              // what makes and deletes an image
    type Changes = ImageChanges;              // what update_image reads
    const LINK: &'static str = "network_line_images";
    const FROM: &'static str = "line_id";
    const TO: &'static str = "image_id";
}

/// A line's logo: `logo_id`.
pub struct LineLogo;

impl LogoField for LineLogo {
    type Images = ImageResource;
    type Changes = ImageChanges;
    const COLUMN: &'static str = "logo_id";
}

#[derive(Resource)]
#[resource(
    model = Line,
    path = "lines",
    out = LineOut,
    input = LineIn,
    delete,
    behaviours(Flags, Images<LineImages>, Logo<LineLogo>)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, get_flags, get_image, get_logo))]
pub struct LineResource;
}

The resource now has these actions on each line (/lines/{id}/…):

ActionMethodBodyWhat it does
add_imagePOSTthe images’ input: a form with the file, or JSONcreates an image and adds it to the gallery; 201
update_imagePATCHid, and what changes (Changes)changes an image of the gallery
remove_imagePOSTpktakes it out of the gallery and deletes it
get_imageGET?image=<id>answers the image
set_logoPOSTthe images’ inputcreates an image and makes it the logo; 201
update_logoPATCHwhat changes (Changes)changes the logo
unset_logoPOSTthe line has no logo any more; the image is kept
get_logoGETanswers the logo

They answer with the line, except the get_ actions, which answer with the image. An image that is not in the gallery (or a line without a logo) is a 404, {"detail": "Image not found"}. The rules name the actions as they name any other: above, anyone may read the images and only the staff may change them.

Sending a logo in a form:

POST /lines/7/set_logo
Content-Type: multipart/form-data; boundary=…

title=Le logo, file=logo.png (image/png, 400 × 200)
{"id": 7, "code": "IMG", "logo": 12, "images": [], "updated": "…", …}
GET /lines/7/get_logo
{"id": 12, "file": {"url": "/media/images/2c/03a1…/logo.png", "name": "logo.png", "size": …},
 "width": 400, "height": 200, "mimetype": "image/png", "title": "Le logo", "credits": ""}

Coming from Django: a real Django application had these as view mixins (ManageImagesAPIViewMixin, ManageLogoAPIViewMixin). The actions keep their names, methods and answers, so a front end written for it works unchanged.

How an image is created and changed

An image is created and changed by its own resource (Images), in the action’s transaction. So its input says what a client sends (the file, a title), its behaviours run (its Dimensions reads the size), and its hooks run too. Its own rules are not asked: who may change the line may change its images.

Changes is the input that update_image and update_logo read. It usually has fewer fields than the input that creates an image: the railway’s ImageChanges changes a title and credits, not the file. Or it can be the images’ input itself. A field it does not have is ignored.

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/images.rs
#[derive(Debug, Input)]
#[input(model = Image)]
pub struct ImageChanges {
    #[input(max_length = 200, allow_blank)]
    pub title: Option<String>,
    #[input(max_length = 500, allow_blank)]
    pub credits: Option<String>,
}
}

Removing an image

remove_image deletes the image. What happens to the rows that still point to it is what their foreign keys say. In the railway, a line whose logo it was has no logo any more (on_delete = set_null). With keys that do nothing (as Django creates them), the deletion is refused with a 400.

unset_logo only clears the line’s key: the image is kept. set_logo on a line that already has a logo makes the new image the logo, and keeps the old image too.

Going further: which hooks run

  • An image change (update_image, update_logo): the model’s behaviours, the images’ resource’s behaviours (its Dimensions) and the model’s hooks run. The images’ resource’s own updating and saved hooks do not run, because they take the images’ input, not Changes.
  • The logo is a write of the line: set_logo and unset_logo change the line’s key through the model’s behaviours, as Django’s item.save() would (so Tracking moves updated), and the model’s hooks are told. The line resource’s own hooks do not run, because they take its input.

Resized copies

A page shows an image at several sizes: a 48-pixel thumbnail in a list, a 512-pixel cover on the detail page. Sending the original each time is slow, and making every size on upload means guessing them in advance. With Sizes, the storage makes a copy the first time it is asked for, by its name:

#![allow(unused)]
fn main() {
rind::storage::Storage::from_env()?
    .sizes(rind::images::Sizes::new())
}

The storage then answers, at its address (/media), resized copies of its images. The name of a copy is the image’s name, then -- and an operation, then the type wanted:

/media/images/2c/03a1…/logo.png                        the image
/media/images/2c/03a1…/logo--cover_256.webp            cut to fill 256 × 256
/media/images/2c/03a1…/logo--contain_354_236_white.jpg fitted in 354 × 236, on white
/media/images/2c/03a1…/logo--resize_767.webp           767 wide

There are three operations:

  • resize_<w>[_<h>] scales the image to fit in w × h. With one side (resize_767), that side is exact and the other follows.
  • contain_<w>[_<h>[_<color>]] fits the image, centred on a w × h background: transparent by default, or white, black, ff8800….
  • cover_<w>[_<h>] fills w × h; what overflows is cut, centred.

Several operations can follow each other: logo--cover_512--resize_256.webp. The type is webp, png or jpg, whatever the original’s. A copy is turned the way the camera said it was held (EXIF).

A front end builds a copy’s address from the file’s url: drop the type, add the operation and the new type. Angular’s image loader, for instance, does this with a small function. These names are those of the image server a real Django application used: a front end written for it works unchanged.

A name that is not a copy, a size that is not allowed, or an operation rind does not know is a 404.

Where the copies are kept

A copy is made the first time it is asked for, on a thread of its own, and then stored: below _sizes/ in the same storage, or in another storage with Sizes::new().copies(storage) (when the images’ storage is read-only, for example). A key’s content never changes, so a copy’s does not either: it is sent with a cache of a year. storage-orphans leaves the copies out.

Limits

Without limits, anyone could fill the storage with every possible size. So a side is at most Sizes::max (2,048 pixels by default), and Sizes::only(&[48, 256, 512]) allows only these sides.

A file that claims a picture larger than 20,000 pixels a side, or that needs more than 512 MiB to decode, is not read. WebP and JPEG copies are written at quality 70 (.quality(q) changes it).

Serving the copies

The copies are answered by the application, on the path the storage serves (.serve("/media"), or the default for a folder without RIND_MEDIA_URL).

  • Behind a CDN that resizes images itself, or an image server, give the storage its public address (RIND_MEDIA_URL) and leave sizes out.
  • A private S3 bucket gives signed addresses, which a client cannot change to ask for a copy. To have copies of such a bucket’s images, serve the bucket through the application (.serve("/media")).

Reference

Behaviours

BehaviourConfigured byColumnsWhat it does
Image(the field group rind::images::image)image, image_width, image_heightreads the size on upload
Dimensions<P>Picture: FILE, WIDTH, HEIGHT, TYPE (optional)those namedreads the size, and the type, on upload
Images<G>Gallery: Images, Changes, LINK, FROM, TO(a link table)add_image, update_image, remove_image, get_image
Logo<L>LogoField: Images, Changes, COLUMNthe foreign keyset_logo, update_logo, unset_logo, get_logo

update_image reads the image’s id from id (or pk), and remove_image from pk (or id).

Copy names

OperationAliases
resize_<w>[_<h>]size, sz, s, scale, scscaled to fit in w × h; with one side (the other missing or 0), that side exact, the other following
contain_<w>[_<h>[_<color>]]ctfitted, centred on a w × h background; h is w by default, w is 128 by default
cover_<w>[_<h>]cofills w × h, the overflow cut, centred; h is w by default

Colours: transparent (or tr), white, black, red, green, blue, gray (or grey), or hexadecimal digits (f80, ff8800, ff880080 with transparency). Types: webp, png, jpg or jpeg.

Sizes

MethodDefault
Sizes::new()copies on request
.max(pixels)2,048the largest side
.only(&[sides])anyonly these sides
.quality(q)70WebP and JPEG quality, 0 to 100
.copies(storage)_sizes/ in the images’ storagewhere the copies are kept

Tested against a real application

These measures come from a real Django application with 337,518 images (72 GB, nearly all PNG). rind read every image that was not a PNG, and one PNG in twenty: 24,250 files, 11 GB, in 20 seconds.

  • Their size: of the 24,049 files rind read, Django had recorded a width and height for 7,186, and none was different. The other 16,863 had none in the database. 4 files were not read: two BMPs, a Photoshop file named .jpg (which PIL reads), and an HTML page.
  • Their type, read from the content: 713 images recorded as image/png were JPEGs.
  • The copies its front end asks for (contain_512, contain_256 and contain_48 in WebP, contain_354_236_white, resize_767, resize_354 in the image’s own type), for 40 PNGs and 40 JPEGs: all 480 had the size asked for. Each was made in 0.2 to 0.4 s, mostly to decode the original, then answered in 0.1 ms once stored.