imagescript 3.17.0 → 3.19.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
@@ -27,11 +27,11 @@ Without a bundler, import it from jsDelivr in the browser:
27
27
 
28
28
  ```html
29
29
  <script type="module">
30
- import { Image, ResizeModes } from 'https://cdn.jsdelivr.net/npm/imagescript@3/+esm';
30
+ import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@3/+esm';
31
31
 
32
32
  const image = await Image.decode(await fetch('photo.jpg').then(r => r.arrayBuffer()));
33
- image.resize(256, ResizeModes.AUTO);
34
- const url = URL.createObjectURL(new Blob([await image.encode()], { type: 'image/png' }));
33
+ image.resize({ width: 256 });
34
+ const url = URL.createObjectURL(new Blob([await image.encodePNG()], { type: 'image/png' }));
35
35
  document.body.append(Object.assign(document.createElement('img'), { src: url }));
36
36
  </script>
37
37
  ```
@@ -41,12 +41,12 @@ Without a bundler, import it from jsDelivr in the browser:
41
41
  ### Example
42
42
 
43
43
  ```js
44
- import { Image, ResizeModes } from 'imagescript';
44
+ import { Image } from 'imagescript';
45
45
  import { readFile, writeFile } from 'node:fs/promises';
46
46
 
47
47
  const image = await Image.decode(await readFile('input.jpg'));
48
- image.resize(256, ResizeModes.AUTO).roundCorners(16);
49
- await writeFile('output.png', await image.encode());
48
+ image.resize({ width: 256 }).roundCorners(16);
49
+ await writeFile('output.png', await image.encodePNG());
50
50
  ```
51
51
 
52
52
  <p align="center">
@@ -1,39 +1,32 @@
1
1
  import { Image } from './image.js';
2
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 the frames take (0-6, lossy and lossless), 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
- /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
25
- alphaQuality?: number;
26
- }
27
- /** Options of {@link Animation.gifEncoder} */
28
- export interface GIFAnimationEncoderOptions extends AnimationEncoderOptions {
29
- /** 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above). Default: `95` */
30
- quality?: number;
31
- }
32
- /** Options of {@link Animation.apngEncoder} */
33
- export interface APNGAnimationEncoderOptions extends AnimationEncoderOptions {
34
- /** The zlib compression level (0-9), higher is smaller but slower. Default: `4` */
35
- compression?: number;
36
- }
3
+ import type { AnimationOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.js';
4
+ /**
5
+ * The options all animation encoders of {@link Animation.webpEncoder} and the others have
6
+ * @deprecated {@link Animation.webpEncoder} and the others take the options of {@link Animation.encodeWebP} and the
7
+ * others ({@link AnimationEncodeOptions}) with the {@link AnimationOptions.loopCount}, this will be removed in 4.0
8
+ * @group Deprecated
9
+ */
10
+ export type AnimationEncoderOptions = AnimationEncodeOptions & AnimationOptions;
11
+ /**
12
+ * Options of {@link Animation.webpEncoder}
13
+ * @deprecated Use {@link WebPAnimationEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed
14
+ * in 4.0
15
+ * @group Deprecated
16
+ */
17
+ export type WebPAnimationEncoderOptions = WebPAnimationEncodeOptions & AnimationOptions;
18
+ /**
19
+ * Options of {@link Animation.gifEncoder}
20
+ * @deprecated Use {@link GIFEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0
21
+ * @group Deprecated
22
+ */
23
+ export type GIFAnimationEncoderOptions = GIFEncodeOptions & AnimationOptions;
24
+ /**
25
+ * Options of {@link Animation.apngEncoder}
26
+ * @deprecated Use {@link APNGEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0
27
+ * @group Deprecated
28
+ */
29
+ export type APNGAnimationEncoderOptions = APNGEncodeOptions & AnimationOptions;
37
30
  /**
38
31
  * Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder},
39
32
  * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}. The file is the one an {@link Animation} of the
@@ -7,7 +7,7 @@ import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimi
7
7
  import { compressAsync, decompressAsync } from "./codecs/zlib.js";
8
8
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
9
9
  import { finite, compressionLevel } from "./util/options.js";
10
- const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
10
+ const toPlays = (loopCount) => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1;
11
11
  export class AnimationEncoder {
12
12
  format;
13
13
  optimizer;
@@ -174,7 +174,7 @@ export class AnimationEncoder {
174
174
  function canvas(width, height, loopCount) {
175
175
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
176
176
  throw new RangeError(`Invalid canvas size: ${width}x${height}`);
177
- if (!Number.isInteger(loopCount) || loopCount < -1)
177
+ if (loopCount !== Infinity && (!Number.isInteger(loopCount) || loopCount < -1))
178
178
  throw new RangeError('Invalid loop count');
179
179
  }
180
180
  function webpFrame(f) {
@@ -1,11 +1,15 @@
1
1
  import { BinaryData } from './util/mem.js';
2
- import { ResizeMode, ResizeOptions } from './image.js';
2
+ import type { ToneMapping } from './codecs/hdr.js';
3
+ import { ResizeMode, ResizeOptions, ResizeToOptions } from './image.js';
3
4
  import { Frame } from './frame.js';
4
5
  import { Metadata } from './metadata.js';
5
- import { AnimationEncoder, WebPAnimationEncoderOptions, GIFAnimationEncoderOptions, APNGAnimationEncoderOptions } from './animation-encoder.js';
6
+ import { AnimationEncoder } from './animation-encoder.js';
6
7
  /** Options of {@link Animation} */
7
8
  export interface AnimationOptions {
8
- /** How many times to repeat the animation (-1 = forever, 0 = play once). Default: `-1` */
9
+ /**
10
+ * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still
11
+ * means forever, it will be removed in 4.0. Default: forever
12
+ */
9
13
  loopCount?: number;
10
14
  }
11
15
  /** Options of {@link Animation.decode} */
@@ -22,6 +26,22 @@ export interface AnimationDecodeOptions {
22
26
  applyColorProfile?: boolean;
23
27
  /** At most this many worker threads decode in parallel, like `threads` of {@link Image.decode}. Default: the processors available, at most 8 */
24
28
  threads?: number;
29
+ /**
30
+ * Whether to rotate/mirror the frames as the orientation tag (Exif, JPEG XL's header, PNG's eXIf chunk or XMP)
31
+ * says, like `applyOrientation` of {@link Image.decode}: APNGs, animated WebPs and JPEG XLs. Default: `true`
32
+ */
33
+ applyOrientation?: boolean;
34
+ /**
35
+ * How HDR (PQ or HLG) JPEG XL animations, whose light can be brighter than (SDR) white, become 8 bit sRGB, like
36
+ * `toneMapping` of {@link Image.decode}: `'reinhard'` compresses the brightest parts, `'clamp'` clamps everything
37
+ * brighter than white. Default: `'reinhard'`
38
+ */
39
+ toneMapping?: ToneMapping;
40
+ /**
41
+ * Whether to read the gain map (jhgm box) of JPEG XL animations into {@link Image.gainMap} of every frame, like
42
+ * `gainMap` of {@link Image.decode}. Default: `true`
43
+ */
44
+ gainMap?: boolean;
25
45
  }
26
46
  /** The options all animation encoders have */
27
47
  export interface AnimationEncodeOptions {
@@ -67,7 +87,11 @@ export interface APNGEncodeOptions extends AnimationEncodeOptions {
67
87
  * plain arrays.
68
88
  */
69
89
  export declare class Animation extends Array<Frame> {
70
- /** How many times to repeat the animation (-1 = forever, 0 = play once) */
90
+ /**
91
+ * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still
92
+ * means forever, it will be removed in 4.0, when `Infinity` is what animations that loop forever have (animations
93
+ * that loop forever have `-1` until then, also the decoded ones)
94
+ */
71
95
  loopCount: number;
72
96
  /**
73
97
  * Creates a new animation
@@ -78,7 +102,8 @@ export declare class Animation extends Array<Frame> {
78
102
  /**
79
103
  * Creates a new animation
80
104
  * @param frames The frames to create the animation from
81
- * @param loopCount How many times to repeat the animation (-1 = forever, 0 = play once)
105
+ * @param loopCount How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...)
106
+ * @deprecated Pass {@link AnimationOptions} instead, the positional arguments will be removed in 4.0
82
107
  */
83
108
  constructor(frames: Frame[], loopCount?: number);
84
109
  /**
@@ -111,7 +136,7 @@ export declare class Animation extends Array<Frame> {
111
136
  slice(start?: number, end?: number): this;
112
137
  /**
113
138
  * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
114
- * Use {@link ResizeModes.AUTO} as either width or height to automatically preserve the aspect ratio.
139
+ * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
115
140
  * @param width The new width
116
141
  * @param height The new height
117
142
  * @param options See {@link ResizeOptions}
@@ -119,12 +144,19 @@ export declare class Animation extends Array<Frame> {
119
144
  resize(width: number, height: number, options?: ResizeOptions): this;
120
145
  /**
121
146
  * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
122
- * Use {@link ResizeModes.AUTO} as either width or height to automatically preserve the aspect ratio.
147
+ * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
123
148
  * @param width The new width
124
149
  * @param height The new height
125
150
  * @param mode The resizing mode to use. Default: {@link ResizeModes.BILINEAR}
151
+ * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0
126
152
  */
127
153
  resize(width: number, height: number, mode?: ResizeMode): this;
154
+ /**
155
+ * Resizes the animation, scaling every frame and its offsets proportionally: to the given width or height (the
156
+ * other side keeps the aspect ratio), or to both
157
+ * @param options The size and how to resize, see {@link ResizeToOptions}
158
+ */
159
+ resize(options: ResizeToOptions): this;
128
160
  /**
129
161
  * Encodes the animation as GIF. Like all encoders, it stores each frame as the area that changed since the frame
130
162
  * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
@@ -139,6 +171,7 @@ export declare class Animation extends Array<Frame> {
139
171
  * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
140
172
  * after the frames are composited
141
173
  * @param quality 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above)
174
+ * @deprecated Pass {@link GIFEncodeOptions} instead, the positional arguments will be removed in 4.0
142
175
  */
143
176
  encodeGIF(quality?: number): Promise<Uint8Array>;
144
177
  /**
@@ -155,6 +188,7 @@ export declare class Animation extends Array<Frame> {
155
188
  * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
156
189
  * necessarily decode to the same frames
157
190
  * @param compression The zlib compression level (0-9), higher is smaller but slower. Default: `4`
191
+ * @deprecated Pass {@link APNGEncodeOptions} instead, the positional arguments will be removed in 4.0
158
192
  */
159
193
  encodeAPNG(compression?: number): Promise<Uint8Array>;
160
194
  /**
@@ -170,26 +204,26 @@ export declare class Animation extends Array<Frame> {
170
204
  * with `{ duration }`), then `await encoder.finish()` for the file
171
205
  * @param width The canvas width
172
206
  * @param height The canvas height
173
- * @param options See {@link WebPAnimationEncoderOptions}
207
+ * @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
174
208
  */
175
- static webpEncoder(width: number, height: number, options?: WebPAnimationEncoderOptions): AnimationEncoder;
209
+ static webpEncoder(width: number, height: number, options?: WebPAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
176
210
  /**
177
211
  * An encoder that makes an animated GIF a frame at a time, like {@link Animation.encodeGIF} (the same file),
178
212
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()`
179
213
  * @param width The canvas width
180
214
  * @param height The canvas height
181
- * @param options See {@link GIFAnimationEncoderOptions}
215
+ * @param options See {@link GIFEncodeOptions}, and {@link AnimationOptions.loopCount}
182
216
  */
183
- static gifEncoder(width: number, height: number, options?: GIFAnimationEncoderOptions): AnimationEncoder;
217
+ static gifEncoder(width: number, height: number, options?: GIFEncodeOptions & AnimationOptions): AnimationEncoder;
184
218
  /**
185
219
  * An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the
186
220
  * frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame,
187
221
  * then `await encoder.finish()`
188
222
  * @param width The canvas width
189
223
  * @param height The canvas height
190
- * @param options See {@link APNGAnimationEncoderOptions}
224
+ * @param options See {@link APNGEncodeOptions}, and {@link AnimationOptions.loopCount}
191
225
  */
192
- static apngEncoder(width: number, height: number, options?: APNGAnimationEncoderOptions): AnimationEncoder;
226
+ static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
193
227
  /**
194
228
  * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
195
229
  * @param input The binary data to decode
@@ -200,6 +234,7 @@ export declare class Animation extends Array<Frame> {
200
234
  * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
201
235
  * @param input The binary data to decode
202
236
  * @param onlyExtractFirstFrame Whether to stop decoding after the first frame
237
+ * @deprecated Pass {@link AnimationDecodeOptions} instead, the positional arguments will be removed in 4.0
203
238
  */
204
239
  static decode(input: BinaryData, onlyExtractFirstFrame?: boolean): Promise<Animation>;
205
240
  }
package/dist/animation.js CHANGED
@@ -5,7 +5,8 @@ import * as webp from "./codecs/webp.js";
5
5
  import * as jxl from "./codecs/jxl.js";
6
6
  import { availableThreads } from "./util/threads.js";
7
7
  import { view } from "./util/mem.js";
8
- import { Image, ResizeModes } from "./image.js";
8
+ import { GainMap } from "./gainmap.js";
9
+ import { Image, ResizeModes, resizeArguments } from "./image.js";
9
10
  import { Frame, FrameDisposalModes } from "./frame.js";
10
11
  import { ImageType } from "./image-type.js";
11
12
  import { optimize } from "./util/optimize.js";
@@ -13,7 +14,7 @@ import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
13
14
  import { isOptions, finite, compressionLevel } from "./util/options.js";
14
15
  import { MAX_PIXELS, decoding } from "./util/limits.js";
15
16
  import { AnimationEncoder } from "./animation-encoder.js";
16
- const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
17
+ const toPlays = (loopCount) => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1;
17
18
  const fromPlays = (plays) => plays === 0 ? -1 : plays - 1;
18
19
  function canvasFrames(width, height, frames) {
19
20
  return frames.map(({ pixels, duration }) => {
@@ -32,7 +33,7 @@ export class Animation extends Array {
32
33
  for (let i = 0; i < this.length; i++)
33
34
  if (!(this[i] instanceof Frame))
34
35
  throw new TypeError(`Frame ${i} is not an instance of Frame`);
35
- if (finite(loopCount, 'loop count') < -1 || !Number.isInteger(Number(loopCount)))
36
+ if (loopCount !== Infinity && (finite(loopCount, 'loop count') < -1 || !Number.isInteger(Number(loopCount))))
36
37
  throw new RangeError(`Invalid loop count: ${loopCount}`);
37
38
  this.loopCount = loopCount;
38
39
  }
@@ -77,7 +78,8 @@ export class Animation extends Array {
77
78
  const Class = this.constructor;
78
79
  return new Class(Array.prototype.slice.call(this, start, end), this.loopCount);
79
80
  }
80
- resize(width, height, modeOrOptions) {
81
+ resize(widthOrOptions, heightArgument, modeArgument) {
82
+ let [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument);
81
83
  const originalWidth = this.width, originalHeight = this.height;
82
84
  if (width === ResizeModes.AUTO && height === ResizeModes.AUTO)
83
85
  throw new Error('RESIZE_AUTO can only be used for either width or height, not for both');
@@ -89,7 +91,8 @@ export class Animation extends Array {
89
91
  for (const frame of this) {
90
92
  const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy);
91
93
  const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy);
92
- Image.prototype.resize.call(frame, Math.max(1, right - left), Math.max(1, bottom - top), modeOrOptions);
94
+ Image.prototype.resize
95
+ .call(frame, Math.max(1, right - left), Math.max(1, bottom - top), modeOrOptions);
93
96
  frame.xOffset = left;
94
97
  frame.yOffset = top;
95
98
  }
@@ -191,11 +194,20 @@ export class Animation extends Array {
191
194
  throw new RangeError(`threads must be a positive integer, not ${threads}`);
192
195
  if (!(Number(maxPixels) > 0))
193
196
  throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
197
+ const { toneMapping = 'reinhard' } = onlyFirstFrameOrOptions;
198
+ if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
199
+ throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
194
200
  }
195
201
  return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
196
202
  }
197
203
  static async __decode__(input, onlyFirstFrameOrOptions) {
198
- const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)) } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
204
+ const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)), applyOrientation = true, toneMapping = 'reinhard', gainMap = true } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
205
+ const orient = (frames, orientation) => {
206
+ if (applyOrientation && orientation > 1)
207
+ for (const frame of frames)
208
+ frame.__orient__(orientation);
209
+ return frames;
210
+ };
199
211
  const profile = (frames, icc, space) => {
200
212
  const transform = !applyColorProfile ? null : icc ? profileTransform(icc) : space ? colorSpaceTransform(space.xy, space.curve) : null;
201
213
  if (transform)
@@ -209,35 +221,55 @@ export class Animation extends Array {
209
221
  return Animation.__fromGIF__(data, onlyExtractFirstFrame, Animation, maxPixels);
210
222
  if (type === 'webp') {
211
223
  const decoded = webp.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
212
- const frames = profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc);
224
+ const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation);
213
225
  return new Animation(frames, fromPlays(decoded.loopCount));
214
226
  }
215
227
  if (type === 'png' && !png.isAnimated(data)) {
216
- const image = await Image.decode(data, { maxPixels, applyOrientation: false, applyColorProfile });
228
+ const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile });
217
229
  return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), -1);
218
230
  }
219
231
  if (type === 'png') {
220
232
  const decoded = await png.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
221
- const frames = profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc);
233
+ const frames = orient(profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc), decoded.orientation);
222
234
  return new Animation(frames, decoded.frames.length > 1 ? fromPlays(decoded.plays) : -1);
223
235
  }
224
236
  if (type === 'jxl') {
225
237
  const frames = [];
226
238
  let loopCount = -1, icc, space;
227
- for await (const decoded of jxl.frames(data, maxPixels, 'reinhard', threads)) {
239
+ let orientation = 1;
240
+ for await (const decoded of jxl.frames(data, maxPixels, toneMapping, threads)) {
228
241
  const frame = new Frame(decoded.width, decoded.height, decoded.duration, 0, 0, FrameDisposalModes.BACKGROUND);
229
242
  frame.bitmap = decoded.pixels;
230
- frames.push(frame.__orient__(decoded.orientation));
243
+ frames.push(frame);
244
+ orientation = decoded.orientation;
231
245
  loopCount = fromPlays(decoded.loopCount);
232
246
  icc = decoded.icc;
233
247
  space = decoded.colorSpace;
234
248
  if (onlyExtractFirstFrame)
235
249
  break;
236
250
  }
237
- return new Animation(profile(frames, icc, space), frames.length > 1 ? loopCount : -1);
251
+ const map = gainMap && data[0] !== 0xff ? await jxl.decodeGainMap(data, maxPixels).catch(() => undefined) : undefined;
252
+ if (map)
253
+ for (const frame of frames) {
254
+ const image = new Image(map.width, map.height);
255
+ image.bitmap = map.pixels.slice();
256
+ frame.gainMap = GainMap.__from_pixels__(image, map.params);
257
+ }
258
+ for (const frame of orient(profile(frames, icc, space), orientation)) {
259
+ const mapOfFrame = frame.gainMap;
260
+ if (!mapOfFrame || !applyOrientation || orientation <= 1)
261
+ continue;
262
+ try {
263
+ mapOfFrame.image = mapOfFrame.image.__orient__(orientation);
264
+ }
265
+ catch {
266
+ frame.gainMap = null;
267
+ }
268
+ }
269
+ return new Animation(frames, frames.length > 1 ? loopCount : -1);
238
270
  }
239
271
  if (type)
240
- return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyColorProfile }), 0)]);
272
+ return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads }), 0)]);
241
273
  throw new Error('Unsupported image type');
242
274
  }
243
275
  static __fromGIF__(data, onlyExtractFirstFrame, Class, maxPixels = MAX_PIXELS) {
@@ -29,7 +29,7 @@ export function header(width, height, loopCount, comments) {
29
29
  out.bytes(0x21, 0xff, 0x0b);
30
30
  out.string('NETSCAPE2.0');
31
31
  out.bytes(0x03, 0x01);
32
- out.u16(loopCount === -1 ? 0 : loopCount);
32
+ out.u16(loopCount === -1 || loopCount === Infinity ? 0 : loopCount);
33
33
  out.bytes(0x00);
34
34
  }
35
35
  for (const comment of comments) {
@@ -157,7 +157,7 @@ export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinha
157
157
  }
158
158
  throw new Error('JPEG XL: no frame shown');
159
159
  }
160
- async function decodeGainMap(data, maxPixels) {
160
+ export async function decodeGainMap(data, maxPixels) {
161
161
  for (const { type, content: c } of boxesOf(data)) {
162
162
  if (type !== 'jhgm')
163
163
  continue;
@@ -543,10 +543,11 @@ export function isAnimated(array) {
543
543
  export async function decodeAnimation(array, onlyFirstFrame = false, maxPixels = MAX_PIXELS) {
544
544
  const p = parse(array);
545
545
  const { width, height } = p.header;
546
+ const orientation = p.exif ? exifOrientation(p.exif) : await textOrientation(p.text);
546
547
  checkPixels(width, height, maxPixels, !p.animation || p.animationError || onlyFirstFrame ? 1 : Math.max(1, p.frames.length));
547
548
  if (!p.animation || p.animationError) {
548
549
  const pixels = await decodeImageData(p, p.idat, width, height);
549
- return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp) };
550
+ return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp), orientation };
550
551
  }
551
552
  const frames = [];
552
553
  for (const { control: c, data } of p.frames) {
@@ -561,7 +562,7 @@ export async function decodeAnimation(array, onlyFirstFrame = false, maxPixels =
561
562
  if (onlyFirstFrame)
562
563
  break;
563
564
  }
564
- return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp) };
565
+ return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp), orientation };
565
566
  }
566
567
  export function compositeAnimation({ width, height, frames }) {
567
568
  const canvas = new Uint8Array(width * height * 4);
@@ -141,7 +141,7 @@ export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PI
141
141
  const header = list[0];
142
142
  if (!header || header.type !== VP8X || !list.some(c => c.type === ANMF)) {
143
143
  const { width, height, pixels } = decodeBitstream(list, maxPixels);
144
- return { width, height, loopCount: 0, background: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, blend: false, dispose: false, pixels }], icc: list.find(c => c.type === ICCP)?.data };
144
+ return { width, height, loopCount: 0, background: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, blend: false, dispose: false, pixels }], icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) };
145
145
  }
146
146
  if (header.data.length < 10)
147
147
  throw new Error('WebP: invalid VP8X chunk');
@@ -176,7 +176,11 @@ export function decodeAnimation(data, onlyFirstFrame = false, maxPixels = MAX_PI
176
176
  }
177
177
  if (!frames.length)
178
178
  throw new Error('WebP: animation without frames');
179
- return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data };
179
+ return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) };
180
+ }
181
+ function orientationOf(list) {
182
+ const exif = list.find(c => c.type === EXIF);
183
+ return exif ? exifOrientation(exif.data) : 1;
180
184
  }
181
185
  export function composite({ width, height, frames }) {
182
186
  const canvas = new Uint8Array(width * height * 4);
package/dist/frame.d.ts CHANGED
@@ -1,7 +1,11 @@
1
- import { Image, ResizeMode, ResizeOptions, Color, TrimOptions } from './image.js';
1
+ import { Image, ResizeMode, ResizeOptions, ResizeToOptions, Color, TrimOptions } from './image.js';
2
2
  /** Names of the frame disposal modes, see {@link Frame.disposalMode} */
3
3
  export type FrameDisposalModeName = 'any' | 'keep' | 'previous' | 'background';
4
- /** Ids of the frame disposal modes, as GIFs store them (0 any, 1 keep, 2 previous, 3 background) */
4
+ /**
5
+ * Ids of the frame disposal modes, as GIFs store them (0 any, 1 keep, 2 previous, 3 background)
6
+ * @deprecated Use the names ({@link FrameDisposalModeName}: `'any'`, `'keep'`, `'previous'`, `'background'`), the ids will
7
+ * be removed in 4.0
8
+ */
5
9
  export type FrameDisposalModeId = 0 | 1 | 2 | 3;
6
10
  /** What happens to a frame's area before the next frame is drawn, see {@link Frame.disposalMode} */
7
11
  export declare class FrameDisposalModes {
@@ -75,13 +79,17 @@ export declare class Frame extends Image {
75
79
  * @param xOffset The frame's offset on the x-axis
76
80
  * @param yOffset The frame's offset on the y-axis
77
81
  * @param disposalMode The frame's disposal mode
82
+ * @deprecated Pass {@link FrameOptions} instead, the positional arguments will be removed in 4.0
78
83
  */
79
84
  constructor(width: number, height: number, duration?: number, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId);
80
- /** The frame's disposal mode (`'any'`, `'keep'`, `'previous'` or `'background'`); also settable by id (0-3) */
85
+ /**
86
+ * The frame's disposal mode (`'any'`, `'keep'`, `'previous'` or `'background'`). Setting it by id (0-3) is deprecated,
87
+ * the ids will be removed in 4.0
88
+ */
81
89
  get disposalMode(): FrameDisposalModeName;
82
90
  /**
83
91
  * Sets the disposal mode
84
- * @param disposalMode The mode's name (`'any'`, `'keep'`, `'previous'`, `'background'`) or id (0-3)
92
+ * @param disposalMode The mode's name (`'any'`, `'keep'`, `'previous'`, `'background'`) or, deprecated, its id (0-3)
85
93
  */
86
94
  set disposalMode(disposalMode: FrameDisposalModeName | FrameDisposalModeId);
87
95
  /** A short description for debugging, e.g. `Frame<64x64x100ms>` */
@@ -99,24 +107,45 @@ export declare class Frame extends Image {
99
107
  * @param xOffset The frame's offset on the x-axis
100
108
  * @param yOffset The frame's offset on the y-axis
101
109
  * @param disposalMode The frame's disposal mode
110
+ * @deprecated Pass {@link FrameOptions} instead, the positional arguments will be removed in 4.0
102
111
  */
103
112
  static from(image: Image, duration?: number, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId): Frame;
104
113
  /**
105
114
  * Clones the frame, including its duration, offsets and disposal mode
106
115
  */
107
116
  clone(): Frame;
117
+ /**
118
+ * Removes borders of one color, moving the frame's offsets so the remaining pixels stay in place
119
+ * @param options See {@link TrimOptions}
120
+ */
121
+ trim(options?: TrimOptions): this;
108
122
  /**
109
123
  * Removes borders of one color, moving the frame's offsets so the remaining pixels stay in place
110
124
  * @param color The border color, by default the color of the top left pixel
111
125
  * @param options See {@link TrimOptions}
126
+ * @deprecated Pass {@link TrimOptions} instead, the positional arguments will be removed in 4.0
112
127
  */
113
128
  trim(color?: Color, options?: TrimOptions): this;
114
129
  /**
115
130
  * Resizes the frame, scaling its offsets along with it.
116
- * Use {@link ResizeModes.AUTO} as either width or height to automatically preserve the aspect ratio.
131
+ * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
117
132
  * @param width The new width
118
133
  * @param height The new height
119
- * @param modeOrOptions The resizing mode (default: {@link ResizeModes.BILINEAR}) or {@link ResizeOptions}
134
+ * @param options See {@link ResizeOptions}
135
+ */
136
+ resize(width: number, height: number, options?: ResizeOptions): this;
137
+ /**
138
+ * Resizes the frame, scaling its offsets along with it.
139
+ * @param width The new width
140
+ * @param height The new height
141
+ * @param mode The resizing mode (default: {@link ResizeModes.BILINEAR})
142
+ * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0
143
+ */
144
+ resize(width: number, height: number, mode?: ResizeMode): this;
145
+ /**
146
+ * Resizes the frame, scaling its offsets along with it: to the given width or height (the other side keeps the
147
+ * aspect ratio), or to both
148
+ * @param options The size and how to resize, see {@link ResizeToOptions}
120
149
  */
121
- resize(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this;
150
+ resize(options: ResizeToOptions): this;
122
151
  }
package/dist/frame.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Image } from "./image.js";
1
+ import { Image, resizeArguments } from "./image.js";
2
2
  import { isOptions, finite } from "./util/options.js";
3
3
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
4
4
  export class FrameDisposalModes {
@@ -58,7 +58,15 @@ export class Frame extends Image {
58
58
  clone() {
59
59
  return Frame.from(this, { duration: this.duration, xOffset: this.xOffset, yOffset: this.yOffset, disposalMode: this.disposalMode });
60
60
  }
61
- trim(color, options = {}) {
61
+ __room__() {
62
+ return { left: this.xOffset, top: this.yOffset };
63
+ }
64
+ __grown__(left, top) {
65
+ this.xOffset -= left;
66
+ this.yOffset -= top;
67
+ }
68
+ trim(colorOrOptions, optionsArgument = {}) {
69
+ const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color };
62
70
  const bounds = this.__trim_bounds__(color, options);
63
71
  if (!bounds)
64
72
  return this;
@@ -66,7 +74,8 @@ export class Frame extends Image {
66
74
  this.yOffset += bounds[1];
67
75
  return this.__apply__(this.__crop__(...bounds));
68
76
  }
69
- resize(width, height, modeOrOptions) {
77
+ resize(widthOrOptions, heightArgument, modeArgument) {
78
+ const [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument);
70
79
  const originalWidth = this.width;
71
80
  const originalHeight = this.height;
72
81
  super.resize(width, height, modeOrOptions);
package/dist/gainmap.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { Image } from './image.js';
2
2
  import { BinaryData } from './util/mem.js';
3
+ /** Options of {@link GainMap.encode} */
4
+ export interface GainMapEncodeOptions {
5
+ /** The JPEG quality (1-100). Default: `90` */
6
+ quality?: number;
7
+ }
3
8
  /** Options of the {@link GainMap} constructor: per channel values can be one number for all three or [r, g, b] */
4
9
  export interface GainMapOptions {
5
10
  /** log2 of the boost of the map's value 0 (`-1`: half as bright). Default: `0` */
@@ -71,10 +76,17 @@ export declare class GainMap {
71
76
  get channels(): 1 | 3;
72
77
  /** Clones the gain map (its pixels too) */
73
78
  clone(): GainMap;
79
+ /**
80
+ * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an
81
+ * Ultra HDR JPEG
82
+ * @param options See {@link GainMapEncodeOptions}
83
+ */
84
+ encode(options?: GainMapEncodeOptions): Promise<Uint8Array>;
74
85
  /**
75
86
  * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an
76
87
  * Ultra HDR JPEG
77
88
  * @param quality The JPEG quality (1-100). Default: `90`
89
+ * @deprecated Pass {@link GainMapEncodeOptions} instead, the positional arguments will be removed in 4.0
78
90
  */
79
91
  encode(quality?: number): Promise<Uint8Array>;
80
92
  /**
package/dist/gainmap.js CHANGED
@@ -2,7 +2,7 @@ import { Image } from "./image.js";
2
2
  import * as jpeg from "./codecs/jpeg.js";
3
3
  import * as codec from "./codecs/gainmap.js";
4
4
  import { view } from "./util/mem.js";
5
- import { finite, quality as checkQuality } from "./util/options.js";
5
+ import { finite, isOptions, quality as checkQuality } from "./util/options.js";
6
6
  const perChannel = (value, name) => {
7
7
  const values = typeof value === 'number' ? [value, value, value] : Array.from(value);
8
8
  if (values.length === 1)
@@ -177,7 +177,8 @@ export class GainMap {
177
177
  }
178
178
  this.image = out;
179
179
  }
180
- async encode(quality) {
180
+ async encode(qualityOrOptions) {
181
+ let quality = isOptions(qualityOrOptions) ? qualityOrOptions.quality : qualityOrOptions;
181
182
  if (quality !== undefined)
182
183
  quality = Math.max(1, checkQuality(quality));
183
184
  return codec.mapWithMetadata(this.__body__(quality), this.__params__());