imagescript 4.0.0-rc.1 → 4.0.0-rc.3

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/dist/image.js CHANGED
@@ -13,10 +13,6 @@ import * as avif from "./codecs/avif.js";
13
13
  import * as avifEnc from "./codecs/avif-enc.js";
14
14
  import { availableThreads } from "./util/threads.js";
15
15
  const defaultThreads = () => Math.max(1, Math.min(availableThreads(), 8));
16
- const checkThreads = (threads) => {
17
- if (!Number.isInteger(threads) || threads < 1)
18
- throw new RangeError(`threads must be a positive integer, not ${threads}`);
19
- };
20
16
  import * as jxl from "./codecs/jxl.js";
21
17
  import * as quantize from "./codecs/quantize.js";
22
18
  import * as textRenderer from "./render/text.js";
@@ -24,20 +20,24 @@ import * as svgRenderer from "./render/svg.js";
24
20
  import { view } from "./util/mem.js";
25
21
  import { cicpTransform, colorSpaceTransform, profileTransform } from "./util/icc.js";
26
22
  import { ImageType } from "./image-type.js";
27
- import { TextLayout } from "./text-layout.js";
23
+ import { textLayout } from "./text-layout.js";
28
24
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
29
25
  import { encode as utf8 } from "./util/utf8.js";
30
26
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
31
27
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
32
28
  import { Colors, wrapHue, hue2rgb } from "./colors.js";
33
- import { isOptions, checkOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
- import { MAX_PIXELS, decoding } from "./util/limits.js";
29
+ import { isOptions, checkOptions, finite, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
30
+ import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
35
31
  import { GainMap } from "./gainmap.js";
36
32
  import * as gain from "./util/gain.js";
37
33
  import { multiply, invert } from "./util/matrix.js";
38
34
  import { sampleAffine } from "./util/affine.js";
39
35
  import * as gainMapCodec from "./codecs/gainmap.js";
40
36
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
37
+ const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
38
+ const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
39
+ export const TONE_MAPPINGS = ['reinhard', 'clamp'];
40
+ export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
41
41
  function featureList(features) {
42
42
  if (typeof features !== 'object' || features === null)
43
43
  throw new TypeError('Features must be an object');
@@ -89,6 +89,8 @@ export class Image {
89
89
  throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array');
90
90
  if (bitmap.length !== this.width * this.height * 4)
91
91
  throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`);
92
+ if (bitmap.byteOffset % 4)
93
+ throw new TypeError(`The bitmap has to start at a byte offset divisible by 4 to be used without copying, not ${bitmap.byteOffset} (pass bitmap.slice() for a copy)`);
92
94
  this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length));
93
95
  }
94
96
  __set_bitmap__(bitmap) {
@@ -107,11 +109,6 @@ export class Image {
107
109
  get height() {
108
110
  return this.__height__;
109
111
  }
110
- *coordinates() {
111
- for (let y = 0; y < this.height; y++)
112
- for (let x = 0; x < this.width; x++)
113
- yield [x, y];
114
- }
115
112
  *pixels() {
116
113
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
117
114
  let offset = 0;
@@ -125,6 +122,7 @@ export class Image {
125
122
  const color = gradientFunction(stops);
126
123
  finite(angle, 'angle');
127
124
  const image = new Image(width, height);
125
+ ({ width, height } = image);
128
126
  const radians = angle * Math.PI / 180;
129
127
  const dx = Math.sin(radians), dy = -Math.cos(radians);
130
128
  const length = Math.abs(width * dx) + Math.abs(height * dy);
@@ -136,13 +134,14 @@ export class Image {
136
134
  }
137
135
  static radialGradient(width, height, options) {
138
136
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
137
+ const image = new Image(width, height);
138
+ ({ width, height } = image);
139
139
  const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
140
140
  const color = gradientFunction(stops);
141
141
  finite(cx, 'x');
142
142
  finite(cy, 'y');
143
143
  if (!(finite(radius, 'radius') > 0))
144
144
  throw new RangeError('Invalid radius');
145
- const image = new Image(width, height);
146
145
  const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
147
146
  for (let y = 0, i = 0; y < height; y++)
148
147
  for (let x = 0; x < width; x++, i += 4)
@@ -150,14 +149,14 @@ export class Image {
150
149
  return image;
151
150
  }
152
151
  getPixelAt(x, y) {
153
- x = ~~finite(x, 'x');
154
- y = ~~finite(y, 'y');
152
+ x = Math.trunc(finite(x, 'x'));
153
+ y = Math.trunc(finite(y, 'y'));
155
154
  this.__check_boundaries__(x, y);
156
155
  return this.__view__.getUint32((y * this.width + x) * 4, false);
157
156
  }
158
157
  setPixelAt(x, y, color) {
159
- x = ~~finite(x, 'x');
160
- y = ~~finite(y, 'y');
158
+ x = Math.trunc(finite(x, 'x'));
159
+ y = Math.trunc(finite(y, 'y'));
161
160
  this.__check_boundaries__(x, y);
162
161
  this.__set_pixel__(x, y, checkColor(color));
163
162
  return this;
@@ -186,21 +185,19 @@ export class Image {
186
185
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
187
186
  if (typeof color !== 'function')
188
187
  color = checkColor(color);
189
- if (this.__gain_map__)
190
- this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
191
188
  if (typeof color === 'function') {
192
189
  let offset = 0;
193
190
  for (let y = 0; y < this.height; y++)
194
191
  for (let x = 0; x < this.width; x++, offset += 4)
195
- view.setUint32(offset, color(x, y), false);
192
+ view.setUint32(offset, checkColor(color(x, y)), false);
196
193
  }
197
194
  else {
198
- if (!this.bitmap.length)
199
- return this;
200
195
  view.setUint32(0, color, false);
201
196
  const u32 = new Uint32Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength / 4);
202
197
  u32.fill(u32[0]);
203
198
  }
199
+ if (this.__gain_map__)
200
+ this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
204
201
  return this;
205
202
  }
206
203
  clone() {
@@ -213,16 +210,17 @@ export class Image {
213
210
  }
214
211
  scale(factor, options) {
215
212
  checkOptions(options, 'scale(factor, { mode: \'area\' })');
216
- const { mode, fast } = resizeOptions(options);
217
- const image = this.__scale__(factor, mode, fast);
213
+ const { mode } = resizeOptions(options);
214
+ const image = this.__scale__(factor, mode);
218
215
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
219
216
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
220
217
  return this.__apply__(image);
221
218
  }
222
- __scale__(factor, mode = 'bilinear', fast = true) {
219
+ __scale__(factor, mode = 'bilinear') {
223
220
  if (factor === 1)
224
221
  return this;
225
- return this.__resize__(this.width * factor, this.height * factor, mode, fast);
222
+ const size = (side) => factor > 0 ? Math.max(1, side * factor) : side * factor;
223
+ return this.__resize__(size(this.width), size(this.height), mode);
226
224
  }
227
225
  resize(widthOrOptions, heightArgument, optionsArgument) {
228
226
  const [width, height, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument);
@@ -233,8 +231,8 @@ export class Image {
233
231
  ? this.__contain__(width, height, options)
234
232
  : this.__cover__(width, height, options);
235
233
  }
236
- const { mode, fast } = resizeOptions(options);
237
- const image = this.__resize__(...this.__resized_size__(width, height, fit), mode, fast);
234
+ const { mode } = resizeOptions(options);
235
+ const image = this.__resize__(...this.__resized_size__(width, height, fit), mode);
238
236
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
239
237
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
240
238
  return this.__apply__(image);
@@ -274,7 +272,7 @@ export class Image {
274
272
  const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
275
273
  this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
276
274
  this.__moved__?.(fx, fy, region.x, region.y);
277
- return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, resizeOpts.fast, region));
275
+ return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region));
278
276
  }
279
277
  this.resize(resizedWidth, resizedHeight, resizeOpts);
280
278
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
@@ -288,20 +286,19 @@ export class Image {
288
286
  return [width, Math.max(1, Math.round(this.height / this.width * Math.floor(width)))];
289
287
  return [width, height];
290
288
  }
291
- __resize__(width, height, mode = 'bilinear', fast = true, region) {
289
+ __resize__(width, height, mode = 'bilinear', region) {
292
290
  width = Math.floor(width);
293
291
  height = Math.floor(height);
294
292
  if (width < 1)
295
293
  throw new RangeError('Image has to be at least 1 pixel wide');
296
294
  if (height < 1)
297
295
  throw new RangeError('Image has to be at least 1 pixel high');
296
+ oneOf(mode, RESIZE_MODES, 'resize mode');
298
297
  if (mode === 'nearest-neighbor')
299
298
  return this.__resize_nearest_neighbor__(width, height);
300
- const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : mode === 'area' ? BOX : null;
301
- if (!filter)
302
- throw new Error('Invalid resize mode');
299
+ const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX;
303
300
  const image = new Image(region?.width ?? width, region?.height ?? height);
304
- resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
301
+ resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, true, region);
305
302
  return image;
306
303
  }
307
304
  __resize_nearest_neighbor__(width, height) {
@@ -336,10 +333,10 @@ export class Image {
336
333
  return image;
337
334
  }
338
335
  __crop_bounds__(x, y, width, height) {
339
- x = ~~finite(x, 'x');
340
- y = ~~finite(y, 'y');
341
- width = ~~finite(width, 'width');
342
- height = ~~finite(height, 'height');
336
+ x = Math.trunc(finite(x, 'x'));
337
+ y = Math.trunc(finite(y, 'y'));
338
+ width = Math.trunc(finite(width, 'width'));
339
+ height = Math.trunc(finite(height, 'height'));
343
340
  const left = Math.max(0, x), top = Math.max(0, y);
344
341
  const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
345
342
  if (right <= left || bottom <= top)
@@ -459,11 +456,11 @@ export class Image {
459
456
  }
460
457
  return this;
461
458
  }
462
- opacity(opacity) {
463
- opacity = finite(opacity, 'opacity value');
464
- if (opacity < 0)
459
+ opacity(factor) {
460
+ factor = finite(factor, 'opacity value');
461
+ if (factor < 0)
465
462
  throw new RangeError('Invalid opacity value');
466
- this.__set_channel_value__(opacity, 3);
463
+ this.__set_channel_value__(factor, 3);
467
464
  return this;
468
465
  }
469
466
  red(factor) {
@@ -515,15 +512,15 @@ export class Image {
515
512
  }
516
513
  composite(source, options = {}) {
517
514
  checkOptions(options, 'composite(source, { x: 10, y: 20 })');
515
+ if (!(source instanceof Image))
516
+ throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { x: 10, y: 20 })');
518
517
  const { opacity = 1, mode = 'normal' } = options;
519
518
  let x = options.x ?? 0, y = options.y ?? 0;
520
- x = finite(x, 'x') | 0;
521
- y = finite(y, 'y') | 0;
519
+ x = Math.trunc(finite(x, 'x'));
520
+ y = Math.trunc(finite(y, 'y'));
522
521
  if (isNaN(opacity) || opacity < 0 || opacity > 1)
523
522
  throw new RangeError('Invalid composite opacity');
524
- const blend = BLEND_MODES[mode];
525
- if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
526
- throw new RangeError(`Invalid blend mode: ${mode}`);
523
+ const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
527
524
  if (opacity === 0)
528
525
  return this;
529
526
  if (this.__gain_map__ || source.__gain_map__)
@@ -748,8 +745,6 @@ export class Image {
748
745
  }
749
746
  quantize(options = {}) {
750
747
  checkOptions(options, 'image.quantize({ colors: 16 })');
751
- if (typeof options !== 'object' || options === null)
752
- throw new TypeError('quantize takes an options object');
753
748
  const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options;
754
749
  if (colors !== undefined && palette !== undefined)
755
750
  throw new TypeError('quantize takes colors or palette, not both');
@@ -815,11 +810,8 @@ export class Image {
815
810
  if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
816
811
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
817
812
  const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
818
- if (typeof options !== 'object' || options === null)
819
- throw new TypeError('transform takes an options object');
820
813
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
821
- if (!TRANSFORM_MODES.includes(mode))
822
- throw new TypeError(`transform mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
814
+ oneOf(mode, TRANSFORM_MODES, 'transform mode');
823
815
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
824
816
  finite(pivotX, 'origin x');
825
817
  finite(pivotY, 'origin y');
@@ -1063,8 +1055,8 @@ export class Image {
1063
1055
  }
1064
1056
  dominantColor(options = {}) {
1065
1057
  checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1066
- const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = options;
1067
- const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
1058
+ const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options;
1059
+ const threshold = Math.min(256, Math.max(0, finite(bwThreshold, 'threshold')));
1068
1060
  const pixels = this.__bytes__();
1069
1061
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1070
1062
  || quantize.dominantColor(pixels, () => true);
@@ -1073,8 +1065,7 @@ export class Image {
1073
1065
  rotate(angle, options = {}) {
1074
1066
  checkOptions(options, 'rotate(angle, { expand: false })');
1075
1067
  const { expand = true, mode = 'bilinear' } = options;
1076
- if (!TRANSFORM_MODES.includes(mode))
1077
- throw new TypeError(`rotate mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
1068
+ oneOf(mode, TRANSFORM_MODES, 'rotate mode');
1078
1069
  angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1079
1070
  if (angle === 0)
1080
1071
  return this;
@@ -1100,6 +1091,16 @@ export class Image {
1100
1091
  else
1101
1092
  dst[x * height + height - 1 - y] = i;
1102
1093
  }
1094
+ if (!expand && out.width !== width) {
1095
+ const canvas = new Image(width, height), target = canvas.__u32__, turned = out.__u32__;
1096
+ const left = Math.floor((width - out.width) / 2), top = Math.floor((height - out.height) / 2);
1097
+ for (let y = Math.max(0, top); y < Math.min(height, top + out.height); y++)
1098
+ for (let x = Math.max(0, left); x < Math.min(width, left + out.width); x++)
1099
+ target[y * width + x] = turned[(y - top) * out.width + x - left];
1100
+ rotateGainMap(width, height);
1101
+ this.__moved__?.(1, 1, 0, 0);
1102
+ return this.__apply__(canvas);
1103
+ }
1103
1104
  rotateGainMap(out.width, out.height);
1104
1105
  this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2);
1105
1106
  return this.__apply__(out);
@@ -1117,21 +1118,20 @@ export class Image {
1117
1118
  return this.__apply__(out);
1118
1119
  }
1119
1120
  flip(direction) {
1121
+ oneOf(direction, FLIP_DIRECTIONS, 'flip direction');
1120
1122
  const u32 = this.__u32__;
1121
1123
  const { width, height } = this;
1122
1124
  if (direction === 'horizontal') {
1123
1125
  for (let y = 0; y < height; y++)
1124
1126
  u32.subarray(y * width, (y + 1) * width).reverse();
1125
1127
  }
1126
- else if (direction === 'vertical') {
1128
+ else {
1127
1129
  for (let y = 0; y < height >> 1; y++) {
1128
1130
  const top = u32.slice(y * width, (y + 1) * width);
1129
1131
  u32.copyWithin(y * width, (height - 1 - y) * width, (height - y) * width);
1130
1132
  u32.set(top, (height - 1 - y) * width);
1131
1133
  }
1132
1134
  }
1133
- else
1134
- throw new RangeError('Invalid flip direction');
1135
1135
  this.__gain_map__?.__transform__(width, height, width, height, direction === 'horizontal' ? (X, Y) => [width - X, Y] : (X, Y) => [X, height - Y]);
1136
1136
  return this;
1137
1137
  }
@@ -1233,28 +1233,27 @@ export class Image {
1233
1233
  }
1234
1234
  async encodeJPEG(options = {}) {
1235
1235
  checkOptions(options, 'encodeJPEG({ quality: 80 })');
1236
- const { quality = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1237
- if (subsampling !== undefined && subsampling !== '4:4:4' && subsampling !== '4:2:0')
1238
- throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1236
+ const { quality: qualityOption = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1237
+ const quality = checkQuality(qualityOption);
1238
+ if (subsampling !== undefined)
1239
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1239
1240
  const backgroundColor = checkColor(background, 'background');
1240
1241
  const m = resolveMetadata(metadata);
1241
1242
  const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1242
1243
  const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1243
1244
  const gainMap = source.__gain_map__;
1244
1245
  if (!gainMap || gainMapOption === false)
1245
- return jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), base);
1246
+ return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1246
1247
  const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1247
1248
  let width, height;
1248
1249
  if (scale !== undefined) {
1249
- const s = finite(scale, 'gain map scale');
1250
- if (!(s > 0 && s <= 1))
1251
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1250
+ const s = gainMapScale(scale);
1252
1251
  width = Math.max(1, Math.round(this.width * s));
1253
1252
  height = Math.max(1, Math.round(this.height * s));
1254
1253
  }
1255
1254
  const params = gainMap.__params__();
1256
1255
  const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1257
- const primary = jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1256
+ const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) });
1258
1257
  return gainMapCodec.finish(primary, map);
1259
1258
  }
1260
1259
  __flattened__(background, withGainMap) {
@@ -1307,8 +1306,7 @@ export class Image {
1307
1306
  const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1308
1307
  checkEffort(effort, 2);
1309
1308
  checkThreads(threads);
1310
- if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
1311
- throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1309
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1312
1310
  const exif = exifData(resolveMetadata(metadata));
1313
1311
  return avifEnc.encode(this.__bytes__(), this.width, this.height, {
1314
1312
  quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads, gainMap: this.__gain_map_pixels__(gainMap)
@@ -1322,9 +1320,7 @@ export class Image {
1322
1320
  const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1323
1321
  let map = gainMap.image;
1324
1322
  if (scale !== undefined) {
1325
- const s = finite(scale, 'gain map scale');
1326
- if (!(s > 0 && s <= 1))
1327
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1323
+ const s = gainMapScale(scale);
1328
1324
  const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1329
1325
  if (width !== map.width || height !== map.height)
1330
1326
  map = map.clone().resize(width, height);
@@ -1348,10 +1344,8 @@ export class Image {
1348
1344
  checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
1349
1345
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1350
1346
  checkThreads(threads);
1351
- if (!(Number(maxPixels) > 0))
1352
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1353
- if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1354
- throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1347
+ pixelLimit(maxPixels);
1348
+ oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
1355
1349
  const data = view(input);
1356
1350
  const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1357
1351
  const decoded = await decoding(() => {
@@ -1403,13 +1397,13 @@ export class Image {
1403
1397
  (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
1404
1398
  }
1405
1399
  const image = new Image(decoded.width, decoded.height);
1406
- image.bitmap = decoded.pixels;
1400
+ image.bitmap = alignedPixels(decoded.pixels);
1407
1401
  if (gainMap && ImageType.isJPEG(dataView)) {
1408
1402
  try {
1409
1403
  const found = gainMapCodec.find(data);
1410
1404
  const size = found && gainMapCodec.dimensions(found.map);
1411
1405
  if (found && size && size.width * size.height <= maxPixels)
1412
- image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple);
1406
+ image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple, maxPixels);
1413
1407
  }
1414
1408
  catch {
1415
1409
  image.__gain_map__ = null;
@@ -1418,7 +1412,7 @@ export class Image {
1418
1412
  if (decoded.gainMap) {
1419
1413
  const { width, height, pixels, params } = decoded.gainMap;
1420
1414
  const map = new Image(width, height);
1421
- map.bitmap = pixels;
1415
+ map.bitmap = alignedPixels(pixels);
1422
1416
  image.__gain_map__ = GainMap.__from_pixels__(map, params);
1423
1417
  }
1424
1418
  if (applyOrientation && decoded.orientation && decoded.orientation > 1) {
@@ -1483,9 +1477,11 @@ export class Image {
1483
1477
  }
1484
1478
  static async renderSVG(svg, options = {}) {
1485
1479
  checkOptions(options, 'renderSVG(svg, { width: 512 })');
1486
- const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, fonts = [], images: givenImages = {} } = options;
1487
- if (!(Number(maxPixels) > 0))
1488
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1480
+ const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
1481
+ pixelLimit(maxPixels);
1482
+ const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
1483
+ pixelLimit(maxLayerPixels, 'maxLayerPixels');
1484
+ pixelLimit(maxImagePixels, 'maxImagePixels');
1489
1485
  const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1490
1486
  if (sizes > 1)
1491
1487
  throw new TypeError('renderSVG() takes one of width, height and scale');
@@ -1506,27 +1502,39 @@ export class Image {
1506
1502
  }
1507
1503
  const source = typeof svg === 'string' ? svg : view(svg);
1508
1504
  const images = new Map();
1505
+ const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
1506
+ let imagePixels = Number(maxImagePixels);
1509
1507
  for (const { href, data } of svgRenderer.imageReferences(source)) {
1510
1508
  const value = given.get(href) ?? data;
1511
1509
  if (!value)
1512
1510
  continue;
1511
+ if (value instanceof Image) {
1512
+ images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1513
+ continue;
1514
+ }
1515
+ const tooLarge = (cause) => new LimitError(`SVG: the image ${shown(href)} exceeds what's left of the ${maxImagePixels} pixels the SVG's images may decode to (the render options' maxImagePixels)`, { cause });
1516
+ if (!(imagePixels >= 1)) {
1517
+ images.set(href, { error: tooLarge() });
1518
+ continue;
1519
+ }
1513
1520
  try {
1514
- if (value instanceof Image) {
1515
- images.set(href, { width: value.width, height: value.height, pixels: value.bitmap });
1516
- }
1517
- else if (ImageType.getType(value) === 'gif') {
1518
- const decoded = gif.decode(view(value), true, maxPixels);
1519
- images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1521
+ let decoded;
1522
+ if (ImageType.getType(value) === 'gif') {
1523
+ const gifData = await decoding(() => gif.decode(view(value), true, imagePixels));
1524
+ decoded = { width: gifData.width, height: gifData.height, pixels: gif.composite(gifData)[0].pixels };
1520
1525
  }
1521
1526
  else {
1522
- const image = await Image.decode(value, { maxPixels });
1523
- images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1527
+ const image = await Image.decode(value, { maxPixels: imagePixels });
1528
+ decoded = { width: image.width, height: image.height, pixels: image.bitmap };
1524
1529
  }
1530
+ imagePixels -= decoded.width * decoded.height;
1531
+ images.set(href, decoded);
1525
1532
  }
1526
- catch {
1533
+ catch (err) {
1534
+ images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1527
1535
  }
1528
1536
  }
1529
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels);
1537
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), Number(maxPixels), Number(maxLayerPixels));
1530
1538
  const image = new Image(width, height);
1531
1539
  image.bitmap.set(pixels);
1532
1540
  return image;
@@ -1536,9 +1544,10 @@ export class Image {
1536
1544
  throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
1537
1545
  if (options.font === undefined)
1538
1546
  throw new TypeError('renderText(text, options) needs the font in the options');
1539
- const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1540
- const { maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks } = options;
1541
- const layout = new TextLayout({ maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks });
1547
+ const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1548
+ pixelLimit(maxPixels);
1549
+ const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
1550
+ const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1542
1551
  const axes = textRenderer.axisValues(variations);
1543
1552
  const size = finite(options.size, 'font size');
1544
1553
  if (size < 0)
@@ -1549,8 +1558,16 @@ export class Image {
1549
1558
  if (!fonts.length)
1550
1559
  throw new RangeError('No font given');
1551
1560
  const [r, g, b, a] = Colors.toRGBA(color);
1552
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes);
1553
1561
  const pad = Math.ceil(strokeWidth);
1562
+ if (layout.width !== undefined && layout.width <= 2 * pad)
1563
+ throw new RangeError(`The width (${layout.width}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1564
+ if (layout.height !== undefined && layout.height <= 2 * pad)
1565
+ throw new RangeError(`The height (${layout.height}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1566
+ if (layout.width !== undefined)
1567
+ layout.width -= 2 * pad;
1568
+ if (layout.height !== undefined)
1569
+ layout.height -= 2 * pad;
1570
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, Number(maxPixels), pad);
1554
1571
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1555
1572
  const coverage = new Uint8Array(width * height);
1556
1573
  for (let y = 0; y < rendered.height; y++)
@@ -1624,6 +1641,9 @@ function circleCoverage(px, py, cx, cy, radius) {
1624
1641
  return 0;
1625
1642
  return pixelCoverage(px, py, (x, y) => (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius);
1626
1643
  }
1644
+ export function alignedPixels(pixels) {
1645
+ return pixels.byteOffset % 4 ? pixels.slice() : pixels;
1646
+ }
1627
1647
  export function resizeArguments(widthOrOptions, height, options) {
1628
1648
  if (!isOptions(widthOrOptions)) {
1629
1649
  checkOptions(options, 'resize(width, height, { mode: \'area\' })');
@@ -1632,8 +1652,7 @@ export function resizeArguments(widthOrOptions, height, options) {
1632
1652
  const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions;
1633
1653
  if (width === undefined && optionsHeight === undefined)
1634
1654
  throw new TypeError('resize() needs a width, a height or both');
1635
- if (!['fill', 'inside', 'contain', 'cover'].includes(fit))
1636
- throw new TypeError(`fit must be 'fill', 'inside', 'contain' or 'cover', not ${String(fit)}`);
1655
+ oneOf(fit, RESIZE_FITS, 'fit');
1637
1656
  return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit];
1638
1657
  }
1639
1658
  export function insideSize(width, height, boxWidth, boxHeight) {
@@ -1642,8 +1661,9 @@ export function insideSize(width, height, boxWidth, boxHeight) {
1642
1661
  const scale = Math.min(boxWidth / width, boxHeight / height);
1643
1662
  return [Math.max(1, Math.min(boxWidth, Math.round(width * scale))), Math.max(1, Math.min(boxHeight, Math.round(height * scale)))];
1644
1663
  }
1664
+ const RESIZE_MODES = ['nearest-neighbor', 'bilinear', 'bicubic', 'area'];
1645
1665
  function resizeOptions(options) {
1646
- return { mode: options?.mode ?? 'bilinear', fast: options?.fast ?? true };
1666
+ return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode') };
1647
1667
  }
1648
1668
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1649
1669
  const BLEND_MODES = {
package/dist/index.d.ts CHANGED
@@ -1,9 +1,13 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @document ../guides/Migrating to 4.0.md
4
+ */
1
5
  import { BinaryData } from './util/mem.js';
2
6
  import { Image, DecodeOptions } from './image.js';
3
7
  import { Animation } from './animation.js';
4
8
  export { Image } from './image.js';
5
9
  export { Colors } from './colors.js';
6
- export type { Color, ColorFunction, ResizeMode, ResizeFit, TextStyleOptions, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, TGAEncodeOptions, GIFEncodeOptions, DitherMethod, GainMapEmbedOptions, RenderSVGOptions, RenderTextOptions, ShadowOptions, OutlineOptions, QuantizeOptions, TransformOptions, TransformMode, AffineTransform, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.js';
10
+ export type { Color, ColorFunction, ResizeMode, ResizeFit, TextStyleOptions, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, TGAEncodeOptions, GIFEncodeOptions, DitherMethod, DitherOptions, GainMapEmbedOptions, RenderSVGOptions, SVGResourceOptions, RenderTextOptions, ShadowOptions, OutlineOptions, QuantizeOptions, TransformOptions, TransformMode, FlipDirection, AffineTransform, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.js';
7
11
  export { Frame } from './frame.js';
8
12
  export type { FrameDisposalMode, FrameOptions } from './frame.js';
9
13
  export { GainMap } from './gainmap.js';
@@ -13,6 +17,7 @@ export type { AnimationOptions, AnimationCanvasOptions, AnimationEncodeOptions,
13
17
  export { AnimationEncoder } from './animation-encoder.js';
14
18
  export type { TextLayoutOptions, WrapStyle, HorizontalAlign, VerticalAlign } from './text-layout.js';
15
19
  export { ImageType } from './image-type.js';
20
+ export { LimitError } from './util/limits.js';
16
21
  export type { ImageTypeName } from './image-type.js';
17
22
  export type { ToneMapping } from './codecs/hdr.js';
18
23
  export type { BinaryData } from './util/mem.js';
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ export { GainMap } from "./gainmap.js";
12
12
  export { Animation } from "./animation.js";
13
13
  export { AnimationEncoder } from "./animation-encoder.js";
14
14
  export { ImageType } from "./image-type.js";
15
+ export { LimitError } from "./util/limits.js";
15
16
  export async function decode(input, options = {}) {
16
17
  checkOptions(options, 'decode(data, { maxPixels: 1e8 })');
17
18
  const bytes = view(input);
@@ -9,7 +9,8 @@
9
9
  * | GIF | software, comment (comment extensions) |
10
10
  * | TGA | author, comment, creation time, software (extension area) |
11
11
  *
12
- * Empty fields are left out
12
+ * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
13
+ * image always encodes to the same bytes
13
14
  */
14
15
  export interface Metadata {
15
16
  /** The image's title */
@@ -20,10 +21,10 @@ export interface Metadata {
20
21
  description?: string;
21
22
  /** The image's copyright info */
22
23
  copyright?: string;
23
- /** The image's creation time. Default: now */
24
- creationTime?: string | number | Date;
25
- /** The software used to create the image. Default: `'ImageScript vX.X.X'`, `''` leaves it out */
26
- software?: string;
24
+ /** The image's creation time. Default: none (`null` leaves it out, too) */
25
+ creationTime?: string | number | Date | null;
26
+ /** The software used to create the image. Default: `'ImageScript'` (without a version), `null` leaves it out */
27
+ software?: string | null;
27
28
  /** A disclaimer for the image */
28
29
  disclaimer?: string;
29
30
  /** A warning for the image */
package/dist/metadata.js CHANGED
@@ -1,15 +1,17 @@
1
- import { VERSION } from "./version.js";
2
1
  import { encode as utf8 } from "./util/utf8.js";
3
2
  import * as exif from "./codecs/exif.js";
4
3
  const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', 'disclaimer', 'warning', 'source', 'comment'];
5
4
  export function resolveMetadata(metadata = {}) {
6
5
  const { creationTime, software } = metadata || {};
7
- const time = new Date(creationTime === undefined ? Date.now() : creationTime);
8
- if (isNaN(time.getTime()))
9
- throw new RangeError('Invalid creation time');
10
- const resolved = { creationTime: time };
6
+ const resolved = {};
7
+ if (creationTime !== undefined && creationTime !== null) {
8
+ const time = new Date(creationTime);
9
+ if (isNaN(time.getTime()))
10
+ throw new RangeError('Invalid creation time');
11
+ resolved.creationTime = time;
12
+ }
11
13
  for (const key of TEXT_FIELDS) {
12
- const value = key === 'software' && software === undefined ? `ImageScript v${VERSION}` : metadata?.[key];
14
+ const value = key === 'software' && software === undefined ? 'ImageScript' : metadata?.[key];
13
15
  if (value)
14
16
  resolved[key] = String(value);
15
17
  }
@@ -21,7 +23,7 @@ export function pngText(m) {
21
23
  Author: m.author,
22
24
  Description: m.description,
23
25
  Copyright: m.copyright,
24
- 'Creation Time': m.creationTime.toUTCString(),
26
+ 'Creation Time': m.creationTime?.toUTCString(),
25
27
  Software: m.software,
26
28
  Disclaimer: m.disclaimer,
27
29
  Warning: m.warning,