Images
Resize, crop, convert and measure images with the Image module and GraphicsMagick or ImageMagick.
On this page
The global Image object processes pictures: resizing, cropping, rotating, filters, watermarks and format conversion. It does not process the pixels itself. It builds a command line and runs GraphicsMagick or ImageMagick, so one of them must be installed on the server.
var image = Image.load(PATH.public('photos/beach.jpg'));
image.resizeCenter(400, 300);
image.quality(85);
image.save(PATH.public('photos/beach-small.jpg'), function(err) {
err && console.error(err);
});The module also measures the size of images (JPG, PNG, GIF, WebP, SVG, BMP, PSD) from a buffer, in pure JavaScript, without any external tool.
Requirements
Install one of the tools and make it available in the PATH of the process:
# macOS
brew install graphicsmagick
# Debian / Ubuntu
apt-get install graphicsmagickThe config key default_image_converter chooses the tool:
| Value | Tool | Command that runs |
|---|---|---|
gm (default) | GraphicsMagick | gm convert ... |
im | ImageMagick 6 | convert ... |
magick | ImageMagick 7 | magick ... |
// /config
default_image_converter : imThe second argument of Image.load() overrides the config for one image.
Loading an image
Image.load(source, [converter], [width], [height]) creates an Image object; Image.init() is the same function. The source is a file name, a readable stream or a Buffer:
var a = Image.load('/www/photos/cat.png'); // file
var b = Image.load(Fs.createReadStream(path)); // stream
var c = Image.load(buffer, 'magick'); // Buffer, ImageMagick 7For a file, the output format is its extension. For a stream or a buffer, the output format is jpg until you call image.output().
Building the operations
Each method adds a command-line option and returns the image, so calls can be chained. Nothing runs until save(), pipe() or stream():
Image.load(filename)
.resize(800)
.grayscale()
.quality(70)
.save(PATH.temp('gray.jpg'), function(err, saved) {
console.log(saved);
});The options do not run in the order of your calls. Each one has a fixed priority, and the framework sorts them before it builds the command:
| Priority | Methods |
|---|---|
| 1 | resize(), thumbnail(), scale(), filter(), limit() |
| 2 | background(), fill() |
| 3 | align() (-gravity) |
| 4 | crop(), extent(), first part of sepia() |
| 5 | quality(), second part of sepia() |
| 6 | watermark() |
| 8 | rotate() |
| 10 | blur(), flip(), flop(), grayscale(), normalize(), colors(), bitdepth(), command() (default) |
So rotate() always runs after crop(). Use command() with your own priority when you need another order.
Resizing
| Method | Result |
|---|---|
resize(w, h, [options]) | Fits the image into w x h and keeps the aspect ratio. Omit one side to compute it. |
resizeCenter(w, h, [color]) | Fills w x h and crops the overflow around the center. |
resizeAlign(w, h, [align], [color]) | Like resizeCenter(), but crops around align (top, bottom left...). |
miniature(w, h, [color], [filter]) | Fits the whole image into w x h and fills the rest with color. |
thumbnail(w, h, [options]) | Like resize(), with the -thumbnail option of the tool. |
scale(w, h, [options]) | Fast resize without a filter. |
options is a string appended to the size, with the meaning the tool gives it: ! ignores the aspect ratio, > only shrinks, < only enlarges, ^ fills the area, % reads the numbers as percentages:
image.resize(1200, 1200, '>'); // never upscale
image.resize(50, 50, '%'); // half the sizeOther operations
image.crop(200, 200, 10, 10); // w, h, x, y
image.rotate(90);
image.flip(); // vertical mirror
image.flop(); // horizontal mirror
image.blur(3);
image.grayscale();
image.sepia();
image.watermark(PATH.public('img/logo.png'), 10, 10);
image.background('#FFFFFF');
image.minify(); // removes EXIF and other profilesmake(fn) calls fn with the image, so you can group operations in a function and reuse it:
function avatar(image) {
image.resizeCenter(128, 128);
image.quality(80);
}
Image.load(filename).make(avatar).save(target);Quality
quality(percentage) sets the compression quality (-quality). Without an argument it uses 80. An image without quality() gets the default quality of GraphicsMagick or ImageMagick.
Output
save([filename], [callback]) runs the command and writes the result. Without a file name, it overwrites the source file. The format of the saved file comes from the extension of filename:
Image.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));pipe(stream, [type]) sends the result into a writable stream, and stream([type]) returns a readable stream. Here the format is type, or the value of output(), or the extension of the source file. Supported types are jpg, jpeg, png, gif, apng, heif, heic, webp and ico:
var file = Fs.createWriteStream(PATH.temp('out.png'));
Image.load(buffer).resize(100).pipe(file, 'png');When an image has no operation at all, save(), pipe() and stream() add minify() on their own.
Measuring images
Image.measure(type, buffer) reads the width and height from the first bytes of a file. type is an extension (.png or png) or a MIME type (image/png):
var size = Image.measure('.png', buffer);
// { width: 800, height: 600 }There are also functions for each format: Image.measureJPG(), Image.measurePNG(), Image.measureGIF(), Image.measureWEBP(), Image.measureSVG(), Image.measureBMP() and Image.measurePSD(). The framework uses them for uploaded files, which is why file.width and file.height are filled for images.
To measure a file on disk, use image.measure(callback) (JPG, PNG, GIF, WebP) or image.identify(callback), which asks the external tool and works for any format it knows.
Images in responses
In a route, controller.image() and res.image() load an image, let you set the operations and send the result with a cache. RESIZE() creates resized copies of static images on demand:
RESIZE('/img/small/*.jpg', function(image) {
image.resize(200, 200);
image.quality(80);
}, ['/img/']);Both are described in Static files. Images from a FileStorage are loaded with FILESTORAGE(name).image(), see File storage.
Output middleware
Image.middleware(type, fn) registers a function that returns a transform stream. Every output of that type passes through it, for example a PNG optimizer:
// a stream that receives all PNG output
Image.middleware('png', function() {
var Stream = require('stream');
return new Stream.PassThrough();
});The function must return a new stream on each call. With save(), the result is written to the file first, then passed through the stream and written again.