imagescript 3.8.1 → 3.9.0

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
@@ -51,10 +51,12 @@ Coordinates are 0-based, `(0, 0)` is the top left pixel. A bigger example is the
51
51
 
52
52
  Animated WebPs and JPEG XLs decode too, and [animations](https://imagescript.matmen.dev/classes/Animation.html)
53
53
  encode as GIF, APNG or WebP, also [a frame at a time](https://imagescript.matmen.dev/classes/Animation.html#webpencoder).
54
+ Embedded ICC color profiles (Display P3, Adobe RGB, ...) are converted to sRGB when decoding, like browsers show them.
54
55
 
55
56
  - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts,
56
57
  in every script, with color emoji
57
- - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg) (no text)
58
+ - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), text included (with the fonts you
59
+ pass or the SVG embeds)
58
60
  - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
59
61
  [cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
60
62
  [rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
@@ -17,7 +17,7 @@ following projects, under their own licenses. Each derived file says so in its h
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
- | [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 |
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), `src/codecs/jxl/patches-enc.ts` (finding text-like patches, packing them into a reference frame, quantizing it like Modular XYB, the patch dictionary) | 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
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/) |
23
23
  | [FreeType](https://freetype.org) | `src/render/hinting.ts` (behavior and parts of the logic of the TrueType interpreter) | FreeType License |
@@ -25,8 +25,11 @@ following projects, under their own licenses. Each derived file says so in its h
25
25
  | [Pillow](https://github.com/python-pillow/Pillow) | `src/util/resample.ts` (filter coefficients, box, bilinear and bicubic filters) | MIT-CMU |
26
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 |
27
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 |
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; transform-origin, paint-order, context-fill and context-stroke, mix-blend-mode and isolation, following usvg; how text elements are read: whitespace, positions, chunks, spans, decorations, baseline shifts, text paths, as in usvg), `src/render/svg-text.ts` (text layout ported from usvg: shaping across spans, spacing, text length, anchors, positions along paths, baselines, decorations, vertical text, color glyphs' placement), `tests/svgs/resvg` (test cases with resvg's renderings) | MIT (or Apache-2.0) |
29
+ | resvg's test fonts: [Noto](https://notofonts.github.io) fonts by Google, [Amiri](https://github.com/aliftype/amiri) by Khaled Hosny, [M+](https://mplusfonts.github.io) by the M+ Fonts Project, [Sedgwick Ave Display](https://github.com/googlefonts/sedgwickave) by Kevin Burke, [Source Sans Pro](https://github.com/adobe-fonts/source-sans) by Adobe, [Yellowtail](https://fonts.google.com/specimen/Yellowtail) by Astigmatic, [Twemoji](https://github.com/twitter/twemoji) by Twitter, a CFF and sbix test font of resvg | `tests/fonts/resvg` (subsets, see `scripts/resvg-test-fonts.py`; their licenses are next to them) | OFL-1.1, Apache-2.0, MIT, CC-BY 4.0 (Twemoji's graphics) |
30
+ | [fontdb](https://github.com/RazrFalcon/fontdb) by Yevhenii Reizner | `src/render/svg-text.ts` (font matching: CSS Fonts' algorithm as fontdb's queries do it, the fallback's style check) | MIT |
31
+ | [kurbo](https://github.com/linebender/kurbo) by Raph Levien | `src/render/svg-text.ts` (arc lengths of cubics: adaptive Legendre-Gauss quadrature; parameters at arc lengths: the ITP method) | MIT (or Apache-2.0) |
32
+ | [tiny-skia](https://github.com/linebender/tiny-skia) by Yevhenii Reizner (from [Skia](https://skia.org) by Google) | `src/render/blend.ts` (the blend modes of feBlend and mix-blend-mode) | BSD-3-Clause |
30
33
  | [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) |
31
34
  | [Unicode Character Database](https://www.unicode.org/ucd/) | `src/render/unicode-data.ts` (character properties, generated by `scripts/unicode.js`) | Unicode License v3 |
32
35
 
@@ -523,6 +526,62 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
523
526
  DEALINGS IN THE SOFTWARE.
524
527
  ```
525
528
 
529
+ ## fontdb
530
+
531
+ ```
532
+ The MIT License (MIT)
533
+
534
+ Copyright (c) 2020 Yevhenii Reizner
535
+
536
+ Permission is hereby granted, free of charge, to any person obtaining a copy
537
+ of this software and associated documentation files (the "Software"), to deal
538
+ in the Software without restriction, including without limitation the rights
539
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
540
+ copies of the Software, and to permit persons to whom the Software is
541
+ furnished to do so, subject to the following conditions:
542
+
543
+ The above copyright notice and this permission notice shall be included in all
544
+ copies or substantial portions of the Software.
545
+
546
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
547
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
548
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
549
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
550
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
551
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
552
+ SOFTWARE.
553
+ ```
554
+
555
+ ## kurbo
556
+
557
+ ```
558
+ Copyright (c) 2018 Raph Levien
559
+
560
+ Permission is hereby granted, free of charge, to any
561
+ person obtaining a copy of this software and associated
562
+ documentation files (the "Software"), to deal in the
563
+ Software without restriction, including without
564
+ limitation the rights to use, copy, modify, merge,
565
+ publish, distribute, sublicense, and/or sell copies of
566
+ the Software, and to permit persons to whom the Software
567
+ is furnished to do so, subject to the following
568
+ conditions:
569
+
570
+ The above copyright notice and this permission notice
571
+ shall be included in all copies or substantial portions
572
+ of the Software.
573
+
574
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
575
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
576
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
577
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
578
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
579
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
580
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
581
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
582
+ DEALINGS IN THE SOFTWARE.
583
+ ```
584
+
526
585
  ## tiny-skia
527
586
 
528
587
  ```
@@ -21,6 +21,8 @@ export interface WebPAnimationEncoderOptions extends AnimationEncoderOptions {
21
21
  effort?: number;
22
22
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
23
23
  sharpYuv?: boolean;
24
+ /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
25
+ alphaQuality?: number;
24
26
  }
25
27
  /** Options of {@link Animation.gifEncoder} */
26
28
  export interface GIFAnimationEncoderOptions extends AnimationEncoderOptions {
@@ -66,27 +66,21 @@ export class AnimationEncoder {
66
66
  this.optimizer = null;
67
67
  return this.format.file(optimizer);
68
68
  }
69
- static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false }) {
69
+ static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
70
70
  canvas(width, height, loopCount);
71
71
  if (width > 1 << 24 || height > 1 << 24)
72
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
- }
73
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
80
74
  const resolved = resolveMetadata(metadata), chunks = [];
81
75
  let alpha = false;
82
76
  const compositor = optimize ? null : new Compositor(width, height);
83
77
  let full = false;
84
78
  const add = (f) => {
85
79
  alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
86
- chunks.push(webp.frameChunk(f, quality, effort, sharpYuv));
80
+ chunks.push(webp.frameChunk(f, lossy));
87
81
  };
88
82
  return new AnimationEncoder(width, height, {
89
- optimize: { replace: true, even: true, alpha: 'frame', tolerance: quality === undefined ? undefined : webp.lossyTolerance(quality) },
83
+ optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
90
84
  async frame(f, optimized) {
91
85
  if (optimized)
92
86
  return add(f);
@@ -18,6 +18,8 @@ export interface AnimationDecodeOptions {
18
18
  * bombs) can't exhaust the memory. Default: `268402689` (16383², like sharp), `Infinity` for no limit
19
19
  */
20
20
  maxPixels?: number;
21
+ /** Whether to convert the colors of frames with an embedded ICC profile (APNGs, WebPs) to sRGB, like `applyColorProfile` of {@link Image.decode}. Default: `true` */
22
+ applyColorProfile?: boolean;
21
23
  }
22
24
  /** The options all animation encoders have */
23
25
  export interface AnimationEncodeOptions {
@@ -42,6 +44,8 @@ export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
42
44
  effort?: number;
43
45
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
44
46
  sharpYuv?: boolean;
47
+ /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
48
+ alphaQuality?: number;
45
49
  }
46
50
  /** Options of {@link Animation.encodeGIF} */
47
51
  export interface GIFEncodeOptions extends AnimationEncodeOptions {
@@ -145,7 +149,7 @@ export declare class Animation extends Array<Frame> {
145
149
  * shows the same animation, but doesn't necessarily decode to the same frames
146
150
  * @param options See {@link WebPAnimationEncodeOptions}
147
151
  */
148
- encodeWebP({ metadata, optimize, quality, effort, sharpYuv }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
152
+ encodeWebP({ metadata, optimize, quality, effort, sharpYuv, alphaQuality }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
149
153
  /**
150
154
  * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
151
155
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
package/dist/animation.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { profileTransform } from "./util/icc.js";
1
2
  import * as gifCodec from "./codecs/gif.js";
2
3
  import * as png from "./codecs/png.js";
3
4
  import * as webp from "./codecs/webp.js";
@@ -125,20 +126,14 @@ export class Animation extends Array {
125
126
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
126
127
  return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compression, pngText(resolveMetadata(metadata)));
127
128
  }
128
- async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false } = {}) {
129
+ async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = {}) {
129
130
  this.__validate__();
130
131
  if (!this.length)
131
132
  throw new Error('An animation needs at least one frame');
132
- if (quality !== undefined) {
133
- const q = finite(quality, 'quality');
134
- if (q < 0 || q > 100)
135
- throw new RangeError(`quality must be 0-100, not ${q}`);
136
- if (!Number.isInteger(effort) || effort < 0 || effort > 6)
137
- throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
138
- }
139
- const tolerance = quality === undefined ? undefined : webp.lossyTolerance(quality);
133
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
134
+ const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
140
135
  const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__();
141
- return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), quality, effort, sharpYuv);
136
+ return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), lossy);
142
137
  }
143
138
  __webpFrames__() {
144
139
  const width = this.width, height = this.height;
@@ -192,23 +187,30 @@ export class Animation extends Array {
192
187
  return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
193
188
  }
194
189
  static async __decode__(input, onlyFirstFrameOrOptions) {
195
- const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
190
+ const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
191
+ const profile = (frames, icc) => {
192
+ const transform = applyColorProfile && icc ? profileTransform(icc) : null;
193
+ if (transform)
194
+ for (const frame of frames)
195
+ transform(frame.bitmap);
196
+ return frames;
197
+ };
196
198
  const data = view(input);
197
199
  const type = ImageType.getType(data);
198
200
  if (type === 'gif')
199
201
  return Animation.__fromGIF__(data, onlyExtractFirstFrame, Animation, maxPixels);
200
202
  if (type === 'webp') {
201
203
  const decoded = webp.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
202
- const frames = canvasFrames(decoded.width, decoded.height, webp.composite(decoded));
204
+ const frames = profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc);
203
205
  return new Animation(frames, fromPlays(decoded.loopCount));
204
206
  }
205
207
  if (type === 'png' && !png.isAnimated(data)) {
206
- const image = await Image.decode(data, { maxPixels, applyOrientation: false });
208
+ const image = await Image.decode(data, { maxPixels, applyOrientation: false, applyColorProfile });
207
209
  return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), -1);
208
210
  }
209
211
  if (type === 'png') {
210
212
  const decoded = await png.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
211
- const frames = canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded));
213
+ const frames = profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc);
212
214
  return new Animation(frames, decoded.frames.length > 1 ? fromPlays(decoded.plays) : -1);
213
215
  }
214
216
  if (type === 'jxl') {
@@ -225,7 +227,7 @@ export class Animation extends Array {
225
227
  return new Animation(frames, frames.length > 1 ? loopCount : -1);
226
228
  }
227
229
  if (type)
228
- return new Animation([Frame.from(await Image.decode(data, { maxPixels }), 0)]);
230
+ return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyColorProfile }), 0)]);
229
231
  throw new Error('Unsupported image type');
230
232
  }
231
233
  static __fromGIF__(data, onlyExtractFirstFrame, Class, maxPixels = MAX_PIXELS) {
@@ -4,6 +4,7 @@
4
4
  * libavif converts (its reference path, src/reformat.c, with bilinear chroma upsampling; src/read.c, src/alpha.c), HDR
5
5
  * (PQ, HLG) tone mapped. Copyright 2019 Joe Drago, BSD-2-Clause License (see THIRD_PARTY_NOTICES.md)
6
6
  */
7
+ import { parseProfile } from "../util/icc.js";
7
8
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
9
  import { decodeAV1 } from "./av1/frame.js";
9
10
  import { toSRGB, hdrToLinear } from "./hdr.js";
@@ -442,6 +443,11 @@ export function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
442
443
  const alphaItem = alphaOf(primary);
443
444
  const color = decodeItem(d, it, items, idat, maxPixels);
444
445
  applyColr(d, it, color);
446
+ const icc = iccOf(d, it);
447
+ if (icc && parseProfile(icc)) {
448
+ color.primaries = 1;
449
+ color.transfer = 13;
450
+ }
445
451
  let alpha = alphaItem ? decodeItem(d, alphaItem, items, idat, maxPixels) : null;
446
452
  if (!alphaItem && it.type === 'grid') {
447
453
  const tiles = (it.refs.get('dimg') ?? []).map(alphaOf);
@@ -458,13 +464,21 @@ export function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
458
464
  else if (box.type === 'imir')
459
465
  pixels = mirror(pixels, width, height, d[box.start] & 1);
460
466
  }
461
- return { width, height, pixels };
467
+ return { width, height, pixels, icc };
462
468
  }
463
469
  }
464
470
  if (moov)
465
471
  return decodeSequence(d, moov, maxPixels, toneMapping);
466
472
  throw new Error('AVIF: no image');
467
473
  }
474
+ function iccOf(d, it) {
475
+ for (const { box } of it.props) {
476
+ const type = box.type === 'colr' && box.end - box.start > 4 ? fourcc(d, box.start) : '';
477
+ if (type === 'prof' || type === 'rICC')
478
+ return d.subarray(box.start + 4, box.end);
479
+ }
480
+ return undefined;
481
+ }
468
482
  function applyColr(d, it, yuv) {
469
483
  for (const { box } of it.props) {
470
484
  if (box.type !== 'colr' || fourcc(d, box.start) !== 'nclx')
@@ -23,6 +23,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
23
23
  let adobe = null;
24
24
  let jfif = false;
25
25
  let orientation = 1;
26
+ const profile = [];
26
27
  let restartInterval = 0;
27
28
  let pos = 2;
28
29
  const u16 = (offset) => data[offset] << 8 | data[offset + 1];
@@ -112,6 +113,10 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
112
113
  if (orientation === 1)
113
114
  orientation = exifOrientation(data.subarray(start, end));
114
115
  break;
116
+ case 0xe2:
117
+ if (length >= 16 && String.fromCharCode(...data.subarray(start, start + 12)) === 'ICC_PROFILE\0' && data[start + 12] >= 1)
118
+ profile[data[start + 12] - 1] ??= data.subarray(start + 14, end);
119
+ break;
115
120
  case 0xee:
116
121
  if (length >= 14 && data[start] === 0x41 && data[start + 1] === 0x64 && data[start + 2] === 0x6f && data[start + 3] === 0x62 && data[start + 4] === 0x65)
117
122
  adobe = { transform: data[start + 11] };
@@ -151,7 +156,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
151
156
  }
152
157
  if (!frame)
153
158
  throw new Error('JPEG: missing frame header');
154
- return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation };
159
+ const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
160
+ return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
155
161
  }
156
162
  function createFrame(progressive, height, width, componentData) {
157
163
  const count = componentData[0];