Repository navigation
Releases
3.20.4
3.20.4
Deprecated
The deprecation hints now lead to the names 4.0 uses, and 3.x takes those names already. 4.0 ignores an option it
doesn't know, so code that followed the earlier hints (cropCircle({ size: 'cover' })) would have changed its output
there without an error:
cropCircle({ fit }): thesizeoption is deprecated,fitis its name in 4.0. The hint ofcropCircle(max, feathering)and of themaxoption now namesfit.Image.renderSVG(svg, { width }),{ height }and{ scale }: thesizeandmodeoptions (andSVGScaleMode,SVGScaleModes) are deprecated, these are their names in 4.0. Only one of the three can be given.{ font }(one font or an array) is the 4.0 name offonts, which is deprecated.RenderSVGOptionsis the 4.0 name ofSVGOptions.new GainMap(image, { min, max })andmap.min,map.max: the 4.0 names ofgainMapMinandgainMapMax, which are deprecated.ResizeModes,FrameDisposalModesand the constantsImage.RESIZE_*,Frame.DISPOSAL_*andImage.SVG_MODE_*point to the names 4.0 uses ('bicubic','background',{ width }): 4.0 removes the classes too.FrameDisposalModeis the 4.0 name ofFrameDisposalModeName.
4.0.0-rc.5
ImageScript 4.0.0-rc.5
The fifth release candidate for ImageScript 4.0 is ready for evaluation. This is a major release with breaking API
changes from 3.x. Before upgrading, update to the latest 3.x release (3.20.3) and address its deprecation warnings, then
follow the migration guide.
This release candidate fixes values of the wrong type that were still accepted, cut-off and damaged files, right-to-left text and a few SVG and encoder details.
Breaking changes since rc.4
- Right-to-left text is aligned to the right by default:
horizontalAligndefaults to the start of each
paragraph's direction (like CSS'text-align: start). PasshorizontalAlign: 'left'for the old placement. - Cut-off JPEG and lossy WebP files throw like the other formats, where they decoded as gray or smeared images. A
JPEG that only lacks its end marker still decodes. - Boolean options take
trueorfalseonly:optimize: 'yes',applyOrientation: 'no',hinting,
ignoreBlack,ignoreWhite,sharpYuv,expandand the decoders'gainMapthrow aTypeError(a string was read
astrue). - A value that isn't a number where one goes is a
TypeErroreverywhere:transform('matrix(...)'),
colorMatrix()without an argument, fontfeaturesandvariations,renderText({ width: '300' }), the canvas size
of the streaming encoders,transform({ origin: null }),new Animation(5), and binary data that isn't any.
Metadata text fields have to be strings (title: 123was written as'123'). - Options are objects: an array as options throws like a number or a string, and so does a
metadatathat isn't
an object. - More values are checked:
dominantColor({ threshold })outside 0-256,GainMap.encodeJPEG({ quality: 0 }), the
encoders'gainMap: { quality, scale }also for images without a gain map,alphaQualityofencodeWebP()also for
lossless images,renderSVG()withwidth: nullorscale: null, andnew Colors(). - Gain map capacities are checked when they are set:
map.hdrCapacityMax = -0.5throws and keeps the old value
(it was accepted, thenclone()and the encoders threw). A one-element array for a channel value throws. JSON.stringify()andconsole.log()of anImage,FrameorAnimationshow their size (and duration), not
every pixel.
Fixes
image.composite(image, { x, y })onto itself (or an image sharing its pixels) gives the same result as compositing
a copy.Image.pixels()yields the pixels the image had when the iteration started, also when the image is resized meanwhile.Animation.decode()gives still images a frame of 100 ms, theFramedefault, not 0 ms.- PNG chunks with a bad checksum are skipped when they hold color or text metadata, like libpng and browsers (files
from the pngrs and Pillow test suites were refused); the image's own chunks still throw. - A JPEG scan with restart markers carries on after corrupt data at the next marker, like libjpeg.
encodeBMP()of a fully transparent image decodes to transparent pixels (3.x and rc.4 made them opaque).- Wrapped right-to-left lines with
horizontalAlign: 'left'or'center'are placed by their ink, not shifted by the
space at the wrap point. renderSVG()of an SVG with aviewBoxand only one ofwidthandheightsizes the other side by the aspect
ratio, like browsers (it letterboxed the content).encodeJPEG()writes gray images as grayscale JPEGs (one component, a few percent smaller).software: nullwithout other metadata writes no empty Exif block.
Performance
- Lossy JPEG XL encoding starts no worker threads below 1.5 megapixels with fewer than 4 threads, where they took
1.3-1.7x as long as one.
Documentation
- The migration guide lists the right-to-left default,
JSON.stringify(), boolean options and cut-off files among the
behavior changes (seventeen now). - README: CommonJS projects with
module: nodenextneed TypeScript 5.8 or newer;bun buildneeds the worker module
served like esbuild and webpack; CCITT-compressed TIFF and arithmetic-coded JPEG aren't supported.
Known limits
- TypeScript 5.7 or newer is needed (older versions can't read the
Uint8Array<ArrayBuffer>return types). - Single-file bundles (esbuild, webpack,
bun build) and CDN builds served from another origin run without worker
threads: the output is identical, only slower. Servedist/util/worker.jsnext to the bundle for threads. - The default
maxPixels(16383 x 16383) still allows a GIF of 300 bytes to allocate a 1 GB canvas.
Feedback on this release candidate is welcome: open an issue.
4.0.0-rc.4
ImageScript 4.0.0-rc.4
The fourth release candidate for ImageScript 4.0 is ready for evaluation. This is a major release with breaking API
changes from 3.x. Before upgrading, update to the latest 3.x release (3.20.3) and address its deprecation warnings, then
follow the migration guide.
This release candidate comes out of a full pre-release check of the public API, the packaging, the runtimes and about
370,000 fuzzed decodes. It fixes what that found, and makes the remaining numeric arguments behave like the rest.
Breaking changes since rc.3
- Renamed: the
sizeoption ofcropCircle()isfit('contain'or'cover'), likeresize()'s. Out-of-range
feathering(outside 0-1) throws instead of being clamped. - Numbers have to be numbers, everywhere: a numeric string (
opacity('0.5'),quality: '50',scale('2'),
frame.duration = '40'),nullor a boolean where a number goes is aTypeError. 3.x converted them in some methods
and rejected them in others; rc.3 still accepted a few.NaNand the infinities are aRangeError. - Values that did nothing useful throw:
roundCorners({ radius })below 0 (it was clamped to 0),fisheye({ strength })
of 0 or less (an empty image), andrenderText({ size: 0 })(a 1x1 image). - Gradients blend transparency premultiplied, like CSS: a gradient from transparent to red is
ff00007fin the
middle, no longer a dark7f00007f. Gradients between opaque colors are unchanged. image.gainMap = mapstores a copy, so images given one map no longer change each other's by resizing or cropping.resize({ background })is only typed withfit: 'contain'(it was ignored otherwise).Animation.resize()andscale()size the canvas likeImagedoes: sides are cut to whole pixels, andscale()
never goes below one pixel.- Cut-off animations keep the frames that arrived whole, and throw when none did: a GIF cut before its first frame
decoded as a blank image, and the last frame of a cut GIF, lossy WebP or lossy JPEG XL animation was half decoded.
A cut APNG showed only its first frame. - A canvas that doesn't fit the format throws: GIF over 65535 pixels (70000 was written as 4464), and an animation
without a canvas.
Security and robustness
- SVG strokes with round joins took 9 s and 1 GB for a 17 KB path (2.7 GB for 50 KB): a join was a whole circle at every
vertex of a flattened curve. Joins are wedges now (1.6 s and 220 MB), and a render stops with aLimitErroronce its
shapes' edges cross the rows of the image more than 2^27 times (thousands of huge overlapping strokes took 38 s). - A million dashes (157 bytes of SVG) took 650 MB: dashes beside the image are left out and the rest are stroked in
batches. Text of 20000 glyphs took 15 s and now 0.4 s, 8000 random curves 18 s and now 2.3 s. - TIFF files that ask for far more memory than they are (YCbCr subsampling of 65534x65535: 4 GB for 32 KB; 1024
samples per pixel: 1 GB for 33 KB) are refused before anything is allocated. - Decoding an animation takes 1.3 times the result's memory, not 2.2 (APNG and WebP composite each frame as it is
decoded).dropShadow()andoutline()throw aLimitErrorfor sizes an image can't have. - Damaged JPEG, TIFF, GIF and TGA headers are decoding errors, where some read missing bytes or threw a
RangeError.
Fixes
- Bundlers keep only what a page uses:
import { Colors }bundled the whole library (201 kB minified); it is 3.4 kB now,
because the build'sdist/package.jsonno longer hides"sideEffects": false. Animation.resize()changes a frame once when an animation lists it more than once, resizes frames that share an
image at different offsets to their own sizes, and throws below one pixel.Animation.decode()of a JPEG XL animation counts all frames againstmaxPixels.resize({ fit: 'cover' })andfill(fn)leave the image and its gain map untouched when they throw.- The animation encoders cut frames to the canvas like
Animation.encode*()does withoptimize: false;add()rejects
its promise for invalid frames;Colors.gradient()with one color throws forNaN. - Documentation: the README, the migration guide and the doc comments match the behavior (counts, error types, defaults).
Performance
Against 3.20.3 and rc.3, one build per process on a 1920x1080 photo, nothing changed beyond noise except: animated WebP
decode is 4.6% slower than rc.3 (the price of the lower memory), and quantize() with its new default dithering is
3.3 times slower than 3.x's (dither: 'none' is equal).
Known limits
- TypeScript 5.7 or newer is needed (older versions can't read the
Uint8Array<ArrayBuffer>return types). - Single-file bundles (esbuild, webpack) and CDN builds served from another origin run without worker threads: the
output is identical, only slower. Servedist/util/worker.jsnext to the bundle for threads. - The default
maxPixels(16383 x 16383) still allows a GIF of 300 bytes to allocate a 1 GB canvas.
Feedback on this release candidate is welcome: open an issue.
4.0.0-rc.3
ImageScript 4.0.0-rc.3
The third release candidate for ImageScript 4.0 is ready for evaluation. This is a major release with breaking API
changes from 3.x. Before upgrading, update to the latest 3.x release (3.20.3) and address its deprecation warnings, then
follow the migration guide.
This release candidate hardens SVG rendering against untrusted input and settles the last API changes before 4.0.
Security
Untrusted SVG input is supported, and these SVGs of a few hundred bytes could block the thread indefinitely in rc.2:
- Shapes far outside the image (
<circle r="1e9"/>, a hugescale()or arc) made the rasterizer hang. They render
normally now. feTurbulence numOctaveshad no limit, so one attribute could make a filter take weeks. It stops at 24 octaves,
which is all its output can show.- Masks, clip paths, patterns, markers and filter images nested in each other multiplied their work (three per
level took minutes at ten levels). Like<use>, they now share a budget:renderSVG()throws once a document would
take too long. transformlists are parsed in linear time; a long, unclosed one took quadratic time.
Breaking changes since rc.2
- Renamed:
GainMap.encode()isGainMap.encodeJPEG(), and thefontsoption ofrenderSVG()isfont, like
renderText()'s. renderText()takeswidthandheightinstead ofmaxWidthandmaxHeight. They set the image's size:
lines wrap to the width and are aligned in the box.wrapHardBreaksis removed.dominantColor()counts colors in a histogram (16 levels per channel, like sharp's) and returns the average of
the fullest bin, so the result is always a color the image has. Itsthresholdis in channel values (0-256): the
default60is 3.x's15.rotate(angle, { expand: false })keeps the size for quarter turns too: the turned image is centered and cropped
instead of swapping width and height.- Removed:
coordinates()(usepixels(), deprecated in 3.20.3), and thefastoption ofresize()and
scale()(resizing always takes the fast path). - More values throw: an out-of-range JPEG
quality(0-100, it was clamped), and acomposite()source that isn't
anImage. - Types:
RenderSVGOptionsis a union of the sizes (width,heightorscale), with the limits, fonts and
images inSVGResourceOptions.QuantizeOptionstakes eithercolorsorpalette. The animation encoders' option
types extend the still-image ones.AnimationEncoderhas no public constructor; create one with
Animation.webpEncoder(),gifEncoder()orapngEncoder().
New
Animation.flip(), which mirrors each frame and its place on the canvas, and theFlipDirectiontype.LimitErroris exported (name'LimitError'), so a "too large" error can be told apart from otherRangeErrors.GainMap.decode(data, { maxPixels })takes the limit ofImage.decode().metadata: { creationTime: null, software: null }leaves those fields out of the file.
Fixes
Animation.resize(),scale(),crop(),trim()andflip()change a frame once when the animation lists it more
than once (a hold or ping-pong). Before, it was resized or moved once per listing.- The streaming encoders cut frames to the canvas like
Animation.encode*()does. Withoptimize: false, parts outside
the canvas were dropped, or threw for APNG. AnimationEncoder.add()rejects its promise instead of throwing synchronously.Image.linearGradient()andradialGradient()work with fractional sizes; they threw aRangeError.scale()keeps each side at least one pixel, likeresize().- A damaged JPEG XL with an invalid blend channel throws a decoding error instead of a raw
TypeError. - Gain map value checks name the values that conflict.
The minimum TypeScript version is 5.7, now stated in the README.
See the migration guide
for the full list of removed and reshaped APIs, behavior changes, and migration examples.
3.20.3
3.20.3
Deprecated
image.coordinates()is deprecated and will be removed in 4.0, like iterating over the image (for (const [x, y] of image)), which now points topixels()instead ofcoordinates(). Usefor (const [x, y] of image.pixels()):pixels()yields[x, y, color], so the color comes with the position.
4.0.0-rc.2
ImageScript 4.0.0-rc.2
The second release candidate for ImageScript 4.0 is ready for evaluation. This is a major release with breaking API
changes from 3.x. Before upgrading, update to the latest 3.x release and address its deprecation warnings, then follow
the migration guide.
What changed
-
Values that were wrapped, clamped or ignored throw: colors have to be integers from -2^31 to 2^32 - 1, also the ones a
fill()function returns (they wrapped to 32 bits; negative ones, which bitwise operators return, keep working); pixel coordinates are truncated without wrapping at 2^32;compressionis an integer 0-9 likeeffort(it was clamped); frame durations that GIF, APNG or WebP can't store throw aRangeErrorlike loop counts (they were cut; unchanged frames merged by the encoders are split at the limit);frame.xOffsetandframe.yOffsetare truncated to integers when set;image.bitmap = viewthrows aTypeErrorfor a view that doesn't start at a multiple of 4 bytes (it was copied, so changes to the view were lost);Colors.gradient()throws for aNaNposition with any number of stops;encodeGIF()of an animation without frames throws like the other encoders. -
Invalid choices throw a
TypeErrornaming the valid ones: the resizemode(anError, thrown once resizing started, soresize({ fit: 'cover' })could move a frame's offsets before failing),composite()'smode,flip(),disposalModeandwrapStyle(RangeErrors; an empty ornullwrapStylewas the default). -
No creation time and no version in encoded files by default: the encoders only write a creation time when
metadata.creationTimeis given, so the same image encodes to the same bytes, and the default software is'ImageScript'without the version. -
Drawing an SVG image that can't be drawn throws: an
hrefthat isn't a data URI or one of theimages, an image that can't be decoded (with the decoding error as itscause), an unsupported data URI type or an embedded SVG that can't be read throw once they are drawn (images in<defs>or hidden ones don't); they drew nothing before. -
renderSVG({ maxLayerPixels })limits the layers SVG rendering uses at once (groups with opacity, masks, filters, ...; 16 bytes per pixel each), so nested ones can't multiply the memory of a small SVG: default4 * maxPixels.renderSVG({ maxImagePixels })limits the raster images an SVG references together (defaultmaxPixels; each was limited on its own before). -
renderText({ maxPixels }), default 16383², counting the outline, checked before anything is allocated.
See the migration guide for the full list of removed and reshaped APIs, behavior
changes, and migration examples.
4.0.0-rc.1
ImageScript 4.0.0-rc.1
The first release candidate for ImageScript 4.0 is ready for evaluation. This is a major release with breaking API
changes from 3.x. Before upgrading, update to the latest 3.x release and address its deprecation warnings, then follow
the migration guide.
What changed
- A more consistent API: methods that take options now use options objects instead of positional arguments.
Resize modes and frame disposal modes are plain strings; color conversion helpers are grouped underColors. - Unified frames and animations:
Framenow contains anImageatframe.image;Animationstores frames in
animation.framesinstead of extendingArray. The separateGIFclass is replaced byAnimation. - Flexible resizing:
resize({ width, height, fit })supports stretching, aspect-preservinginside, padded
contain, and croppedcoverbehavior on images, frames, and animations. - More predictable animation handling:
decode()recognizes animation markers, including one-frame animations;
Image.decode()returns the first frame. Infinite looping is represented byInfinityinstead of-1. - Behavior changes to check:
rotate()now turns clockwise; HSL hue values use degrees; JPEG encoding composites
transparency onto black by default;quantize()dithers by default; and size-changing operations onFramemove
its offsets to keep it positioned in the animation. - Expanded encoding and image operations: single images can encode as GIF, GIF encoders expose color-count and
dithering options, animations gain more image operations, and SVG rendering accepts fonts and embedded images. - Tighter types and validation: fixed-length tuple types, checked frame and gain-map values, and
Promise<Uint8Array<ArrayBuffer>>encoder results improve type safety. The encoder result type requires TypeScript
5.7 or newer.
See the migration guide for the full list of removed and reshaped APIs, behavior
changes, and migration examples.
3.20.2
Fixes
- Loop counts that don't fit the file format are refused with a
RangeErrornaming the format's largest count, instead of wrapping around: a GIF withloopCount: 65536was written with 0, which plays forever (GIF and animated WebP store up to 65535 and 65534, APNG up to 2147483646). This applies toencodeGIF(),encodeWebP()andencodeAPNG()of animations and to the streaming encoders.
3.20.1
Performance
- Drawing on an image with a gain map (an HDR photo) is much faster:
drawBox()anddrawCircle()only recompute the part of the map they cover, instead of the whole map for every call. 400 scanlines over a 1820x1820 Ultra HDR photo take 0.3 s instead of 5.8 s, with the same result. composite()onto or from an image with a gain map is up to twice as fast: 1820x1820 with a blend mode like'add'takes 0.22 s instead of 0.48 s, with the same result. Gain maps stay in sync with the pixels as before.
3.20.0
New
image.quantize({ colors, palette, dither, ditherStrength }): reduces the image to a palette, in place:image.quantize({ colors: 16 })for the 16 colors that best represent it, or a fixed one:image.quantize({ palette: [0x0f380fff, 0x306230ff, 0x8bac0fff, 0x9bbc0fff] })for a Game Boy look.dither: 'floyd-steinberg'(or'atkinson', or'ordered'for a regular pattern) makes gradients look smooth with few colors. Transparent pixels keep their color and don't count towards the palette.Image.renderSVG(svg, { images }): images for the<image>elements by theirhref, without data URIs:Image.renderSVG('<svg ...><image href="logo.png" .../></svg>', { images: { 'logo.png': bytes } }). The values are encoded images orImages; they are decoded only when the SVG uses them. Nothing is read from files or URLs.image.colorMatrix(matrix): mixes the colors of every pixel with a color matrix, like SVG'sfeColorMatrix: greyscale, sepia, tints, swapped channels, color blindness simulation or any mix of them in one pass. Twenty values (four rows of[red, green, blue, alpha, offset], 0 to 1) or nine for just the colors:image.colorMatrix([0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0])swaps red and blue.image.transform(matrix, { origin, expand, mode }): 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 are SVG'smatrix(a b c d e f):image.transform([1, 0, -0.3, 1, 0, 0])slants an image like italics. The image grows to hold the result unlessexpand: false, andmodeis'nearest-neighbor','bilinear'(default) or'bicubic'.