Creates a new image with the given dimensions, all pixels transparent black
The width in pixels (a fraction is truncated)
The height in pixels (a fraction is truncated)
The image's RGBA pixel data (red, green, blue and transparency, four bytes per pixel). It can be replaced by any 8-bit array with width * height * 4 bytes starting at a byte offset divisible by 4 (it is used as is, without copying). Direct changes to this array or Image.setPixelAt don't update the image's gain map.
Replaces the pixel data
The new RGBA data, width * height * 4 bytes (used as is, without copying, so its byte offset has to be divisible by 4: the image reads it as 32-bit pixels too)
Extra image data that lets high-dynamic-range (HDR) screens show brighter highlights. Standard screens show the
image without the extra brightness. Image.encodeJPEG, Image.encodeAVIF and
Image.encodeJXL can write it. null means there is no gain map. This is the image's own map, not a
copy: changing it (image.gainMap.max = 3) changes the image's
Replaces the gain map
The new gain map, or null to remove it
The image uses a copy of the map: changing the image (resizing it, say) changes its own map only, also when the same map was given to other images, and later changes to the map you gave don't reach the image
TypeError if it isn't a GainMap or null
The image's height
The image's width
Gets the average color of the image, weighting each pixel by its opacity
The average color (fully opaque), black for fully transparent images
Image.dominantColor for the color that most of the image has
Scales the blue channel
The factor to multiply the channel with (>= 0, results are clamped)
Blurs the image with a gaussian blur (transparent pixels don't bleed their color)
The blur radius: the gaussian's standard deviation in pixels, like CSS' blur()
Multiplies the color channels, e.g. 1.2 makes the image 20% brighter
The factor (>= 0, 1 keeps the image)
Clones the current image
Mixes the colors of every pixel with a color matrix, like SVG's feColorMatrix: the new red, green, blue and alpha
are each a sum of the old red, green, blue and alpha times a factor, plus an offset. Grayscale, sepia, tints,
swapped channels, color blindness simulation or a mix of those in one pass
The 9 or 20 values
The values are 20 numbers, four rows of [red, green, blue, alpha, offset] for the new red, green, blue and alpha,
with the colors and the offsets as 0 to 1 (like CSS and SVG): [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] changes nothing, [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0] swaps red and
blue. Nine numbers are the first three rows without the alpha and the offsets (the alpha stays as it is). The
colors are the sRGB values, not premultiplied, and the results are clamped. With a gain map (an HDR image), the
HDR highlights follow the change as they do for other color changes
Makes a color transparent, like GIMP's "Color to Alpha": the color is removed from every pixel and replaced by transparency, so pixels that are partly the color (e.g. antialiased edges against a background) become semi-transparent instead of keeping a fringe of it. The color is removed everywhere in the image, not only from a connected background: removing a white background also makes white areas inside the subject (e.g. eyes in a logo) transparent
Optionaloptions: ColorToAlphaOptions
Composites (overlays) the source onto this image
The image to place
Optionaloptions: CompositeOptions
Position, opacity and blend mode, see CompositeOptions
TypeError if the source isn't an Image
Scales the color channels' distance from mid gray, e.g. 1.5 increases the contrast, 0.5 reduces it
The factor (>= 0, 1 keeps the image, 0 makes it gray)
Crops an image to the specified dimensions. The region is clipped to the image, so the result can be smaller than the requested size
The x offset (0-based)
The y offset (0-based)
The new width
The new height
Crops the image into a circle with an antialiased edge
Image.roundCorners for rounded corners
StaticdecodeDecodes an image (PNG, JPEG, TIFF, WebP, BMP, ICO, CUR, QOI, PBM, PGM, PPM, PAM, PFM, Radiance HDR, TGA, AVIF or JPEG XL)
The binary data to decode
See DecodeOptions. JPEGs, TIFFs, PNGs, WebPs and JPEG XLs are rotated/mirrored as their orientation (Exif, for PNGs also XMP) says by default: photos taken with a rotated camera are stored sideways
The decoded image
For animations (GIFs, animated WebPs, AVIF image sequences, JPEG XL animations) this is the first frame, composed onto the canvas as Animation.decode has it, and decoding stops after it: use Animation.decode for all frames. For APNGs this is the default image, which is what viewers without APNG support show; for icons and cursors it's their largest image
const image = await Image.decode(bytes); // the file's bytes, e.g. from fs.readFile() or fetch()
const webp = await image.resize({ width: 800 }).encodeWebP({ quality: 80 });
LimitError if the image has more than options.maxPixels pixels (checked before its pixels are
allocated)
Gets the image's dominant color: the colors are counted in a histogram of 16 levels per channel, and the average of the pixels in the fullest bin is returned (so it is a color the image has, not a mix of two hues)
Optionaloptions: DominantColorOptions
Which colors to ignore, see DominantColorOptions
The image's dominant color (fully opaque); mostly transparent pixels are ignored. If every pixel is ignored as black or white, the filter is dropped
Image.averageColor for the mix of all colors
Adds a shadow behind the image, shaped by its alpha: a drop shadow with an offset, or a glow without one
(image.dropShadow({ blur: 8, color: 0xff2fb9ff }), with spread to make it stronger). The image grows to fit
the shadow, unless expand is false
See ShadowOptions
LimitError if the size or offset of the shadow would make the image larger than an image can be
Encodes the image as AVIF (AV1, with an alpha image if the image has transparency)
Encodes the image as BMP: with a palette if it is opaque and has at most 256 colors, else with 24 bit pixels, or 32 bit ones if it has transparency
Encodes the image as a GIF (one frame): at most 256 colors, transparency only on or off (pixels with an alpha below 128 become transparent). For animations, see Animation.encodeGIF
The palette size, the dithering and the metadata, see GIFEncodeOptions
Encodes the image into a JPEG. JPEG has no transparency: an image with transparent or translucent pixels is
composited onto the background color (black by default) first, the image itself stays unchanged. An image whose
pixels are all gray is written as a grayscale JPEG (one component)
Optionaloptions: JPEGEncodeOptions
Encodes the image as JPEG XL: losslessly (the default), or lossy with a quality. Alpha (if the image has transparency) is lossless either way. The codestream is in the container, with the metadata as Exif
See JXLEncodeOptions
Lossless works like libjxl's cjxl -e 3 (a palette of up to 1024 colors, else palettes of channels using few of
their values; YCoCg; the weighted predictor in contexts of its error; grayscale if the image is), at effort 0 the
codestream byte for byte like cjxl -e 1 on CPUs with AVX2 or NEON (its fast lossless mode: the gradient predictor,
a palette if the image has at most 511 colors besides black, else YCoCg). Lossy works like cjxl -q: XYB, varblocks
of libjxl's search, chroma from luma, the edge preserving filter
Encodes the image into a PNG, with the smallest lossless color type (a palette for up to 256 colors, grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available, so the compressed bytes can differ between runtimes and browsers; the pixels are the same
Optionaloptions: PNGEncodeOptions
See PNGEncodeOptions
The encoded data
Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for grayscale ones, PPM for others, PAM if the image has transparency
Encodes the image as QOI (3 channels if the image is opaque)
Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)
See TGAEncodeOptions
Encodes the image as WebP: lossless (usually 20-30% smaller than PNG, but slower to encode), or lossy with a quality below 100
Copies a region of the image into a new image and leaves the image unchanged (like Image.crop on a clone, without copying the whole image). The region is clipped to the image, so the result can be smaller than the requested size
The x offset (0-based)
The y offset (0-based)
The region's width
The region's height
Fills the image data with the supplied color. The image's gain map, if it has one, is made neutral (no boost anywhere): the new pixels have no HDR light beyond their own
The color, or a function returning the color of each pixel (checked like any color: a result that isn't a number throws a TypeError, a number that isn't a color a RangeError)
Applies a fisheye (barrel distortion) effect
Optionaloptions: FisheyeOptions
See FisheyeOptions
Flips / mirrors the image horizontally or vertically
The direction to flip, see FlipDirection
Applies a gamma correction, values above 1 brighten the dark tones, values below 1 darken them
The gamma (> 0, 1 keeps the image)
Gets the pixel color at the specified position (0-based). Colors.toRGBA splits it into its channels
The x coordinate (a fraction is dropped: 1.9 is the pixel 1)
The y coordinate (likewise)
The color value (0xRRGGBBAA)
Image.pixels to go over every pixel
Converts the image to grayscale by its luma (ITU-R 601, like Pillow), keeping the alpha
Scales the green channel
The factor to multiply the channel with (>= 0, results are clamped)
Shifts the image's hue
How many degrees to shift the hue by
Inverts the image's colors
Inverts the image's lightness (HSL), keeping hue and saturation: dark colors become light and vice versa
Inverts the image's value (HSV), keeping hue and saturation: the brightest channel v becomes 255 - v
and the others scale along, black becomes white
Scales the lightness of the image (HSL), keeping its hue and saturation
The factor to multiply the lightness with (>= 0, results are clamped)
StaticlinearCreates an image with a linear gradient, like CSS' linear-gradient()
The image's width
The image's height
The colors and the direction, see LinearGradientOptions
The new image
Scales the opacity of the image
The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped)
Draws an outline around the image's shape (its alpha): the sticker effect for cut-out images, or an outline for
text. The image grows to fit it, unless expand is false
See OutlineOptions
LimitError if the width would make the image larger than an image can be
Yields an [x, y, color] array for every pixel in the image (0-based), row by row. Resizing the image meanwhile
doesn't affect the iteration (it goes on over the pixels the image had when pixels() was called), but other changes to the pixels, like
setPixelAt(), are seen by the pixels not yet yielded
Reduces the image to a palette of at most 256 colors (or a fixed one), in place, optionally dithered
See QuantizeOptions
Transparent pixels (alpha 0) keep their color and don't count towards the palette; the other pixels keep their alpha and only their RGB is reduced. The result is deterministic. With a gain map (an HDR image), the HDR highlights are dropped, like Image.invert does: the map is neutral afterwards
StaticradialCreates an image with a radial (circular) gradient, like CSS' radial-gradient(circle)
The image's width
The image's height
The colors and the circle, see RadialGradientOptions
The new image
Sets the RGB of every pixel to the given color, keeping each pixel's own alpha. Turns an image into a silhouette
or tints it: image.recolor(0xffffffff) makes every pixel white, keeping its transparency
The color to use, its alpha is ignored
Sets the RGB of every pixel to the RGB of the same pixel of another image, keeping each pixel's own alpha. With a
gradient this fills a shape with it, e.g. gradient text:
text.recolor(Image.linearGradient(text.width, text.height, { stops: [0x22d3eeff, 0xfb923cff], angle: 90 }))
The image to take the colors from, it has to have the same size. Its alpha is ignored
Scales the red channel
The factor to multiply the channel with (>= 0, results are clamped)
StaticrenderCreates a new image from the given SVG
The SVG content
Optionaloptions: RenderSVGOptions
See RenderSVGOptions
The rendered SVG graphic
Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths, masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs (PNG, JPEG, GIF, WebP, SVG) or given with SVGResourceOptions.images, and text with the given or embedded fonts (see SVGResourceOptions.font). Hrefs are resolved from the options and the data URIs only, never from files or URLs: drawing an image that isn't given, or can't be decoded, throws. SVGs from untrusted sources are fine to render: the size of the output, the layers and the images are limited by the options, and so is the work nested masks, clip paths, patterns, markers and filter images can multiply
const logo = await Image.renderSVG(
'<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><image href="logo.png" width="64" height="64"/></svg>',
{ images: { 'logo.png': logoPNG } } // (the PNG's bytes, e.g. from a fetch or a file you read)
);
LimitError if the output, the layers or the images exceed the limits of the options, or the SVG
exceeds a fixed limit of the work it may take: more than 100000 elements drawn through <use> references and
markers, more than 10000 markers, masks, clip paths, patterns, markers and filter images nested so deeply that
they would multiply, entities that expand past the size limit, or filters past their budget
StaticrenderCreates a new image containing the rendered text
Text to render
The font and size, color, layout and style, see RenderTextOptions. Without a width or
height, the image grows by the outline width on every side; with one, it has exactly that size
The rendered text
const label = await Image.renderText('Hello, world', { font: fontBytes, size: 48, color: 0xffffffff });
LimitError if the image would have more than options.maxPixels pixels (checked before anything is
allocated)
Resizes the image to the given dimensions. Pass ResizeToOptions with only a width or a height to keep the aspect ratio.
The new width
The new height
Optionaloptions: ResizeOptions
See ResizeOptions
The resized image
Resizes the image: to the given width or height (the other side keeps the aspect ratio), or to both
The size and how to resize, see ResizeToOptions
The resized image
Rotates the image clockwise by the given angle in degrees (like CSS' rotate(); negative angles turn it
counterclockwise). Multiples of 90° move whole pixels; other angles resample the image (see
RotateOptions.mode). By default the image grows so the corners fit (a quarter turn swaps width and
height); with expand: false it keeps its size, also for quarter turns, and what doesn't fit is cut off
The angle in degrees, clockwise
Optionaloptions: RotateOptions
See RotateOptions
image.rotate(90); // a quarter turn clockwise: width and height swap
image.rotate(-15, { expand: false }); // 15° counterclockwise, the size stays and the corners are cut off
Image.transform for skews, flips and shifts
Rounds the image's corners, with antialiased edges
Optionaloptions: RoundCornersOptions
Image.cropCircle for a circle
Scales the saturation of the image (HSL), keeping its hue and lightness. 0 makes it grayscale
The factor to multiply the saturation with (>= 0, results are clamped)
Resizes the image by the given factor: a side of 7 pixels scaled by 0.5 is 3 (fractions are dropped, a side doesn't go below 1 pixel)
The factor to resize the image with
Optionaloptions: ResizeOptions
See ResizeOptions
Applies a sepia tone
Sharpens the image with an unsharp mask: the difference to a blurred copy is amplified
Optionaloptions: SharpenOptions
See SharpenOptions
A short description for debugging, e.g. Image<64x64>
Moves every point of the image with an affine transform, in one resampling: rotation, scaling, skew, flips and shifts in any mix and around any point
The six values [a, b, c, d, e, f]
See TransformOptions
The six numbers are SVG's matrix(a b c d e f): a point (x, y) of the image ends up at (a x + c y + e,
b x + d y + f), with y pointing down. The image grows to hold the result (expand: false keeps its size), so a shift
only shows with expand: false. The edges fade, like the pixels outside were transparent. A transform that flattens
the image (a factor of 0) is refused. With a gain map (an HDR image), the map moves with the image
image.transform([1, 0, Math.tan(-0.3), 1, 0, 0]); // slanted like italics, around the middle
image.transform([0.5, 0, 0, 0.5, 0, 0], { origin: { x: 0, y: 0 } }); // half the size
image.transform([-1, 0, 0, 1, 0, 0]); // flipped horizontally
const a = Math.PI / 6;
image.transform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); // turned 30° clockwise
Image.rotate for turning by an angle
Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background. An image that only has the color stays unchanged (Frame.trim also moves the frame's offsets)
Optionaloptions: TrimOptions
See TrimOptions
An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place and return it, so calls can be chained
Remarks
Subclassing is not supported: the methods that make an image (Image.clone, Image.extract, Image.decode, ...) return plain
Images, without calling a subclass' constructor.The
maxPixelslimits guard what comes from outside: decoding and rendering.new Image(),resize()andscale()make the size they are asked for, so check sizes that come from users before you pass them on