Images
The Image global and every method of image objects.
On this page
The Image global loads, changes, measures and saves images with GraphicsMagick or ImageMagick. The guide Images explains how to use it with examples; this page is the exact reference.
API
class
Image
The global image module.
ImageImage is the image module of the framework. It has Image.load() to create image objects, the Image.measure*() functions that read the size from a file header, Image.middleware() and the constructor Image.Image. The operations run with the program set in $imageconverter.
Image.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));
method
Image.load(source, [converter], [width], [height])
Creates an image object.
Image.load(source, [converter], [width], [height])| Parameter | Type | Description |
|---|---|---|
source |
String|Buffer|Stream |
A file name, a Buffer or a readable stream. |
converter? |
String |
The program: gm, im or magick. Default: CONF.$imageconverter |
width? |
Number |
The known width, stored in img.width. |
height? |
Number |
The known height, stored in img.height. |
Returns Image A new image object.
source is a file name, a Buffer or a readable stream. With a file name, img.type is its extension; otherwise it is jpg. converter is gm, im or magick and overrides $imageconverter for this image. width and height are only stored in img.width and img.height; they are not read from the file.
var a = Image.load(PATH.public('photo.jpg'));
var b = Image.load(buffer, 'magick');
method
F.image(source, [converter], [width], [height])
The same function as Image.load().
F.image(source, [converter], [width], [height])| Parameter | Type | Description |
|---|---|---|
source |
String|Buffer|Stream |
A file name, a Buffer or a readable stream. |
converter? |
String |
The program: gm, im or magick. Default: CONF.$imageconverter |
width? |
Number |
The known width. |
height? |
Number |
The known height. |
Returns Image A new image object.
An alias of Image.load() on the framework object.
F.image(filename).grayscale().save(target);
class
new Image.Image(source, [converter], [width], [height])
The constructor of image objects.
new Image.Image(source, [converter], [width], [height])| Parameter | Type | Description |
|---|---|---|
source |
String|Buffer|Stream |
A file name, a Buffer or a readable stream. |
converter? |
String |
The program: gm, im or magick. Default: CONF.$imageconverter |
width? |
Number |
The known width. |
height? |
Number |
The known height. |
Image.load() returns new Image.Image(...) with the same arguments. Use it when you want to test img instanceof Image.Image or add your own methods to Image.Image.prototype.
Image.Image.prototype.avatar = function() {
return this.resizecenter(128, 128).quality(90);
};
Image.load(filename).avatar().save(target);
method
Image.measure(type, buffer)
Reads the width and height from the header of an image.
Image.measure(type, buffer)| Parameter | Type | Description |
|---|---|---|
type |
String |
An extension or a MIME type. |
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }, null for a JPEG without the size marker, undefined for an unsupported type.
type is an extension with or without the dot (jpg, .png) or a MIME type (image/webp). Supported types are JPEG, PNG, GIF, WebP, SVG, BMP and PSD. The buffer needs only the beginning of the file. For other types it returns undefined. For a JPEG buffer without the size marker it returns null.
var size = Image.measure('image/png', buffer);
if (size && size.width > 2000)
$.invalid('The image is too wide');
method
Image.measureJPG(buffer)
Reads the size of a JPEG image from a buffer.
Image.measureJPG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height } or null.
It scans the markers until the frame header. Returns null when the buffer is not a JPEG or when the frame header is not in the buffer (a damaged file, a segment with an invalid length or too little data). Pass enough data: the framework reads 40 kB.
var size = Image.measureJPG(buffer);
console.log(size.width, size.height);
var buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);
var size = Image.measureJPG(buffer);
console.log(size); // null: no frame header in the buffer
method
Image.measurePNG(buffer)
Reads the size of a PNG image from a buffer.
Image.measurePNG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the IHDR header, so 24 bytes are enough.
var size = Image.measurePNG(buffer);
console.log(size.width, size.height);
method
Image.measureGIF(buffer)
Reads the size of a GIF image from a buffer.
Image.measureGIF(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the logical screen size, so 10 bytes are enough.
var size = Image.measureGIF(buffer);
console.log(size.width, size.height);
method
Image.measureWEBP(buffer)
Reads the size of a WebP image from a buffer.
Image.measureWEBP(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the VP8 , VP8L and VP8X headers. Returns undefined for other data.
var size = Image.measureWEBP(buffer);
console.log(size.width, size.height);
method
Image.measureSVG(buffer)
Reads the size of a SVG image from a buffer.
Image.measureSVG(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the first width="..." and height="..." attributes with whole numbers. Returns undefined when there is none.
var size = Image.measureSVG(buffer);
console.log(size.width, size.height);
method
Image.measureBMP(buffer)
Reads the size of a BMP image from a buffer.
Image.measureBMP(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the BITMAPINFOHEADER.
var size = Image.measureBMP(buffer);
console.log(size.width, size.height);
method
Image.measurePSD(buffer)
Reads the size of a Photoshop (PSD) image from a buffer.
Image.measurePSD(buffer)| Parameter | Type | Description |
|---|---|---|
buffer |
Buffer |
The beginning of the file. |
Returns Object { width, height }.
It reads the PSD file header.
var size = Image.measurePSD(buffer);
console.log(size.width, size.height);
method
Image.middleware(type, fn)
Registers a stream that post-processes results of one type.
Image.middleware(type, fn)| Parameter | Type | Description |
|---|---|---|
type |
String |
The image type, for example png or .jpg. |
fn |
Function |
Returns a Transform stream. |
fn must return a new Transform stream each time it is called. With pipe() and writer() the output of the program goes through it before it reaches you, and type is matched with the output format. With save() and a callback, the saved file is read through it and written again before the callback runs; there type is matched with img.type (the extension of the source or the value of output()). A leading dot in type is removed. One function per type; a new call replaces it.
var Transform = require('stream').Transform;
Image.middleware('png', function() {
return new Transform({
transform: function(chunk, encoding, next) {
next(null, chunk);
}
});
});
property
img.width
The width passed to Image.load().
img.widthReturns Number
The third argument of Image.load(), or undefined. It is not read from the file; use img.measure() for that. img.height holds the fourth argument the same way.
var img = Image.load(file.path, null, file.width, file.height);
if (img.width > 1000)
img.resize(1000);
property
img.filename
The source file name.
img.filenameReturns String
The file name given to Image.load(), or null when the source is a Buffer or a stream.
property
img.stream
The source Buffer or stream.
img.streamReturns Buffer|Stream
The Buffer or readable stream given to Image.load(), or null when the source is a file name. It is written to the standard input of the program when the image is saved or piped.
property
img.type
The image type.
img.typeReturns String
The extension of the source file in lower case without the dot (jpg, png…), or jpg for a Buffer or a stream. output() changes it. pipe() and writer() use it as the output format when you do not pass one, and Image.middleware() handlers are matched with it.
property
img.shell
The program that processes the image.
img.shellReturns String
gm, im or magick: the second argument of Image.load(), otherwise CONF.$imageconverter. gm runs gm convert, im runs convert and magick runs magick. You can change it before you save the image.
method
img.resize([w], [h], [options])
Resizes the image.
img.resize([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number|String |
The width in pixels, or a percentage like '50%'. Empty to keep the ratio. |
h? |
Number|String |
The height in pixels, or a percentage. Empty to keep the ratio. |
options? |
String |
A suffix of the size: ! ignores the ratio, ^ fills the box, > only shrinks, < only enlarges. |
Returns Image The same image object, for chaining.
Adds -resize WxH. The image fits into the box and keeps its aspect ratio unless options says otherwise. With only w the height follows the ratio, with only h the width does.
img.resize(800, 600); // into 800x600
img.resize(800); // width 800
img.resize(null, 600); // height 600
img.resize(200, 200, '!'); // exactly 200x200
img.resize('50%'); // half size
method
img.thumbnail([w], [h], [options])
Resizes the image for a small preview.
img.thumbnail([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number|String |
The width in pixels, or a percentage like '50%'. Empty to keep the ratio. |
h? |
Number|String |
The height in pixels, or a percentage. Empty to keep the ratio. |
options? |
String |
A suffix of the size: ! ignores the ratio, ^ fills the box, > only shrinks, < only enlarges. |
Returns Image The same image object, for chaining.
Adds -thumbnail WxH: a resize that also removes the profiles, so the file is smaller. The arguments are the same as in resize().
Image.load(filename).thumbnail(150, 150).save(target);
method
img.scale([w], [h], [options])
Resizes the image quickly without filtering.
img.scale([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number|String |
The width in pixels, or a percentage like '50%'. Empty to keep the ratio. |
h? |
Number|String |
The height in pixels, or a percentage. Empty to keep the ratio. |
options? |
String |
A suffix of the size: ! ignores the ratio, ^ fills the box, > only shrinks, < only enlarges. |
Returns Image The same image object, for chaining.
Adds -scale WxH. Faster than resize() but with lower quality. The arguments are the same as in resize().
img.scale(64, 64);
method
img.geometry([w], [h], [options])
Adds the -geometry option.
img.geometry([w], [h], [options])| Parameter | Type | Description |
|---|---|---|
w? |
Number|String |
The width in pixels, or a percentage like '50%'. Empty to keep the ratio. |
h? |
Number|String |
The height in pixels, or a percentage. Empty to keep the ratio. |
options? |
String |
A suffix of the size: ! ignores the ratio, ^ fills the box, > only shrinks, < only enlarges. |
Returns Image The same image object, for chaining.
Adds -geometry WxH with the optional suffix. The program uses it as the preferred size and offset.
img.geometry(300, 200, '!');
method
img.crop(w, h, [x], [y])
Cuts an area of the image.
img.crop(w, h, [x], [y])| Parameter | Type | Description |
|---|---|---|
w |
Number |
The width of the area. |
h |
Number |
The height of the area. |
x? |
Number |
The horizontal offset. Default: 0 |
y? |
Number |
The vertical offset. Default: 0 |
Returns Image The same image object, for chaining.
Adds -crop WxH+X+Y. The offset is measured from the corner set by align() (top left by default).
img.crop(400, 300, 50, 20);
// The centre
img.align('center').crop(400, 300);
method
img.extent([w], [h], [x], [y])
Sets the size of the canvas.
img.extent([w], [h], [x], [y])| Parameter | Type | Description |
|---|---|---|
w? |
Number |
The width of the canvas. |
h? |
Number |
The height of the canvas. |
x? |
Number |
The horizontal offset, can be negative. |
y? |
Number |
The vertical offset, can be negative. |
Returns Image The same image object, for chaining.
Adds -extent WxH with an optional offset. A larger canvas is filled with the background color, a smaller one cuts the image. The position follows align().
img.resize(500, 500).background('white').align('center').extent(500, 500);
method
img.miniature(w, h, [color], [filter])
Fits the image into a box and fills the rest.
img.miniature(w, h, [color], [filter])| Parameter | Type | Description |
|---|---|---|
w |
Number |
The width. |
h |
Number |
The height. |
color? |
String |
The color of the free area. Default: 'white' |
filter? |
String |
The resize filter. Default: 'Hamming' |
Returns Image The same image object, for chaining.
A shortcut for thumbnail(w, h).background(color).align('center').extent(w, h). The result is exactly wxh and shows the whole image. filter is the resize filter of thumbnail().
Image.load(filename).miniature(300, 300, '#F0F0F0').save(target);
method
img.resizecenter(w, h, [color])
Fills a box and crops the centre.
img.resizecenter(w, h, [color])| Parameter | Type | Description |
|---|---|---|
w |
Number |
The width. |
h |
Number |
The height. |
color? |
String |
The background color. Default: 'white' |
Returns Image The same image object, for chaining.
A shortcut for resize(w, h, '^').background(color).align('center').crop(w, h). The result is wxh and the image covers it completely.
Image.load(filename).resizecenter(1200, 630).save(target);
method
img.resizealign(w, h, [align], [color])
Fills a box and crops at a side.
img.resizealign(w, h, [align], [color])| Parameter | Type | Description |
|---|---|---|
w |
Number |
The width. |
h |
Number |
The height. |
align? |
String |
Where to crop: top, bottom, left, center… Default: 'center' |
color? |
String |
The background color. Default: 'white' |
Returns Image The same image object, for chaining.
A shortcut for resize(w, h, '^').background(color).align(align).crop(w, h). align takes the values of align().
Image.load(filename).resizealign(200, 200, 'top').save(target);
method
img.align(type)
Sets the gravity for crop and extent.
img.align(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The position. |
Returns Image The same image object, for chaining.
Adds -gravity. Accepted values: 'top left' (NorthWest), 'top' (North), 'top right' (NorthEast), 'left' (West), 'center' or 'middle' (Center), 'right' (East), 'bottom left' (SouthWest), 'bottom' (South), 'bottom right' (SouthEast). Word order does not matter ('left top'), and 'center left' means left. Other values are passed as they are, for example 'NorthEast'.
img.align('bottom right').crop(400, 300);
method
img.gravity(type)
The same method as align().
img.gravity(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The position. |
Returns Image The same image object, for chaining.
An alias of align().
img.gravity('NorthWest');
method
img.quality([percentage])
Sets the compression quality.
img.quality([percentage])| Parameter | Type | Description |
|---|---|---|
percentage? |
Number |
The quality. Default: 80 |
Returns Image The same image object, for chaining.
Adds -quality. For JPEG and WebP it is the quality from 1 to 100; an empty value means 80.
img.quality(70);
method
img.rotate([deg])
Rotates the image.
img.rotate([deg])| Parameter | Type | Description |
|---|---|---|
deg? |
Number |
The angle in degrees. Default: 0 |
Returns Image The same image object, for chaining.
Adds -rotate. The angle is in degrees clockwise. For angles other than multiples of 90 the corners are filled with the background color.
img.background('white').rotate(45);
method
img.flip()
Mirrors the image vertically.
img.flip()Returns Image The same image object, for chaining.
Adds -flip (top to bottom).
img.flip();
method
img.flop()
Mirrors the image horizontally.
img.flop()Returns Image The same image object, for chaining.
Adds -flop (left to right).
img.flop();
method
img.blur(radius)
Blurs the image.
img.blur(radius)| Parameter | Type | Description |
|---|---|---|
radius |
Number|String |
The radius or radiusxsigma. |
Returns Image The same image object, for chaining.
Adds -blur. The value is the radius, or radiusxsigma as a string ('0x8').
img.blur(5);
img.blur('0x8');
method
img.grayscale()
Converts the image to gray.
img.grayscale()Returns Image The same image object, for chaining.
Adds -colorspace Gray.
img.grayscale();
method
img.sepia()
Gives the image a sepia tone.
img.sepia()Returns Image The same image object, for chaining.
Adds -modulate 115,0,100 -colorize 7,21,50.
img.sepia();
method
img.normalize()
Stretches the contrast.
img.normalize()Returns Image The same image object, for chaining.
Adds -normalize: the colors are spread over the full range.
img.normalize();
method
img.colors(value)
Reduces the number of colors.
img.colors(value)| Parameter | Type | Description |
|---|---|---|
value |
Number |
The maximum number of colors. |
Returns Image The same image object, for chaining.
Adds -colors.
img.output('png').colors(64);
method
img.bitdepth(value)
Sets the bit depth.
img.bitdepth(value)| Parameter | Type | Description |
|---|---|---|
value |
Number |
Bits per channel, for example 8. |
Returns Image The same image object, for chaining.
Adds -depth.
img.bitdepth(8);
method
img.background(color)
Sets the background color.
img.background(color)| Parameter | Type | Description |
|---|---|---|
color |
String |
The color. |
Returns Image The same image object, for chaining.
Adds -background color and then -extent 0x0, so the color is set before the canvas is extended. The color fills new areas made by extent(), rotate() and the resize helpers. Any color of the program works: white, #FF0000, none for transparent.
img.background('#FFFFFF').extent(800, 800);
method
img.fill(color)
Sets the fill color.
img.fill(color)| Parameter | Type | Description |
|---|---|---|
color |
String |
The color. |
Returns Image The same image object, for chaining.
Adds -fill. Used by operations that draw, for example -colorize or your own command() options.
img.fill('red').command('-colorize', '30');
method
img.filter(type)
Sets the resize filter.
img.filter(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The filter name. |
Returns Image The same image object, for chaining.
Adds -filter, for example 'Lanczos', 'Hamming', 'Box' or 'Triangle'. It is always placed before -resize, -thumbnail and -scale, so it applies to them whether you call it before or after resize(), thumbnail() or scale().
img.resize(400).filter('Lanczos');
Image.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');
// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'
method
img.define(value)
Passes a coder option.
img.define(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
The definition format:key=value. |
Returns Image The same image object, for chaining.
Adds -define, for example 'jpeg:extent=200kb' or 'png:compression-level=9'.
img.define('jpeg:extent=200kb');
method
img.minify()
Removes the profiles and metadata.
img.minify()Returns Image The same image object, for chaining.
Adds +profile '*', which removes EXIF, ICC and other profiles. save(), pipe() and writer() call it when the image has no operations.
Image.load(filename).minify().save(target);
method
img.limit(type, value)
Limits a resource of the program.
img.limit(type, value)| Parameter | Type | Description |
|---|---|---|
type |
String |
The resource. |
value |
Number|String |
The limit, for example 256MB. |
Returns Image The same image object, for chaining.
Adds -limit type value, for example limit('memory', '256MB'). Types and units are those of the program (memory, map, disk…). A number without a unit is in bytes.
img.limit('memory', '256MB').limit('map', '512MB');
method
img.watermark(filename, [x], [y], [w], [h])
Draws another image over the picture.
img.watermark(filename, [x], [y], [w], [h])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The file of the watermark. |
x? |
Number |
The horizontal offset. Default: 0 |
y? |
Number |
The vertical offset. Default: 0 |
w? |
Number |
The width of the watermark. Default: 0 |
h? |
Number |
The height of the watermark. Default: 0 |
Returns Image The same image object, for chaining.
Adds -draw 'image over x,y w,h filename'. The offset is measured from the top left corner. A width and height of 0 keep the size of the watermark. Single quotes are removed from the file name.
Image.load(filename)
.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)
.save(target);
method
img.command(key, [value], [priority], [escape])
Adds any option of the program.
img.command(key, [value], [priority], [escape])| Parameter | Type | Description |
|---|---|---|
key |
String |
The option, for example -sharpen. |
value? |
String|Number |
The value. |
priority? |
Number|Boolean |
The position, or true to quote the value. Default: 10 |
escape? |
Boolean |
Quote the value. Default: false |
Returns Image The same image object, for chaining.
Adds key value to the command. priority decides the position (lower first, default 10; sizes have 1, gravity 3, crop 4, quality 5, rotate 8). escape puts the value in quotes; passing true as priority also turns on escape (with priority 10).
img.command('-sharpen', '0x1');
img.command('-strip');
img.command('-label', 'My photo', true);
method
img.make(fn)
Applies a function to the image.
img.make(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
Gets the image. |
Returns Image The same image object, for chaining.
Calls fn(img) with this set to the image. Use it to reuse a set of operations.
function avatar(img) {
img.resizecenter(128, 128).quality(90);
}
Image.load(filename).make(avatar).save(target);
method
img.clear()
Removes all operations.
img.clear()Returns Image The same image object, for chaining.
Empties the list of operations. save() calls it after the program finishes.
img.clear().resize(100);
method
img.output(type)
Sets the image type.
img.output(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The type, for example png or .webp. |
Returns Image The same image object, for chaining.
Sets img.type (a leading dot is removed). pipe() and writer() produce this format when you do not pass one, and Image.middleware() is matched with it. save() takes the format from the extension of the target file.
Image.load(buffer).output('png').resize(100).pipe($.res);
method
img.save([filename], [callback])
Runs the program and writes the result to a file.
img.save([filename], [callback])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
The target file. Default: img.filename |
callback? |
Function |
function(err, success). |
Returns Image The same image object, for chaining.
Builds the command and runs it. The format comes from the extension of filename. Without filename the source file is overwritten. A Buffer or stream source is sent to the standard input. The callback gets (err, success), where success is true or false. The operations are cleared afterwards.
Image.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {
if (err)
$.invalid(err);
else
$.success();
});
method
img.pipe(stream, [type], [options])
Runs the program and sends the result to a stream.
img.pipe(stream, [type], [options])| Parameter | Type | Description |
|---|---|---|
stream |
Stream |
A writable stream, for example $.res. |
type? |
String |
The output format. Default: img.type |
options? |
Object |
Options of stream.pipe(). |
Returns Image The same image object, for chaining.
Writes the output of the program to stream. type is the output format: jpg, jpeg, png, gif, apng, webp, heif, heic or ico; other values use img.type. options goes to stream.pipe() (for example { end: false }); you can pass it as the second argument. Messages of the program on the standard error are emitted as error events on stream.
function preview($) {
$.res.writeHead(200, { 'content-type': 'image/png' });
Image.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');
}
method
img.writer([type])
Runs the program and returns the output stream.
img.writer([type])| Parameter | Type | Description |
|---|---|---|
type? |
String |
The output format. Default: img.type |
Returns Stream A readable stream with the result.
Starts the program and returns its readable output (passed through the Image.middleware() of the type, when there is one). type takes the same values as in pipe().
var chunks = [];
var stream = Image.load(buffer).resize(100, 100).writer('webp');
stream.on('data', chunk => chunks.push(chunk));
stream.on('end', function() {
var output = Buffer.concat(chunks);
});
method
img.measure(callback)
Reads the size of the source file.
img.measure(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(err, size). |
Returns Image The same image object, for chaining.
Reads the header of the source file and calls callback(err, size) with { width, height }. For a .jpg file without the frame header in its first 40 kB, size is null. The source must be a file name with the extension .jpg, .png, .gif or .webp; other extensions give an error. It does not use the external program.
Image.load(PATH.public('photo.jpg')).measure(function(err, size) {
console.log(size.width, size.height);
});
method
img.cmd(from, to)
Returns the command line without running it.
img.cmd(from, to)| Parameter | Type | Description |
|---|---|---|
from |
String |
The source file or -. |
to |
String |
The target file or -. |
Returns String The command line.
Builds the command used by save(): the program, the quoted source, the sorted operations and the quoted target. Use '-' for the standard input or output. Useful for debugging.
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'