Skip to the page
Kiln / Images

Start here01

The language02

Programs and the world03

Kiln04

04 Kiln / 06

Images

Kinds of images and their sizes, files that forms send, and keeping them, each size made once.

An image's record says what sizes it comes in: key, the stored file's name, and a field for each size, holding where that size is served. Its own keep names the sizes, and Images.keep stores an upload and makes them:

hem
# images/photo.hem
import "@kiln"

export record Photo
  key: String
  thumb: String
  large: String

  static def keep(upload: Upload): Photo!
    return try Images.keep[Photo](upload, sizes: [
      new Size(name: "thumb", width: 480, height: 600, cropped: true),
      new Size(name: "large", width: 1200, height: 1500),
    ])
  end
end
  • Each Size is a name, a field of the record's, and the box it fits in. cropped fills the box exactly, cutting away what's outside it (where the eye goes first); without it, the image fits inside the box, as it is.
  • An image is only ever made smaller, never larger.
  • A record whose fields aren't key and one String for each size is a failure (kind invalid) when an image is kept.

A form that sends a file says so, and its handler finds the file among the request's files:

template
form
  method: "post"
  action: "/photos"
  enctype: "multipart/form-data"

  input
    type: "file"
    name: "photo"
    accept: "image/*"
  end
end
hem
static def add(request: Request, staff: Staff, id: Int): Response!
  const sent = request.files.find do (file)
    return file.field == "photo"
  end

  if sent == nil
    return failure("choose a photo", kind: ErrorKind.invalid)
  end

  const photo = try Photo.keep(sent)
  const product = try products.find(id)

  try products.update(product.with(photo: photo))
  return Response.redirect("/office/products/#{id}", status: Redirect.see_other)
end
template
img
  src: product.photo.thumb
  alt: product.name
end
  • An Upload (the http package's) has the file's name, its content_type as the browser gave it, its size in bytes, and the path it's held at while its request is answered.
  • Images.keep keeps the file in storage/, in a folder named by the hash of its bytes, with each size as WebP; the same file kept twice is kept once. Something that isn't an image fails with kind invalid; a file over 20 MB too.
  • Images.file(path) gives a file on disk as an Upload, for a script that keeps images it has (a seeder, say).
  • Any other file a form sends, a PDF say, is kept as it came with File.move(sent.path, to: "storage/#{sent.name}"), before its request is answered (see Bytes in the language's guide).
  • The app serves what's kept: Route.files("/storage", from: "storage").
  • Sizes are made by libvips's vips command, which must be installed; only a program that keeps images needs it.