imagescript 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,80 +7,17 @@
7
7
 
8
8
  ---
9
9
 
10
- **ImageScript** is a zero-dependency alternative to common JavaScript bitmap image manipulation tools. Every codec and
11
- renderer is written in TypeScript: no WebAssembly, no native binaries, no npm dependencies, no install scripts. The
12
- package is about 160 kB (compressed) and runs in Node.js 22.13 or newer (including Alpine/musl, ARM and bundled
13
- serverless functions), Deno, Bun and browsers. It works with both `import` and `require()`, type definitions are included.
10
+ **ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, no
11
+ dependencies. It runs in Node.js 22.13+, Deno, Bun and browsers, with `import` or `require()`, and includes type
12
+ definitions.
14
13
 
15
14
  ```sh
16
15
  npm install imagescript # Node.js, Bun and bundlers
17
- deno add jsr:@matmen/imagescript # Deno (npm:imagescript works too)
16
+ deno add jsr:@matmen/imagescript # Deno
18
17
  ```
19
18
 
20
19
  ---
21
20
 
22
- ### Features
23
-
24
- - [Decoding images](https://imagescript.matmen.dev/classes/Image.html#decode)
25
- - PNGs (grayscale, RGB, indexed colors, 1-16 bit, interlaced) with and without alpha channels
26
- - JPEGs (baseline and progressive; grayscale, RGB, CMYK)
27
- - TIFFs (strips and tiles; uncompressed, LZW, deflate, PackBits and JPEG compressed; BigTIFF)
28
- - WebPs (lossy, lossless and with alpha; bit-exact with libwebp)
29
- - BMPs (1-64 bit, with any channel masks, alpha, RLE4 and RLE8, embedded JPEGs and PNGs; also OS/2 bitmaps)
30
- - ICOs and CURs (the largest image: bitmaps with their masks, or PNGs)
31
- - QOIs
32
- - Netpbm images: PBM, PGM, PPM (plain and raw, up to 16 bits), PAM and PFM
33
- - Radiance HDRs (RGBE and XYZE, every orientation), tone mapped to sRGB like Reinhard's operator does (or clamped,
34
- `toneMapping`)
35
- - TGAs (color mapped, truecolor and greyscale; uncompressed and run length encoded)
36
- - AVIFs (4:2:0, 4:2:2, 4:4:4 and monochrome, 8-12 bit; grids, alpha, crop, rotation and mirroring; the first frame
37
- of image sequences; bit-exact with dav1d and libavif), HDR ones (PQ, HLG) tone mapped to sRGB
38
- - JPEG XLs (Modular and VarDCT, lossless and lossy, every coding tool: progressive passes and LF frames, patches,
39
- splines, noise, restoration filters, upsampling, JPEG recompression, layers and blending, alpha and spot colors,
40
- CMYK; animations; within 1 of libjxl's djxl on the conformance suite), XYB ones as sRGB, HDR ones tone mapped to
41
- sRGB
42
- - JPEGs, TIFFs, PNGs and WebPs are rotated as their Exif (or, for PNGs, XMP) orientation says
43
- - images larger than 268 megapixels (`maxPixels`) are rejected before decoding, so small files declaring huge images
44
- can't exhaust the memory
45
- - [Decoding animations](https://imagescript.matmen.dev/classes/Animation.html#decode) (GIF, APNG, WebP and JPEG XL) with all
46
- frames, durations and disposal modes
47
- - [Rendering SVGs](https://imagescript.matmen.dev/classes/Image.html#rendersvg) (shapes, paths, gradients, strokes, clip paths,
48
- masks, CSS; no text, images or filters)
49
- - [Rendering vector fonts](https://imagescript.matmen.dev/classes/Image.html#rendertext) (TrueType and OpenType, with
50
- complex text shaping in every script, right to left and bidirectional text, outlines, TrueType hinting, fallback
51
- fonts and color emoji)
52
- - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize) (bilinear, bicubic, area averaging and nearest neighbor)
53
- - Image manipulation functions ([crop](https://imagescript.matmen.dev/classes/Image.html#crop)
54
- , [rotate](https://imagescript.matmen.dev/classes/Image.html#rotate)
55
- , [cropCircle](https://imagescript.matmen.dev/classes/Image.html#cropcircle)
56
- , [roundCorners](https://imagescript.matmen.dev/classes/Image.html#roundcorners)
57
- , [trim](https://imagescript.matmen.dev/classes/Image.html#trim), ...)
58
- - Filters and color adjustments ([blur](https://imagescript.matmen.dev/classes/Image.html#blur)
59
- , [sharpen](https://imagescript.matmen.dev/classes/Image.html#sharpen)
60
- , [brightness](https://imagescript.matmen.dev/classes/Image.html#brightness)
61
- , [hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...)
62
- - Compositing with opacity and blend modes ([composite](https://imagescript.matmen.dev/classes/Image.html#composite)),
63
- removing backgrounds ([colorToAlpha](https://imagescript.matmen.dev/classes/Image.html#colortoalpha))
64
- - Color information functions ([averageColor](https://imagescript.matmen.dev/classes/Image.html#averagecolor)
65
- , [dominantColor](https://imagescript.matmen.dev/classes/Image.html#dominantcolor), ...)
66
- - Encoding images as [PNGs](https://imagescript.matmen.dev/classes/Image.html#encode) (smallest lossless color type)
67
- , [JPEGs](https://imagescript.matmen.dev/classes/Image.html#encodejpeg)
68
- , lossless and lossy [WebPs](https://imagescript.matmen.dev/classes/Image.html#encodewebp) (lossy ones byte for
69
- byte like libwebp's cwebp)
70
- , [AVIFs](https://imagescript.matmen.dev/classes/Image.html#encodeavif) (lossy and lossless, with alpha)
71
- , [JPEG XLs](https://imagescript.matmen.dev/classes/Image.html#encodejxl) (lossless byte for byte like libjxl's
72
- `cjxl -e 1`, lossy about as small as `cjxl -e 5`)
73
- , [BMPs](https://imagescript.matmen.dev/classes/Image.html#encodebmp)
74
- , [QOIs](https://imagescript.matmen.dev/classes/Image.html#encodeqoi)
75
- , [Netpbm images](https://imagescript.matmen.dev/classes/Image.html#encodepnm) (PBM, PGM, PPM or PAM, whichever is
76
- smallest)
77
- and [TGAs](https://imagescript.matmen.dev/classes/Image.html#encodetga)
78
- - Encoding animations as [GIF](https://imagescript.matmen.dev/classes/Animation.html#encodegif),
79
- [APNG](https://imagescript.matmen.dev/classes/Animation.html#encodeapng) and lossless or lossy
80
- [WebP](https://imagescript.matmen.dev/classes/Animation.html#encodewebp), storing only what changes from frame to frame
81
-
82
- ---
83
-
84
21
  ### Example
85
22
 
86
23
  ```js
@@ -92,47 +29,59 @@ image.resize(256, Image.RESIZE_AUTO).roundCorners(16);
92
29
  await writeFile('output.png', await image.encode());
93
30
  ```
94
31
 
95
- With CommonJS:
96
-
97
- ```js
98
- const { Image } = require('imagescript');
99
- ```
100
-
101
- All coordinates are 0-based, `(0, 0)` is the top left pixel.
102
-
103
- A bigger example is the [README image generation](https://github.com/matmen/ImageScript/blob/master/tests/readme.js).
104
- Upgrading from 1.x? Version 3 has breaking changes (0-based coordinates, lossy WebP encoding as `encodeWebP({ quality })`,
105
- Node.js 22.13+, ...), see the [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md).
32
+ Coordinates are 0-based, `(0, 0)` is the top left pixel. A bigger example is the
33
+ [README image generation](https://github.com/matmen/ImageScript/blob/master/tests/readme.js):
106
34
 
107
35
  [![Example](https://github.com/matmen/ImageScript/raw/master/tests/targets/readme.png)](https://github.com/matmen/ImageScript/blob/master/tests/readme.js)
108
36
 
109
37
  ---
110
38
 
111
- ### Benchmarks
39
+ ### Features
112
40
 
113
- [bench/](bench/README.md) compares ImageScript to Jimp, image-js, Photon, sharp and @napi-rs/canvas: speed of decoding,
114
- encoding, image operations and rendering, encoded file sizes and install sizes. It runs for every release.
41
+ | Format | Decode | Encode |
42
+ |---|---|---|
43
+ | PNG | ✓ | ✓ |
44
+ | JPEG | ✓ | ✓ |
45
+ | WebP | ✓ | ✓ (lossless and lossy) |
46
+ | AVIF | ✓ | ✓ (lossless and lossy) |
47
+ | JPEG XL | ✓ | ✓ (lossless and lossy) |
48
+ | GIF, APNG (animations) | ✓ | ✓ |
49
+ | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
50
+ | TIFF, ICO/CUR, Radiance HDR | ✓ | |
51
+
52
+ Animated WebPs and JPEG XLs decode too, and [animations](https://imagescript.matmen.dev/classes/Animation.html)
53
+ encode as GIF, APNG or WebP, also [a frame at a time](https://imagescript.matmen.dev/classes/Animation.html#webpencoder).
54
+
55
+ - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts,
56
+ in every script, with color emoji
57
+ - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg) (no text)
58
+ - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
59
+ [cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
60
+ [rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
61
+ [trimming](https://imagescript.matmen.dev/classes/Image.html#trim),
62
+ [rounded corners](https://imagescript.matmen.dev/classes/Image.html#roundcorners), ...
63
+ - [Compositing](https://imagescript.matmen.dev/classes/Image.html#composite) with opacity and blend modes
64
+ - Filters and color adjustments: [blur](https://imagescript.matmen.dev/classes/Image.html#blur),
65
+ [sharpen](https://imagescript.matmen.dev/classes/Image.html#sharpen),
66
+ [brightness](https://imagescript.matmen.dev/classes/Image.html#brightness),
67
+ [hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...
68
+
69
+ See the [documentation](https://imagescript.matmen.dev/) for everything else, and the
70
+ [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md) when upgrading from an older major version.
71
+ [bench/](bench/README.md) compares ImageScript to Jimp, sharp and others.
115
72
 
116
73
  ---
117
74
 
118
75
  ### Credits
119
76
 
120
- The deflate/inflate implementation is derived from [fflate](https://github.com/101arrowz/fflate) and the CRC-32 from
121
- [Fast CRC32 in JavaScript](https://gist.github.com/101arrowz/e58695f7ccfdf74f60ba22018093edea), both by Arjun Barrett.
122
- The JPEG codec is based in part on the work of the Independent JPEG Group (libjpeg) and on
123
- [pdf.js](https://github.com/mozilla/pdf.js), the glyph rasterizer is translated from
124
- [font-rs](https://github.com/raphlinus/font-rs). The WebP codecs follow [RFC 9649](https://www.rfc-editor.org/rfc/rfc9649) and [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386)
125
- and reproduce [libwebp](https://chromium.googlesource.com/webm/libwebp)'s color conversion, the lossy WebP encoder is
126
- ported from libwebp's, the TrueType hinting follows
127
- [FreeType](https://freetype.org)'s interpreter (portions of this software are copyright © 2026 The FreeType Project),
128
- the text shaping is ported from [HarfBuzz](https://github.com/harfbuzz/harfbuzz) and uses data of the
129
- [Unicode Character Database](https://www.unicode.org/ucd/). The AV1 decoder is ported from
130
- [dav1d](https://code.videolan.org/videolan/dav1d), AVIFs are converted to RGB like
131
- [libavif](https://github.com/AOMediaCodec/libavif) does, the JPEG XL decoder is ported from
132
- [jxl-oxide](https://github.com/tirr-c/jxl-oxide) and [libjxl](https://github.com/libjxl/libjxl), the JPEG XL encoders
133
- follow libjxl's fast lossless encoder and its lossy heuristics, the AV1 encoder mirrors the decoder and uses libaom's symbol encoder.
134
- See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for their licenses.
77
+ ImageScript builds on [fflate](https://github.com/101arrowz/fflate), libjpeg, [pdf.js](https://github.com/mozilla/pdf.js),
78
+ [font-rs](https://github.com/raphlinus/font-rs), [libwebp](https://chromium.googlesource.com/webm/libwebp),
79
+ [HarfBuzz](https://github.com/harfbuzz/harfbuzz), [dav1d](https://code.videolan.org/videolan/dav1d),
80
+ [libavif](https://github.com/AOMediaCodec/libavif), libaom, [jxl-oxide](https://github.com/tirr-c/jxl-oxide) and
81
+ [libjxl](https://github.com/libjxl/libjxl). The TrueType hinting follows [FreeType](https://freetype.org): portions of
82
+ this software are copyright © 2026 The FreeType Project (www.freetype.org). All rights reserved. See
83
+ [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for the licenses.
135
84
 
136
85
  ---
137
86
 
138
- If you have any additional questions, feel free to join the [discord support server](https://discord.gg/8hPrwAH).
87
+ Questions? Join the [Discord server](https://discord.gg/8hPrwAH).
@@ -12,18 +12,22 @@ following projects, under their own licenses. Each derived file says so in its h
12
12
  | [font-rs](https://github.com/raphlinus/font-rs) by Raph Levien | `src/render/text.ts` (the `Rasterizer` class, also used for SVGs) | Apache-2.0 |
13
13
  | [RFC 9649](https://www.rfc-editor.org/rfc/rfc9649) (WebP Image Format) | `src/codecs/vp8l.ts` (lossless bitstream, short distance code table), `src/codecs/webp.ts` (container) | BSD-3-Clause (Revised BSD) |
14
14
  | [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386) (VP8 Data Format and Decoding Guide, with the libvpx reference decoder) | `src/codecs/vp8-tables.ts` (probability and quantizer tables), `src/codecs/vp8.ts` (decoding procedures) | BSD-3-Clause |
15
- | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`) | BSD-3-Clause |
15
+ | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`), `src/codecs/sharpyuv.ts` (the sharp RGB to YUV conversion, libsharpyuv) | BSD-3-Clause |
16
16
  | [dav1d](https://code.videolan.org/videolan/dav1d) by VideoLAN, the dav1d authors and Two Orioles | `src/codecs/av1/*` (the AV1 decoder, and the encoder's syntax, contexts and reconstruction mirrored from it: bitstream parsing, symbol decoding, prediction, inverse transforms, loop filters, film grain; the tables in `src/codecs/av1/data.ts`, generated from dav1d by `scripts/av1-tables.c`) | BSD-2-Clause |
17
17
  | [libaom](https://aomedia.googlesource.com/aom/) by the Alliance for Open Media | `src/codecs/av1/msac-enc.ts` (the symbol encoder), `src/codecs/av1/fdct.ts` (the forward Walsh-Hadamard transform), `src/codecs/av1/encode.ts` (the loop filter level from the quantizer), `src/codecs/avif-enc.ts` (the quantizer to qindex table) | BSD-2-Clause |
18
18
  | [libavif](https://github.com/AOMediaCodec/libavif) by Joe Drago | `src/codecs/avif.ts` (YUV to RGB conversion with bilinear chroma upsampling, alpha range expansion and unpremultiplication) | BSD-2-Clause |
19
19
  | [jxl-oxide](https://github.com/tirr-c/jxl-oxide) by Wonwoo Choi | `src/codecs/jxl/*` (the JPEG XL decoder: bit reader, header and frame header fields, entropy decoding, VarDCT, dequantization matrices, transforms, restoration filters, upsampling, the parsing of patches, splines and noise) | MIT (or Apache-2.0) |
20
20
  | [libjxl](https://github.com/libjxl/libjxl) by the JPEG XL Project Authors | `src/codecs/jxl/modular.ts` (Modular decoding: MA trees, predictors, the self-correcting predictor, transforms), `src/codecs/jxl/frame.ts` (the sections of frames, the order of the rendering stages, reference frames), `src/codecs/jxl/blend.ts`, `src/codecs/jxl/color.ts` (XYB to RGB), `src/codecs/jxl/features.ts` (rendering patches, splines and noise), `src/codecs/jxl/fast-lossless.ts` (the lossless encoder: palette detection, YCoCg, the gradient predictor, prefix codes, runs as LZ77, the headers) | BSD-3-Clause |
21
21
  | [JPEG XL conformance](https://github.com/libjxl/conformance) by the JPEG XL Project Authors | `tests/jxl/alpha-*.jxl`, `animation-spline.jxl`, `blendmodes.jxl`, `mul-no-extra-channels.jxl` (test files) | BSD-3-Clause |
22
+ | [Various smartphones - Android, Blackberry, Windows Phone, and iOS.jpg](https://commons.wikimedia.org/wiki/File:Various_smartphones_-_Android,_Blackberry,_Windows_Phone,_and_iOS.jpg) by Carlos Varela | `tests/targets/external.png` and `external.jpg` (a square of it, scaled to 638x638), the test files made from them (`tests/avif`, `tests/jxl`, `tests/ico`, `tests/hdr`, `tests/qoi`, `tests/tiffs`) and the test targets showing them; `bench/inputs/photo.jpg` (unmodified) | [CC BY 2.0](https://creativecommons.org/licenses/by/2.0/) |
22
23
  | [FreeType](https://freetype.org) | `src/render/hinting.ts` (behavior and parts of the logic of the TrueType interpreter) | FreeType License |
23
24
  | [QOI](https://github.com/phoboslab/qoi) by Dominic Szablewski | `src/codecs/qoi.ts` (the reference encoder's choices of operations) | MIT |
24
25
  | [Pillow](https://github.com/python-pillow/Pillow) | `src/util/resample.ts` (filter coefficients, box, bilinear and bicubic filters) | MIT-CMU |
25
26
  | [HarfBuzz](https://github.com/harfbuzz/harfbuzz) | `src/render/buffer.ts`, `src/render/layout.ts`, `src/render/shape.ts`, `src/render/shapers/*` (OpenType shaping: buffer, GSUB/GPOS, normalization, fallback positioning, the script shapers and syllable grammars), `scripts/unicode.js` (shaping category tables) | Old MIT |
26
27
  | [Universal Shaping Engine data](https://github.com/harfbuzz/harfbuzz/tree/main/src/ms-use) by Microsoft | `scripts/ms-use` (category overrides, invalid vowel sequences), the tables generated from them in `src/render/unicode-data.ts` | MIT |
28
+ | [resvg](https://github.com/linebender/resvg) by the Resvg Authors | `src/render/filter.ts` (the filter effects: regions, inputs, color spaces, box blur (based on [fastblur](https://github.com/fschutt/fastblur)), IIR blur, offset, flood, composite, merge, drop shadow, color matrix, component transfer, tile, morphology, convolution), `src/render/svg.ts` (the filters' attributes like usvg; how patterns are rendered and their reference cycles broken, following resvg and usvg; the markers' placement and orientation, ported from usvg; as many cubics per arc as kurbo makes for usvg; how images are fitted, clipped and sampled), `tests/svgs/resvg` (test cases with resvg's renderings) | MIT (or Apache-2.0) |
29
+ | [tiny-skia](https://github.com/linebender/tiny-skia) by Yevhenii Reizner (from [Skia](https://skia.org) by Google) | `src/render/filter.ts` (feBlend's blend modes) | BSD-3-Clause |
30
+ | [gaussianiir](http://www.getreuer.info/home/gaussianiir) by Pascal Getreuer | `src/render/filter.ts` (the IIR blur for small deviations, through resvg) | BSD-2-Clause (Simplified BSD) |
27
31
  | [Unicode Character Database](https://www.unicode.org/ucd/) | `src/render/unicode-data.ts` (character properties, generated by `scripts/unicode.js`) | Unicode License v3 |
28
32
 
29
33
  ## fflate, Fast CRC32 in JavaScript
@@ -488,3 +492,99 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
488
492
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
489
493
  SOFTWARE
490
494
  ```
495
+
496
+ ## resvg
497
+
498
+ ```
499
+ Copyright 2017 the Resvg Authors
500
+
501
+ Permission is hereby granted, free of charge, to any
502
+ person obtaining a copy of this software and associated
503
+ documentation files (the "Software"), to deal in the
504
+ Software without restriction, including without
505
+ limitation the rights to use, copy, modify, merge,
506
+ publish, distribute, sublicense, and/or sell copies of
507
+ the Software, and to permit persons to whom the Software
508
+ is furnished to do so, subject to the following
509
+ conditions:
510
+
511
+ The above copyright notice and this permission notice
512
+ shall be included in all copies or substantial portions
513
+ of the Software.
514
+
515
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
516
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
517
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
518
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
519
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
520
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
521
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
522
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
523
+ DEALINGS IN THE SOFTWARE.
524
+ ```
525
+
526
+ ## tiny-skia
527
+
528
+ ```
529
+ Copyright (c) 2011 Google Inc. All rights reserved.
530
+ Copyright (c) 2020 Yevhenii Reizner All rights reserved.
531
+
532
+ Redistribution and use in source and binary forms, with or without
533
+ modification, are permitted provided that the following conditions are
534
+ met:
535
+
536
+ * Redistributions of source code must retain the above copyright
537
+ notice, this list of conditions and the following disclaimer.
538
+
539
+ * Redistributions in binary form must reproduce the above copyright
540
+ notice, this list of conditions and the following disclaimer in
541
+ the documentation and/or other materials provided with the
542
+ distribution.
543
+
544
+ * Neither the name of the copyright holder nor the names of its
545
+ contributors may be used to endorse or promote products derived
546
+ from this software without specific prior written permission.
547
+
548
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
549
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
550
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
551
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
552
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
553
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
554
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
555
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
556
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
557
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
558
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
559
+ ```
560
+
561
+ ## gaussianiir
562
+
563
+ The IIR blur follows Pascal Getreuer's gaussianiir (through resvg), under the Simplified BSD License:
564
+
565
+ ```
566
+ Copyright (c) 2009, Pascal Getreuer
567
+ All rights reserved.
568
+
569
+ Redistribution and use in source and binary forms, with or without
570
+ modification, are permitted provided that the following conditions are
571
+ met:
572
+
573
+ * Redistributions of source code must retain the above copyright
574
+ notice, this list of conditions and the following disclaimer.
575
+ * Redistributions in binary form must reproduce the above copyright
576
+ notice, this list of conditions and the following disclaimer in
577
+ the documentation and/or other materials provided with the distribution
578
+
579
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
580
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
581
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
582
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
583
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
584
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
585
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
586
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
587
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
588
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
589
+ POSSIBILITY OF SUCH DAMAGE.
590
+ ```
@@ -0,0 +1,62 @@
1
+ import { Image } from './image.js';
2
+ import { Frame, FrameOptions } from './frame.js';
3
+ import { Metadata } from './metadata.js';
4
+ /** The options all animation encoders of {@link Animation.webpEncoder} and the others have */
5
+ export interface AnimationEncoderOptions {
6
+ /** How many times to repeat the animation (-1 = forever, 0 = play once). Default: `-1` */
7
+ loopCount?: number;
8
+ /** Metadata to include, see {@link Metadata} */
9
+ metadata?: Metadata;
10
+ /**
11
+ * Whether to store each frame as the area that changed since the frame before and merge identical frames, like
12
+ * {@link AnimationEncodeOptions.optimize}. Default: `true`
13
+ */
14
+ optimize?: boolean;
15
+ }
16
+ /** Options of {@link Animation.webpEncoder} */
17
+ export interface WebPAnimationEncoderOptions extends AnimationEncoderOptions {
18
+ /** Lossy frames (0-100), see {@link WebPAnimationEncodeOptions.quality}. Without it the frames are lossless */
19
+ quality?: number;
20
+ /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `2` */
21
+ effort?: number;
22
+ /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
23
+ sharpYuv?: boolean;
24
+ }
25
+ /** Options of {@link Animation.gifEncoder} */
26
+ export interface GIFAnimationEncoderOptions extends AnimationEncoderOptions {
27
+ /** 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above). Default: `95` */
28
+ quality?: number;
29
+ }
30
+ /** Options of {@link Animation.apngEncoder} */
31
+ export interface APNGAnimationEncoderOptions extends AnimationEncoderOptions {
32
+ /** The zlib compression level (0-9), higher is smaller but slower. Default: `1` */
33
+ compression?: number;
34
+ }
35
+ /**
36
+ * Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder},
37
+ * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}. The file is the one an {@link Animation} of the
38
+ * frames encodes to, but for unoptimized WebPs with frames WebP can't store as they are (disposed to the previous
39
+ * frame, or disposed with odd offsets): from the first of them on, the frames are the canvas they show (the same
40
+ * animation, blending rounds differently by 1 at most). APNGs keep their frames compressed until the end: their pixel
41
+ * format depends on all of them
42
+ */
43
+ export declare class AnimationEncoder {
44
+ readonly width: number;
45
+ readonly height: number;
46
+ private readonly format;
47
+ private optimizer;
48
+ private queue;
49
+ private count;
50
+ private finished;
51
+ /** How many frames were added */
52
+ get frames(): number;
53
+ /**
54
+ * Adds the next frame: a {@link Frame} (with its duration, offsets and disposal) or an image (a frame of 100 ms by
55
+ * default). The options override the frame's. The pixels are copied right away, the image can change afterwards
56
+ * @param frame The frame or image
57
+ * @param options See {@link FrameOptions}
58
+ */
59
+ add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
60
+ /** Encodes the rest and returns the file. The encoder can't be used afterwards */
61
+ finish(): Promise<Uint8Array>;
62
+ }
@@ -0,0 +1,204 @@
1
+ import * as gifCodec from "./codecs/gif.js";
2
+ import * as png from "./codecs/png.js";
3
+ import * as webp from "./codecs/webp.js";
4
+ import { Image } from "./image.js";
5
+ import { Frame } from "./frame.js";
6
+ import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
7
+ import { compressAsync, decompressAsync } from "./codecs/zlib.js";
8
+ import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
9
+ import { finite } from "./util/options.js";
10
+ const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
11
+ export class AnimationEncoder {
12
+ width;
13
+ height;
14
+ format;
15
+ optimizer;
16
+ queue = Promise.resolve();
17
+ count = 0;
18
+ finished = false;
19
+ constructor(width, height, format, optimize) {
20
+ this.width = width;
21
+ this.height = height;
22
+ this.format = format;
23
+ this.optimizer = optimize ? new Optimizer(width, height, format.optimize) : null;
24
+ }
25
+ get frames() {
26
+ return this.count;
27
+ }
28
+ add(frame, options = {}) {
29
+ if (this.finished)
30
+ throw new Error('The animation encoder is finished');
31
+ if (!(frame instanceof Image))
32
+ throw new TypeError('Invalid frame passed');
33
+ const own = frame instanceof Frame ? frame : null;
34
+ const duration = options.duration ?? own?.duration ?? 100;
35
+ const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0;
36
+ if (finite(duration, 'frame duration') < 0)
37
+ throw new RangeError('Invalid frame duration');
38
+ finite(x, 'x offset');
39
+ finite(y, 'y offset');
40
+ const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
41
+ const input = {
42
+ x, y, width: frame.width, height: frame.height, duration, disposal,
43
+ dispose: [0, 0, 2, 1][disposal],
44
+ pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength).slice()
45
+ };
46
+ this.count++;
47
+ return this.queue = this.queue.then(async () => {
48
+ if (!this.optimizer)
49
+ return this.format.frame(input, false);
50
+ this.optimizer.push(input);
51
+ for (const f of this.optimizer.take())
52
+ await this.format.frame(f, true);
53
+ });
54
+ }
55
+ async finish() {
56
+ if (this.finished)
57
+ throw new Error('The animation encoder is finished');
58
+ this.finished = true;
59
+ await this.queue;
60
+ if (!this.count)
61
+ throw new Error('An animation needs at least one frame');
62
+ if (this.optimizer)
63
+ for (const f of this.optimizer.end())
64
+ await this.format.frame(f, true);
65
+ const optimizer = this.optimizer;
66
+ this.optimizer = null;
67
+ return this.format.file(optimizer);
68
+ }
69
+ static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false }) {
70
+ canvas(width, height, loopCount);
71
+ if (width > 1 << 24 || height > 1 << 24)
72
+ throw new RangeError('WebP: canvas too large');
73
+ if (quality !== undefined) {
74
+ const q = finite(quality, 'quality');
75
+ if (q < 0 || q > 100)
76
+ throw new RangeError(`quality must be 0-100, not ${q}`);
77
+ if (!Number.isInteger(effort) || effort < 0 || effort > 6)
78
+ throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
79
+ }
80
+ const resolved = resolveMetadata(metadata), chunks = [];
81
+ let alpha = false;
82
+ const compositor = optimize ? null : new Compositor(width, height);
83
+ let full = false;
84
+ const add = (f) => {
85
+ alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
86
+ chunks.push(webp.frameChunk(f, quality, effort, sharpYuv));
87
+ };
88
+ return new AnimationEncoder(width, height, {
89
+ optimize: { replace: true, even: true, alpha: 'frame', tolerance: quality === undefined ? undefined : webp.lossyTolerance(quality) },
90
+ async frame(f, optimized) {
91
+ if (optimized)
92
+ return add(f);
93
+ const input = f;
94
+ const shown = compositor.push(input);
95
+ full ||= input.dispose === 2 || (input.dispose === 1 && !!(input.x & 1 || input.y & 1));
96
+ if (full)
97
+ return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
98
+ add(webpFrame(input));
99
+ },
100
+ file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
101
+ }, optimize);
102
+ }
103
+ static __gif__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality = 95 }) {
104
+ canvas(width, height, loopCount);
105
+ const comments = gifComments(resolveMetadata(metadata));
106
+ let first = null, restores = false;
107
+ const rest = [];
108
+ return new AnimationEncoder(width, height, {
109
+ optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true },
110
+ async frame(f, optimized) {
111
+ if (!first && optimized)
112
+ coverCanvas(f, width, height);
113
+ const gif = { x: f.x, y: f.y, width: f.width, height: f.height, pixels: f.pixels,
114
+ dispose: optimized ? (f.dispose ? 3 : 1) : f.disposal,
115
+ delay: Math.round(f.duration / 10) };
116
+ restores ||= gif.dispose === 3;
117
+ if (!first)
118
+ first = gif;
119
+ else
120
+ rest.push(gifCodec.encodeFrame(gif, quality, gif.dispose === 3));
121
+ },
122
+ file() {
123
+ const f = first;
124
+ return concat([gifCodec.header(width, height, loopCount, comments), gifCodec.encodeFrame(f, quality, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]);
125
+ }
126
+ }, optimize);
127
+ }
128
+ static __apng__(width, height, { loopCount = -1, metadata = {}, optimize = true, compression = 1 }) {
129
+ canvas(width, height, loopCount);
130
+ const text = pngText(resolveMetadata(metadata));
131
+ const stored = [];
132
+ const cost = new png.AlphaCost();
133
+ let blended = false;
134
+ return new AnimationEncoder(width, height, {
135
+ optimize: { replace: true, even: false, alpha: () => cost.cost() },
136
+ async frame(f, optimized) {
137
+ let frame;
138
+ if (optimized) {
139
+ const o = f;
140
+ cost.add(o.pixels);
141
+ blended ||= o.blend;
142
+ frame = { x: o.x, y: o.y, width: o.width, height: o.height, duration: o.duration, dispose: o.dispose ? 1 : 0, blend: o.blend, pixels: o.pixels };
143
+ }
144
+ else {
145
+ frame = { x: f.x, y: f.y, width: f.width, height: f.height, duration: f.duration, dispose: f.dispose, pixels: f.pixels };
146
+ png.checkFrame(stored.length ? frame : png.coverCanvas(frame, width, height), width, height);
147
+ }
148
+ const { pixels, ...rest } = frame;
149
+ stored.push({ frame: rest, packed: await compressAsync(pixels, 1) });
150
+ },
151
+ async file(optimizer) {
152
+ const fill = !!optimizer && optimizer.opaque && blended && optimizer.denseTotal < optimizer.chosenTotal * cost.cost();
153
+ const frames = async function* () {
154
+ const shown32 = new Int32Array(width * height);
155
+ for (const [i, { frame, packed }] of stored.entries()) {
156
+ let f = { ...frame, pixels: await decompressAsync(packed, frame.width * frame.height * 4) };
157
+ if (fill)
158
+ fillUnchanged(f, shown32, width);
159
+ if (i === 0)
160
+ f = png.coverCanvas(f, width, height);
161
+ yield f;
162
+ }
163
+ };
164
+ const scanner = new png.FormatScanner();
165
+ for await (const f of frames())
166
+ scanner.add(f.pixels);
167
+ const format = scanner.format(), encoded = [];
168
+ for await (const { pixels, ...f } of frames())
169
+ encoded.push({ ...f, data: await png.frameData(pixels, f.width, f.height, format, compression) });
170
+ return png.animationFile(encoded, width, height, toPlays(loopCount), format, text);
171
+ }
172
+ }, optimize);
173
+ }
174
+ }
175
+ function canvas(width, height, loopCount) {
176
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
177
+ throw new RangeError(`Invalid canvas size: ${width}x${height}`);
178
+ if (!Number.isInteger(loopCount) || loopCount < -1)
179
+ throw new RangeError('Invalid loop count');
180
+ }
181
+ function webpFrame(f) {
182
+ let { x, y, width: w, height: h, pixels } = f;
183
+ if (x & 1 || y & 1) {
184
+ const dx = x & 1, dy = y & 1;
185
+ const padded = new Uint8Array((w + dx) * (h + dy) * 4);
186
+ for (let row = 0; row < h; row++)
187
+ padded.set(pixels.subarray(row * w * 4, (row + 1) * w * 4), ((row + dy) * (w + dx) + dx) * 4);
188
+ pixels = padded;
189
+ x -= dx;
190
+ y -= dy;
191
+ w += dx;
192
+ h += dy;
193
+ }
194
+ return { x, y, width: w, height: h, duration: f.duration, dispose: f.dispose === 1, pixels };
195
+ }
196
+ function concat(parts) {
197
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
198
+ let offset = 0;
199
+ for (const p of parts) {
200
+ out.set(p, offset);
201
+ offset += p.length;
202
+ }
203
+ return out;
204
+ }
@@ -2,6 +2,7 @@ import { BinaryData } from './util/mem.js';
2
2
  import { ResizeMode, ResizeOptions } from './image.js';
3
3
  import { Frame } from './frame.js';
4
4
  import { Metadata } from './metadata.js';
5
+ import { AnimationEncoder, WebPAnimationEncoderOptions, GIFAnimationEncoderOptions, APNGAnimationEncoderOptions } from './animation-encoder.js';
5
6
  /** Options of {@link Animation} */
6
7
  export interface AnimationOptions {
7
8
  /** How many times to repeat the animation (-1 = forever, 0 = play once). Default: `-1` */
@@ -33,11 +34,14 @@ export interface AnimationEncodeOptions {
33
34
  export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
34
35
  /**
35
36
  * Lossy frames (0-100, like libwebp's quality: 75 is its default), much smaller than lossless ones. Without it the
36
- * frames are lossless
37
+ * frames are lossless. Optimized lossy frames, like libwebp's, leave out 8x8 blocks that only changed a little (by
38
+ * up to 3 per channel at quality 85, 1 at 100)
37
39
  */
38
40
  quality?: number;
39
41
  /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `2` */
40
42
  effort?: number;
43
+ /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
44
+ sharpYuv?: boolean;
41
45
  }
42
46
  /** Options of {@link Animation.encodeGIF} */
43
47
  export interface GIFEncodeOptions extends AnimationEncodeOptions {
@@ -141,7 +145,33 @@ export declare class Animation extends Array<Frame> {
141
145
  * shows the same animation, but doesn't necessarily decode to the same frames
142
146
  * @param options See {@link WebPAnimationEncodeOptions}
143
147
  */
144
- encodeWebP({ metadata, optimize, quality, effort }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
148
+ encodeWebP({ metadata, optimize, quality, effort, sharpYuv }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
149
+ /**
150
+ * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
151
+ * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
152
+ * with `{ duration }`), then `await encoder.finish()` for the file
153
+ * @param width The canvas width
154
+ * @param height The canvas height
155
+ * @param options See {@link WebPAnimationEncoderOptions}
156
+ */
157
+ static webpEncoder(width: number, height: number, options?: WebPAnimationEncoderOptions): AnimationEncoder;
158
+ /**
159
+ * An encoder that makes an animated GIF a frame at a time, like {@link Animation.encodeGIF} (the same file),
160
+ * without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()`
161
+ * @param width The canvas width
162
+ * @param height The canvas height
163
+ * @param options See {@link GIFAnimationEncoderOptions}
164
+ */
165
+ static gifEncoder(width: number, height: number, options?: GIFAnimationEncoderOptions): AnimationEncoder;
166
+ /**
167
+ * An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the
168
+ * frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame,
169
+ * then `await encoder.finish()`
170
+ * @param width The canvas width
171
+ * @param height The canvas height
172
+ * @param options See {@link APNGAnimationEncoderOptions}
173
+ */
174
+ static apngEncoder(width: number, height: number, options?: APNGAnimationEncoderOptions): AnimationEncoder;
145
175
  /**
146
176
  * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
147
177
  * @param input The binary data to decode