Spanish Total.js
English
Documentation For AI agents
Contents

Images

The global Image object, the methods of an image, and the image config keys.

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

Returns Image

Create it with Image.load(); the constructor is Image.Image (alias Image.Picture). Properties:

  • filename — the source file, or null for a stream or a buffer
  • outputType — the output format; the extension of the file, jpg for streams and buffers, or the value of output()
  • width, height — the values passed to Image.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.

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

Resize a file
Image.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));
From a buffer with ImageMagick 7
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().
ParameterTypeDescription
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().

Create an image
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.
ParameterTypeDescription
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.

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

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

Returns Object { width, height }

Reads the size from the IHDR chunk; 24 bytes are enough.

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

Returns Object { width, height }

Reads the logical screen size; 10 bytes are enough.

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

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

Returns Object { width, height }

Reads the size from the Photoshop header.

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

Measure a WebP file
var size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));
method

Image.measureSVG(buffer)

Returns the width and height of an SVG image.
ParameterTypeDescription
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.

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

Pass all PNG output through a stream
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.
ParameterTypeDescription
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.

Common sizes
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.
ParameterTypeDescription
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.

A square avatar
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.
ParameterTypeDescription
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.

Keep the top part
image.resizeAlign(1200, 400, 'top');
method

image.miniature(w, h, [color], [filter])

Fits the whole image into the size and fills the empty area.
ParameterTypeDescription
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.

Product picture on white
image.miniature(300, 300);
image.miniature(300, 300, '#000000', 'Lanczos');
method

image.thumbnail([w], [h], [options])

Resizes the image with the -thumbnail option.
ParameterTypeDescription
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.

Preview
image.thumbnail(150, 150);
method

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

Resizes the image without a resampling filter.
ParameterTypeDescription
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.

Half size
image.scale(50, 50, '%');
method

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

Cuts out a rectangle.
ParameterTypeDescription
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.

Crop a region
image.crop(400, 300, 50, 20);
method

image.extent([w], [h], [x], [y])

Sets the canvas size.
ParameterTypeDescription
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).

Square canvas
image.background('white').align('center').extent(500, 500);
method

image.align(type)

Sets the gravity of crop(), extent() and watermark().
ParameterTypeDescription
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.

Watermark in the corner
image.align('bottom right');
image.watermark(PATH.public('img/logo.png'), 10, 10);
method

image.filter(type)

Sets the resampling filter for resizing.
ParameterTypeDescription
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.

Sharp downscale
image.filter('Lanczos').resize(800);
method

image.quality([percentage])

Sets the compression quality.
ParameterTypeDescription
percentage? Number From 1 to 100. Default: 80

Returns Image The same image, for chaining.

Adds -quality. Without an argument, the value is 80.

Set the quality
image.quality(85);
method

image.rotate(deg)

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

Rotate
image.rotate(90);
method

image.flip()

Mirrors the image vertically (top to bottom).

Returns Image The same image, for chaining.

Adds -flip.

Flip
image.flip();
method

image.flop()

Mirrors the image horizontally (left to right).

Returns Image The same image, for chaining.

Adds -flop.

Flop
image.flop();
method

image.blur(radius)

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

Blur
image.blur('0x8');
method

image.grayscale()

Converts the image to gray.

Returns Image The same image, for chaining.

Adds -colorspace Gray.

Gray
image.grayscale();
method

image.sepia()

Gives the image a sepia tone.

Returns Image The same image, for chaining.

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

Sepia
image.sepia();
method

image.normalize()

Stretches the contrast to the full range.

Returns Image The same image, for chaining.

Adds -normalize.

Normalize
image.normalize();
method

image.colors(value)

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

Returns Image The same image, for chaining.

Adds -colors. Useful for small PNG and GIF files.

256 colors
image.output('png').colors(256);
method

image.bitdepth(value)

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

Returns Image The same image, for chaining.

Adds -depth.

8 bits
image.bitdepth(8);
method

image.background(color)

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

White background
image.background('#FFFFFF');
method

image.fill(color)

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

Fill
image.fill('red');
method

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

Draws another image over this one.
ParameterTypeDescription
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.

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

Two threads
image.limit('threads', 2);
method

image.minify()

Removes the profiles and metadata.

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.

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

image.output(type)

Sets the output format.
ParameterTypeDescription
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.

Convert a stream to PNG
Image.load(stream).output('png').resize(100).pipe(res);
method

image.make(fn)

Calls a function with the image.
ParameterTypeDescription
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.

Reusable preset
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.
ParameterTypeDescription
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.

Sharpen and interlace
image.resize(800);
image.command('-sharpen', '0x1');
image.command('-interlace', 'Plane');
method

image.clear()

Removes all operations.

Returns Image The same image, for chaining.

Empties image.builder. save() calls it after it runs, so one image object can be used again.

Start again
image.clear().resize(100);
method

image.measure(callback)

Reads the width and height of the source file.
ParameterTypeDescription
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().

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

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

Save a copy as WebP
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.
ParameterTypeDescription
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.

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

Upload a resized image
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.

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

Half of the default limits
default_image_consumption : 50
Made in Europe