Images
The global Image object, the methods of an image, and the image config keys.
On this page
The global Image object loads and measures images, and an image object builds the commands for GraphicsMagick or ImageMagick. The guide Images explains how to use them with examples; this page is the exact reference.
API
class
new Image.Image(source, [converter], [width], [height])
An image with a list of operations for GraphicsMagick or ImageMagick.
new Image.Image(source, [converter], [width], [height])Returns Image
Create it with Image.load(); the constructor is Image.Image (alias Image.Picture). Properties:
filename— the source file, ornullfor a stream or a bufferoutputType— the output format; the extension of the file,jpgfor streams and buffers, or the value ofoutput()width,height— the values passed toImage.load()(they are not measured)builder— the list of operations added so far
All operation methods return the image. Add your own methods with F.prototypes(), whose argument has the Image prototype.
F.prototypes(function(proto) {
proto.Image.avatar = function() {
return this.resizeCenter(128, 128).quality(80);
};
});
Image.load(filename).avatar().save(target);
method
Image.load(source, [converter], [width], [height])
Creates an image object from a file, a stream or a buffer.
Image.load(source, [converter], [width], [height])| Parameter | Type | Description |
|---|---|---|
source |
String|Stream|Buffer |
A file name, a readable stream or a buffer with the image. |
converter? |
String |
gm (GraphicsMagick), im (ImageMagick 6, convert) or magick (ImageMagick 7). Default: CONF.default_image_converter |
width? |
Number |
Stored in image.width; not used by the operations. |
height? |
Number |
Stored in image.height; not used by the operations. |
Returns Image A new image.
Nothing is read or run yet. For a file name, the output format is the file extension; for a stream or a buffer, it is jpg until you call output().
Image.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));
var image = Image.load(buffer, 'magick');
image.output('png');
image.resize(64, 64);
image.pipe(res);
method
Image.init(source, [converter], [width], [height])
The same function as Image.load().
Image.init(source, [converter], [width], [height])| Parameter | Type | Description |
|---|---|---|
source |
String|Stream|Buffer |
A file name, a readable stream or a buffer with the image. |
converter? |
String |
gm (GraphicsMagick), im (ImageMagick 6, convert) or magick (ImageMagick 7). Default: CONF.default_image_converter |
width? |
Number |
Stored in image.width; not used by the operations. |
height? |
Number |
Stored in image.height; not used by the operations. |
Returns Image A new image.
Creates an image object; the arguments and the result are the same as in Image.load().
var image = Image.init(filename);
image.grayscale().save(filename);
method
Image.measure(type, buffer)
Returns the width and height of an image from its first bytes.
Image.measure(type, buffer)| Parameter | Type | Description |
|---|---|---|
type |
String |
Extension or MIME type. |
buffer |
Buffer |
The beginning of the file (the whole file for SVG; for JPEG, enough bytes to reach the frame header). |
Returns Object { width, height }, or undefined/null when it cannot be read.
Calls the measuring function for the type. type is an extension with or without the dot, or a MIME type: jpg, jpeg, png, gif, svg, webp, bmp, psd (image/jpeg, image/png, image/gif, image/svg+xml, image/webp, image/bmp, image/vnd.adobe.photoshop). For other types it returns undefined. No external tool is needed.
var size = Image.measure('image/png', buffer);
if (size && size.width > 2000)
console.log('Too large');
method
Image.measureJPG(buffer)
Returns the width and height of a JPG image.
Image.measureJPG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }
Walks the JPEG markers to the first frame header (SOF). Returns null when the buffer is not a JPEG or the header is not in the buffer.
var size = Image.measureJPG(Fs.readFileSync(filename));
console.log(size.width, size.height);
method
Image.measurePNG(buffer)
Returns the width and height of a PNG image.
Image.measurePNG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }
Reads the size from the IHDR chunk; 24 bytes are enough.
var size = Image.measurePNG(Fs.readFileSync(filename));
console.log(size.width, size.height);
method
Image.measureGIF(buffer)
Returns the width and height of a GIF image.
Image.measureGIF(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }
Reads the logical screen size; 10 bytes are enough.
var size = Image.measureGIF(Fs.readFileSync(filename));
console.log(size.width, size.height);
method
Image.measureBMP(buffer)
Returns the width and height of a BMP image.
Image.measureBMP(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }
Reads the size from the BMP header. The height is always positive (top-down bitmaps have a negative height in the file).
var size = Image.measureBMP(Fs.readFileSync(filename));
console.log(size.width, size.height);
method
Image.measurePSD(buffer)
Returns the width and height of a PSD image.
Image.measurePSD(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }
Reads the size from the Photoshop header.
var size = Image.measurePSD(Fs.readFileSync(filename));
console.log(size.width, size.height);
method
Image.measureWEBP(buffer)
Returns the width and height of a lossy or lossless WebP image.
Image.measureWEBP(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }, or undefined.
Supports lossy (VP8 ) and lossless (VP8L) WebP images. It needs the first 30 bytes. It returns undefined for an unknown header.
var size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));
method
Image.measureSVG(buffer)
Returns the width and height of an SVG image.
Image.measureSVG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The SVG file. |
Returns Object { width, height }, or undefined.
Searches the text for the first width="N" and height="N" attributes with whole numbers. Units and viewBox are not read. It returns undefined when there are no such attributes, and 0 for a missing side.
var size = Image.measureSVG(Buffer.from('<svg width="120" height="40"></svg>'));
// { width: 120, height: 40 }
method
Image.middleware(type, fn)
Registers a stream that processes every output of a type.
Image.middleware(type, fn)| Parameter | Type | Description |
|---|---|---|
type |
String |
Output type, for example png or .png. |
fn |
Function |
Returns a new transform stream. |
Returns undefined
fn() must return a new transform (duplex) stream on each call. The output of pipe() and stream() for that type passes through it. After save(), the saved file is read, passed through the stream and written again before the callback. Only one middleware per type; a new one replaces the old one. The type is matched with the output type (png, jpg...), so jpeg and jpg are different.
var Stream = require('stream');
Image.middleware('png', function() {
return new Stream.PassThrough();
});
method
image.resize([w], [h], [options])
Resizes the image and keeps its aspect ratio.
image.resize([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number |
Width in pixels. Use 0 or null to compute it from the height. |
h? |
Number |
Height in pixels. Omit it to compute it from the width. |
options? |
String |
A suffix of the size: ! (ignore aspect ratio), > (only shrink), < (only enlarge), ^ (fill), % (percent). |
Returns Image The same image, for chaining.
Adds -resize WxH. With only the width, the height is computed, and the other way round. The image fits into the box; add options to change it.
image.resize(800); // width 800
image.resize(null, 600); // height 600
image.resize(800, 600, '!'); // exactly 800x600
image.resize(1920, 1920, '>'); // only shrink
method
image.resizeCenter(w, h, [color])
Fills the size and crops the rest around the center.
image.resizeCenter(w, h, [color])| Parameter | Type | Description |
|---|---|---|
w |
Number |
Width in pixels. |
h |
Number |
Height in pixels. |
color? |
String |
Background color, for example white or #F0F0F0. Default: 'white' |
Returns Image The same image, for chaining.
Resizes with ^ so the image covers w x h, then crops the center part. The result has exactly the given size. resize_center() is an alias.
Image.load(filename).resizeCenter(200, 200).save(target);
method
image.resizeAlign(w, h, [align], [color])
Fills the size and crops the rest around a side or a corner.
image.resizeAlign(w, h, [align], [color])| Parameter | Type | Description |
|---|---|---|
w |
Number |
Width in pixels. |
h |
Number |
Height in pixels. |
align? |
String |
Which part to keep. Default: 'center' |
color? |
String |
Background color, for example white or #F0F0F0. Default: 'white' |
Returns Image The same image, for chaining.
Like resizeCenter(), but keeps the part given by align (the values of align(), for example top, bottom, top left). resize_align() is an alias.
image.resizeAlign(1200, 400, 'top');
method
image.miniature(w, h, [color], [filter])
Fits the whole image into the size and fills the empty area.
image.miniature(w, h, [color], [filter])| Parameter | Type | Description |
|---|---|---|
w |
Number |
Width in pixels. |
h |
Number |
Height in pixels. |
color? |
String |
Background color, for example white or #F0F0F0. Default: 'white' |
filter? |
String |
Resize filter. Default: 'Hamming' |
Returns Image The same image, for chaining.
Runs thumbnail(w, h) with the filter, centers the result and extends it to exactly w x h with the background color. Nothing is cut off.
image.miniature(300, 300);
image.miniature(300, 300, '#000000', 'Lanczos');
method
image.thumbnail([w], [h], [options])
Resizes the image with the -thumbnail option.
image.thumbnail([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number |
Width in pixels. Use 0 or null to compute it from the height. |
h? |
Number |
Height in pixels. Omit it to compute it from the width. |
options? |
String |
A suffix of the size: ! (ignore aspect ratio), > (only shrink), < (only enlarge), ^ (fill), % (percent). |
Returns Image The same image, for chaining.
Works like resize(). The tool also removes the profiles, so it is a good choice for small previews.
image.thumbnail(150, 150);
method
image.scale([w], [h], [options])
Resizes the image without a resampling filter.
image.scale([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number |
Width in pixels. Use 0 or null to compute it from the height. |
h? |
Number |
Height in pixels. Omit it to compute it from the width. |
options? |
String |
A suffix of the size: ! (ignore aspect ratio), > (only shrink), < (only enlarge), ^ (fill), % (percent). |
Returns Image The same image, for chaining.
Adds -scale. It is faster than resize() and gives a lower quality.
image.scale(50, 50, '%');
method
image.crop(w, h, [x], [y])
Cuts out a rectangle.
image.crop(w, h, [x], [y])| Parameter | Type | Description |
|---|---|---|
w |
Number |
Width in pixels. |
h |
Number |
Height in pixels. |
x? |
Number |
Left offset. Default: 0 |
y? |
Number |
Top offset. Default: 0 |
Returns Image The same image, for chaining.
Adds -crop WxH+X+Y. The offset is relative to the gravity set with align() (top left by default). The offset must be zero or positive.
image.crop(400, 300, 50, 20);
method
image.extent([w], [h], [x], [y])
Sets the canvas size.
image.extent([w], [h], [x], [y])| Parameter | Type | Description |
|---|---|---|
w? |
Number |
Width in pixels. Use 0 or null to compute it from the height. |
h? |
Number |
Height in pixels. Omit it to compute it from the width. |
x? |
Number |
Horizontal offset. |
y? |
Number |
Vertical offset. |
Returns Image The same image, for chaining.
Adds -extent. A larger canvas is filled with the background color; a smaller one cuts the image. x and y move the image (negative values are allowed).
image.background('white').align('center').extent(500, 500);
method
image.align(type)
Sets the gravity of crop(), extent() and watermark().
image.align(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The position. |
Returns Image The same image, for chaining.
Adds -gravity. Values: top left, top, top right, left, center (or middle), right, bottom left, bottom, bottom right; the words can be in any order (left top) and center can be added (top center). Other values go to the tool unchanged, for example NorthEast. gravity() is an alias.
image.align('bottom right');
image.watermark(PATH.public('img/logo.png'), 10, 10);
method
image.filter(type)
Sets the resampling filter for resizing.
image.filter(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
Filter name. |
Returns Image The same image, for chaining.
Adds -filter, for example Lanczos, Box, Hamming, Triangle. See the documentation of your tool for all names.
image.filter('Lanczos').resize(800);
method
image.quality([percentage])
Sets the compression quality.
image.quality([percentage])| Parameter | Type | Description |
|---|---|---|
percentage? |
Number |
From 1 to 100. Default: 80 |
Returns Image The same image, for chaining.
Adds -quality. Without an argument, the value is 80.
image.quality(85);
method
image.rotate(deg)
Rotates the image.
image.rotate(deg)| Parameter | Type | Description |
|---|---|---|
deg |
Number |
Degrees. Default: 0 |
Returns Image The same image, for chaining.
Adds -rotate. Positive values rotate clockwise. It runs after the resize and crop operations (priority 8).
image.rotate(90);
method
image.flip()
Mirrors the image vertically (top to bottom).
image.flip()Returns Image The same image, for chaining.
Adds -flip.
image.flip();
method
image.flop()
Mirrors the image horizontally (left to right).
image.flop()Returns Image The same image, for chaining.
Adds -flop.
image.flop();
method
image.blur(radius)
Blurs the image.
image.blur(radius)| Parameter | Type | Description |
|---|---|---|
radius |
Number|String |
The blur radius. |
Returns Image The same image, for chaining.
Adds -blur. The value is passed to the tool, so it can be a number or radiusxsigma, for example 0x8.
image.blur('0x8');
method
image.grayscale()
Converts the image to gray.
image.grayscale()Returns Image The same image, for chaining.
Adds -colorspace Gray.
image.grayscale();
method
image.sepia()
Gives the image a sepia tone.
image.sepia()Returns Image The same image, for chaining.
Adds -modulate 115,0,100 and -colorize 7,21,50.
image.sepia();
method
image.normalize()
Stretches the contrast to the full range.
image.normalize()Returns Image The same image, for chaining.
Adds -normalize.
image.normalize();
method
image.colors(value)
Reduces the number of colors.
image.colors(value)| Parameter | Type | Description |
|---|---|---|
value |
Number |
The maximum number of colors. |
Returns Image The same image, for chaining.
Adds -colors. Useful for small PNG and GIF files.
image.output('png').colors(256);
method
image.bitdepth(value)
Sets the bit depth of a channel.
image.bitdepth(value)| Parameter | Type | Description |
|---|---|---|
value |
Number |
Bits per channel, for example 8. |
Returns Image The same image, for chaining.
Adds -depth.
image.bitdepth(8);
method
image.background(color)
Sets the background color.
image.background(color)| Parameter | Type | Description |
|---|---|---|
color |
String |
A color name or #RRGGBB. |
Returns Image The same image, for chaining.
Adds -background and -extent 0x0. The color fills transparent areas and the area added by extent(), rotate() and miniature().
image.background('#FFFFFF');
method
image.fill(color)
Sets the fill color for drawing.
image.fill(color)| Parameter | Type | Description |
|---|---|---|
color |
String |
A color name or #RRGGBB. |
Returns Image The same image, for chaining.
Adds -fill. Use it with command() options that draw, for example -colorize.
image.fill('red');
method
image.watermark(filename, [x], [y], [w], [h])
Draws another image over this one.
image.watermark(filename, [x], [y], [w], [h])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The watermark file. |
x? |
Number |
Horizontal offset. Default: 0 |
y? |
Number |
Vertical offset. Default: 0 |
w? |
Number |
Width of the watermark. Default: 0 |
h? |
Number |
Height of the watermark. Default: 0 |
Returns Image The same image, for chaining.
Adds -draw with image over X,Y W,H filename. The file name must not contain spaces or quotes. The position is relative to the gravity from align(). With w and h set to 0, the watermark keeps its size.
Image.load(filename)
.resize(1200)
.align('bottom right')
.watermark(PATH.public('img/logo.png'), 20, 20)
.save(target);
method
image.limit(type, value)
Limits the resources the tool can use.
image.limit(type, value)| Parameter | Type | Description |
|---|---|---|
type |
String |
The resource. |
value |
Number|String |
The limit, in the units of the tool. |
Returns Image The same image, for chaining.
Adds -limit type value, for example memory, map, disk, threads. When you call it, default_image_consumption is not applied to this image.
image.limit('threads', 2);
method
image.minify()
Removes the profiles and metadata.
image.minify()Returns Image The same image, for chaining.
Adds +profile "*", which removes EXIF, ICC and other profiles and makes the file smaller. save(), pipe() and stream() call it on their own when the image has no operation.
Image.load(filename).minify().save(filename);
method
image.output(type)
Sets the output format.
image.output(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
For example png, webp, .jpg. |
Returns Image The same image, for chaining.
Changes image.outputType (a leading dot is removed). pipe() and stream() use it as the format, and res.image() uses it for the Content-Type. save() takes the format from the extension of the target file.
Image.load(stream).output('png').resize(100).pipe(res);
method
image.make(fn)
Calls a function with the image.
image.make(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function(image) |
Adds the operations. |
Returns Image The same image, for chaining.
fn is called with the image as this and as the argument. Use it to reuse a set of operations.
function preview(image) {
image.resize(300).quality(70);
}
Image.load(filename).make(preview).save(target);
method
image.command(key, [value], [priority], [escape])
Adds any option of the tool.
image.command(key, [value], [priority], [escape])| Parameter | Type | Description |
|---|---|---|
key |
String |
The option, for example -sharpen. |
value? |
String|Number |
The value of the option. |
priority? |
Number|Boolean |
Order of the option. Default: 10 |
escape? |
Boolean |
Quote the value. Default: false |
Returns Image The same image, for chaining.
Use it for options without their own method, for example -strip, -sharpen or -define. The options run in the order of their priority (see the guide). escape puts the value in quotes and removes ' from it; use it for values that come from users. With priority set to true, the priority is 0 and the value is escaped.
image.resize(800);
image.command('-sharpen', '0x1');
image.command('-interlace', 'Plane');
method
image.clear()
Removes all operations.
image.clear()Returns Image The same image, for chaining.
Empties image.builder. save() calls it after it runs, so one image object can be used again.
image.clear().resize(100);
method
image.measure(callback)
Reads the width and height of the source file.
image.measure(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function(err, size) |
size is { width, height }. |
Returns Image The same image, for chaining.
Reads the beginning of the file and measures it in JavaScript. It works only for an image loaded from a file name with the extension .jpg, .png, .gif or .webp (lower or upper case); other extensions, .jpeg included, give an error. For a stream or a buffer use Image.measure(), and for other formats identify().
Image.load(PATH.public('img/a.jpg')).measure(function(err, size) {
console.log(size.width, size.height);
});
method
image.identify(callback)
Reads the type and size of the source file with the external tool.
image.identify(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function(err, info) |
info is { type, width, height }, for example { type: 'JPEG', width: 800, height: 600 }. |
Returns Image The same image, for chaining.
Runs gm identify (or identify for im and magick) and parses the first line. It needs an image loaded from a file name.
Image.load(filename).identify(function(err, info) {
err && console.error(err);
info && console.log(info.type, info.width, info.height);
});
method
image.save([filename], [callback], [writer])
Runs the operations and saves the result to a file.
image.save([filename], [callback], [writer])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
The target file. Default: the source file |
callback? |
Function(err, saved) |
saved is true on success and false on an error. |
writer? |
Function(stdin) |
Gets the input stream of the tool, to write the source yourself. |
Returns Image The same image, for chaining.
Without filename, the source file is overwritten. The format follows the extension of filename. A registered Image.middleware() for the output type runs after the file is written. After the run, the operations are cleared.
Image.load(PATH.public('img/photo.jpg'))
.resize(1024)
.quality(75)
.save(PATH.public('img/photo.webp'), function(err, saved) {
if (err)
console.error(err);
});
method
image.pipe(stream, [type], [options])
Runs the operations and pipes the result into a writable stream.
image.pipe(stream, [type], [options])| Parameter | Type | Description |
|---|---|---|
stream |
Stream |
A writable stream, for example a file stream or res. |
type? |
String |
Output format. Default: image.outputType |
options? |
Object |
Options of pipe(). |
Returns Image The same image, for chaining.
type is the output format: jpg, jpeg, png, gif, apng, heif, heic, webp or ico. Another value or none uses image.outputType. options are passed to stream.pipe(). Errors of the tool are emitted as error events of stream.
var target = Fs.createWriteStream(PATH.temp('thumb.png'));
Image.load(buffer).resize(64, 64).pipe(target, 'png');
method
image.stream([type], [writer])
Runs the operations and returns the result as a readable stream.
image.stream([type], [writer])| Parameter | Type | Description |
|---|---|---|
type? |
String |
Output format. Default: image.outputType |
writer? |
Function(stdin) |
Writes the source data. |
Returns ReadableStream The output of the tool (through the middleware, if one is registered).
type works as in pipe(). writer(stdin) can write the source into the tool yourself.
var stream = Image.load(filename).resize(500).stream('jpg');
stream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));
config
default_image_consumption : 0
Limits the memory of GraphicsMagick or ImageMagick, as a percentage.
default_image_consumption : 0Returns Number
When it is not 0, each image without its own limit() gets -limit memory (15 × value) and -limit map (30 × value). It is disabled by default because some versions of GraphicsMagick fail with these limits. A % sign in the config file is allowed.
Default: 0 (disabled).
default_image_consumption : 50