Spanish Total.js
English
Documentation For AI agents
Contents

Images

The Image global and every method of image objects.

.md GitHub
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.

Image 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.

Resize a photo
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.
ParameterTypeDescription
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.

Load from a file and a buffer
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().
ParameterTypeDescription
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.

Load an image
F.image(filename).grayscale().save(target);
class

new Image.Image(source, [converter], [width], [height])

The constructor of image objects.
ParameterTypeDescription
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.

Add a method
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.
ParameterTypeDescription
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.

Measure an uploaded buffer
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.
ParameterTypeDescription
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.

Measure
var size = Image.measureJPG(buffer);
console.log(size.width, size.height);
A JPEG without the size
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.
ParameterTypeDescription
buffer Buffer The beginning of the file.

Returns Object { width, height }.

It reads the IHDR header, so 24 bytes are enough.

Measure
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.
ParameterTypeDescription
buffer Buffer The beginning of the file.

Returns Object { width, height }.

It reads the logical screen size, so 10 bytes are enough.

Measure
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.
ParameterTypeDescription
buffer Buffer The beginning of the file.

Returns Object { width, height }.

It reads the VP8 , VP8L and VP8X headers. Returns undefined for other data.

Measure
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.
ParameterTypeDescription
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.

Measure
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.
ParameterTypeDescription
buffer Buffer The beginning of the file.

Returns Object { width, height }.

It reads the BITMAPINFOHEADER.

Measure
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.
ParameterTypeDescription
buffer Buffer The beginning of the file.

Returns Object { width, height }.

It reads the PSD file header.

Measure
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.
ParameterTypeDescription
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.

Pass PNG results through a stream
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().

Returns 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.

Known size
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.

Returns 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.

Returns 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.

Returns 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.

Returns 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.
ParameterTypeDescription
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.

Resize
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.
ParameterTypeDescription
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().

Thumbnail
Image.load(filename).thumbnail(150, 150).save(target);
method

img.scale([w], [h], [options])

Resizes the image quickly without filtering.
ParameterTypeDescription
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().

Scale
img.scale(64, 64);
method

img.geometry([w], [h], [options])

Adds the -geometry option.
ParameterTypeDescription
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.

Geometry
img.geometry(300, 200, '!');
method

img.crop(w, h, [x], [y])

Cuts an area of the image.
ParameterTypeDescription
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).

Crop
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.
ParameterTypeDescription
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().

Square canvas
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.
ParameterTypeDescription
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().

Product photo
Image.load(filename).miniature(300, 300, '#F0F0F0').save(target);
method

img.resizecenter(w, h, [color])

Fills a box and crops the centre.
ParameterTypeDescription
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.

Cover
Image.load(filename).resizecenter(1200, 630).save(target);
method

img.resizealign(w, h, [align], [color])

Fills a box and crops at a side.
ParameterTypeDescription
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().

Avatar
Image.load(filename).resizealign(200, 200, 'top').save(target);
method

img.align(type)

Sets the gravity for crop and extent.
ParameterTypeDescription
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'.

Align
img.align('bottom right').crop(400, 300);
method

img.gravity(type)

The same method as align().
ParameterTypeDescription
type String The position.

Returns Image The same image object, for chaining.

An alias of align().

Gravity
img.gravity('NorthWest');
method

img.quality([percentage])

Sets the compression quality.
ParameterTypeDescription
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.

Quality
img.quality(70);
method

img.rotate([deg])

Rotates the image.
ParameterTypeDescription
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.

Rotate
img.background('white').rotate(45);
method

img.flip()

Mirrors the image vertically.

Returns Image The same image object, for chaining.

Adds -flip (top to bottom).

Flip
img.flip();
method

img.flop()

Mirrors the image horizontally.

Returns Image The same image object, for chaining.

Adds -flop (left to right).

Flop
img.flop();
method

img.blur(radius)

Blurs the image.
ParameterTypeDescription
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').

Blur
img.blur(5);
img.blur('0x8');
method

img.grayscale()

Converts the image to gray.

Returns Image The same image object, for chaining.

Adds -colorspace Gray.

Gray
img.grayscale();
method

img.sepia()

Gives the image a sepia tone.

Returns Image The same image object, for chaining.

Adds -modulate 115,0,100 -colorize 7,21,50.

Sepia
img.sepia();
method

img.normalize()

Stretches the contrast.

Returns Image The same image object, for chaining.

Adds -normalize: the colors are spread over the full range.

Normalize
img.normalize();
method

img.colors(value)

Reduces the number of colors.
ParameterTypeDescription
value Number The maximum number of colors.

Returns Image The same image object, for chaining.

Adds -colors.

Palette
img.output('png').colors(64);
method

img.bitdepth(value)

Sets the bit depth.
ParameterTypeDescription
value Number Bits per channel, for example 8.

Returns Image The same image object, for chaining.

Adds -depth.

Depth
img.bitdepth(8);
method

img.background(color)

Sets the background color.
ParameterTypeDescription
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.

Background
img.background('#FFFFFF').extent(800, 800);
method

img.fill(color)

Sets the fill color.
ParameterTypeDescription
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.

Fill
img.fill('red').command('-colorize', '30');
method

img.filter(type)

Sets the resize filter.
ParameterTypeDescription
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().

Filter
img.resize(400).filter('Lanczos');
The command
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.
ParameterTypeDescription
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'.

Define
img.define('jpeg:extent=200kb');
method

img.minify()

Removes the profiles and metadata.

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.

Strip metadata
Image.load(filename).minify().save(target);
method

img.limit(type, value)

Limits a resource of the program.
ParameterTypeDescription
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.

Limit memory
img.limit('memory', '256MB').limit('map', '512MB');
method

img.watermark(filename, [x], [y], [w], [h])

Draws another image over the picture.
ParameterTypeDescription
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.

Logo in the corner
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.
ParameterTypeDescription
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).

Custom options
img.command('-sharpen', '0x1');
img.command('-strip');
img.command('-label', 'My photo', true);
method

img.make(fn)

Applies a function to the image.
ParameterTypeDescription
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.

Preset
function avatar(img) {
	img.resizecenter(128, 128).quality(90);
}

Image.load(filename).make(avatar).save(target);
method

img.clear()

Removes all operations.

Returns Image The same image object, for chaining.

Empties the list of operations. save() calls it after the program finishes.

Clear
img.clear().resize(100);
method

img.output(type)

Sets the image type.
ParameterTypeDescription
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.

Buffer to PNG
Image.load(buffer).output('png').resize(100).pipe($.res);
method

img.save([filename], [callback])

Runs the program and writes the result to a file.
ParameterTypeDescription
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.

Save
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.
ParameterTypeDescription
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.

Send to the response
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.
ParameterTypeDescription
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().

Collect into a Buffer
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.
ParameterTypeDescription
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.

Measure a file
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.
ParameterTypeDescription
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.

Show the command
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'
Made in Europe