Images
Resize, crop, convert, watermark and measure images with GraphicsMagick or ImageMagick.
On this page
Total.js processes images with an external program: GraphicsMagick (gm, the default) or ImageMagick (convert or magick). The framework does not change pixels itself. An Image object collects the operations you call and builds one command line from them. The command runs when you call save(), pipe() or writer().
Install the program on the server first, for example brew install graphicsmagick or apt-get install graphicsmagick. The exact reference of every method is in Images.
Load an image
The Image global is the image module. Image.load() (also F.image()) creates an image object from a file name, a Buffer or a readable stream:
var img = Image.load(PATH.public('photos/beach.jpg'));
img.resize(800, 600);
img.quality(85);
img.save(PATH.public('photos/beach-800.jpg'), function(err) {
if (err)
console.error(err);
});// From a Buffer or a stream
var img = Image.load(buffer);
var img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));The type of the image (img.type) comes from the extension of the file name. For a Buffer or a stream it is jpg; change it with img.output('png').
The methods return the image object, so you can chain them:
Image.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);Other modules give you image objects too: an uploaded file has file.image() (see Controller), a file storage has fs.image(id) (see File storage), and $.image(opt) processes an image and sends it as the response.
Choose the program
The configuration key $imageconverter sets the program for all images: gm (GraphicsMagick, the default), im (ImageMagick 6, the convert command) or magick (ImageMagick 7). See Configuration.
$imageconverter : imThe second argument of Image.load() changes it for one image:
var img = Image.load(filename, 'magick');Resize and crop
| Method | What it does |
|---|---|
resize(w, h, [options]) | Resizes into the box wxh and keeps the aspect ratio. One side can be empty. options is appended to the size ('!', '^', '>', '<'), and a size can be a percentage like '50%' |
thumbnail(w, h, [options]) | Like resize(), but also removes the profiles, for small previews |
scale(w, h, [options]) | A fast resize without filtering |
crop(w, h, [x], [y]) | Cuts a wxh area at the offset x, y |
extent(w, h, [x], [y]) | Sets the canvas to wxh; new area is filled with the background color |
resizecenter(w, h, [color]) | Fills the wxh box completely and crops the centre |
resizealign(w, h, [align], [color]) | Like resizecenter() but crops at the given side |
miniature(w, h, [color]) | Fits the image into wxh and fills the rest with the color (white) |
// A square avatar, the face is usually at the top
Image.load(filename).resizealign(200, 200, 'top').quality(90).save(target);
// The whole photo inside 300x300, with a white border
Image.load(filename).miniature(300, 300).save(target);align(type) (alias gravity()) sets the gravity used by crop() and extent(). It accepts 'top left', 'top', 'center', 'bottom right'… and any GraphicsMagick gravity name such as 'NorthEast'.
Adjust and transform
var img = Image.load(filename);
img.rotate(90); // degrees
img.flip(); // vertical mirror
img.flop(); // horizontal mirror
img.blur(3);
img.grayscale();
img.sepia();
img.normalize();
img.colors(16); // reduce the palette
img.bitdepth(8);
img.quality(75); // compression level, 80 when empty
img.save(target);background(color) sets the color for new areas (used by extent(), rotate() and the resize helpers), fill(color) sets the fill color, filter(name) the resize filter ('Lanczos', 'Hamming'…; it applies to every resize of the image, in any order of the calls) and define(value) passes a coder option such as 'jpeg:extent=200kb'.
Watermarks
watermark(filename, x, y, w, h) draws another image over the picture. x and y are measured from the top left corner, and a width and height of 0 keep the size of the watermark:
Image.load(filename)
.resize(1200)
.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)
.save(target);Any other option
command(key, [value], [priority], [escape]) adds any option of the program. Pass true as the third argument to put the value in quotes:
img.command('-sharpen', '0x1');
img.command('-strip');
img.command('-label', 'Holiday 2024', true);The operations are sorted by priority before the command is built (the resize filter of filter() first, then sizes, gravity, crop, quality, rotation and effects such as blur()). img.cmd(from, to) returns the command line without running it, which helps when you debug:
var img = Image.load('photo.jpg').resize(200, 100);
console.log(img.cmd('photo.jpg', 'small.jpg'));
// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'img.clear() removes all operations, and img.make(fn) calls fn(img) so you can keep a set of operations in a function.
Save, pipe and stream
save([filename], [callback]) writes the result to a file. The format comes from the extension of the target file. Without a file name it overwrites the source file. The callback gets (err, success):
Image.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {
// success === true
});pipe(stream, [type], [options]) sends the result to a writable stream, for example the HTTP response. type is the output format (jpg, png, gif, webp, heic…, otherwise img.type); options goes to stream.pipe():
function preview($) {
var img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));
img.resize(300, 300);
$.res.writeHead(200, { 'content-type': 'image/webp' });
img.pipe($.res, 'webp');
}writer([type]) starts the conversion and returns the readable output stream:
var stream = Image.load(buffer).resize(100, 100).writer('png');
stream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));When an image has no operations, save(), pipe() and writer() add minify(), which removes the profiles and metadata.
For HTTP responses with a cache, $.image() of the controller is shorter (see Controller).
Measure an image
The module reads the size from the header of the file, without the external program:
var size = Image.measure('png', buffer);
// { width: 800, height: 600 }
Image.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {
console.log(size.width, size.height);
});Image.measure(type, buffer) understands JPEG, PNG, GIF, WebP, SVG, BMP and PSD (as an extension or a MIME type) and returns undefined for other types. For a JPEG whose size marker is not in the buffer (a damaged file or too little data), it returns null. The method img.measure(callback) reads files with the extensions .jpg, .png, .gif and .webp. Uploaded files are measured automatically, see file.width and file.height in Controller.
Post-processing middleware
Image.middleware(type, fn) registers a function that returns a transform stream. Every result of that type passes through it (for save() only when it has a callback), for example to run an optimizer:
Image.middleware('png', function() {
return new MyPngOptimizer(); // a Transform stream
});The type is img.type: the extension of the source, or the value of output(). For pipe() and writer() it is the output format.