imagescript 4.0.0-rc.2 → 4.0.0-rc.4

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,26 @@ 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, oneOf, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
- import { MAX_PIXELS, LimitError, decoding } from "./util/limits.js";
29
+ import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapScale, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
30
+ import { MAX_PIXELS, LimitError, decoding, checkGrowth } 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";
35
+ import { rotateBilinear } from "./util/rotate.js";
39
36
  import * as gainMapCodec from "./codecs/gainmap.js";
40
37
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
38
+ const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
39
+ const CIRCLE_FITS = ['contain', 'cover'];
40
+ const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
41
+ export const TONE_MAPPINGS = ['reinhard', 'clamp'];
42
+ export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
41
43
  function featureList(features) {
42
44
  if (typeof features !== 'object' || features === null)
43
45
  throw new TypeError('Features must be an object');
@@ -79,7 +81,7 @@ export class Image {
79
81
  set gainMap(gainMap) {
80
82
  if (gainMap !== null && !(gainMap instanceof GainMap))
81
83
  throw new TypeError('The gain map has to be a GainMap or null');
82
- this.__gain_map__ = gainMap;
84
+ this.__gain_map__ = gainMap?.clone() ?? null;
83
85
  }
84
86
  get bitmap() {
85
87
  return this.__bitmap__;
@@ -109,11 +111,6 @@ export class Image {
109
111
  get height() {
110
112
  return this.__height__;
111
113
  }
112
- *coordinates() {
113
- for (let y = 0; y < this.height; y++)
114
- for (let x = 0; x < this.width; x++)
115
- yield [x, y];
116
- }
117
114
  *pixels() {
118
115
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
119
116
  let offset = 0;
@@ -127,6 +124,7 @@ export class Image {
127
124
  const color = gradientFunction(stops);
128
125
  finite(angle, 'angle');
129
126
  const image = new Image(width, height);
127
+ ({ width, height } = image);
130
128
  const radians = angle * Math.PI / 180;
131
129
  const dx = Math.sin(radians), dy = -Math.cos(radians);
132
130
  const length = Math.abs(width * dx) + Math.abs(height * dy);
@@ -138,13 +136,14 @@ export class Image {
138
136
  }
139
137
  static radialGradient(width, height, options) {
140
138
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
139
+ const image = new Image(width, height);
140
+ ({ width, height } = image);
141
141
  const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options;
142
142
  const color = gradientFunction(stops);
143
143
  finite(cx, 'x');
144
144
  finite(cy, 'y');
145
145
  if (!(finite(radius, 'radius') > 0))
146
146
  throw new RangeError('Invalid radius');
147
- const image = new Image(width, height);
148
147
  const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength);
149
148
  for (let y = 0, i = 0; y < height; y++)
150
149
  for (let x = 0; x < width; x++, i += 4)
@@ -189,10 +188,12 @@ export class Image {
189
188
  if (typeof color !== 'function')
190
189
  color = checkColor(color);
191
190
  if (typeof color === 'function') {
191
+ const pixels = new Uint8ClampedArray(this.bitmap.length), out = new DataView(pixels.buffer);
192
192
  let offset = 0;
193
193
  for (let y = 0; y < this.height; y++)
194
194
  for (let x = 0; x < this.width; x++, offset += 4)
195
- view.setUint32(offset, checkColor(color(x, y)), false);
195
+ out.setUint32(offset, checkColor(color(x, y)), false);
196
+ this.bitmap.set(pixels);
196
197
  }
197
198
  else {
198
199
  view.setUint32(0, color, false);
@@ -213,16 +214,18 @@ export class Image {
213
214
  }
214
215
  scale(factor, options) {
215
216
  checkOptions(options, 'scale(factor, { mode: \'area\' })');
216
- const { mode, fast } = resizeOptions(options);
217
- const image = this.__scale__(factor, mode, fast);
217
+ const { mode } = resizeOptions(options);
218
+ finite(factor, 'scale factor');
219
+ const image = this.__scale__(factor, mode);
218
220
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
219
221
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
220
222
  return this.__apply__(image);
221
223
  }
222
- __scale__(factor, mode = 'bilinear', fast = true) {
224
+ __scale__(factor, mode = 'bilinear') {
223
225
  if (factor === 1)
224
226
  return this;
225
- return this.__resize__(this.width * factor, this.height * factor, mode, fast);
227
+ const size = (side) => factor > 0 ? Math.max(1, side * factor) : side * factor;
228
+ return this.__resize__(size(this.width), size(this.height), mode);
226
229
  }
227
230
  resize(widthOrOptions, heightArgument, optionsArgument) {
228
231
  const [width, height, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument);
@@ -233,8 +236,8 @@ export class Image {
233
236
  ? this.__contain__(width, height, options)
234
237
  : this.__cover__(width, height, options);
235
238
  }
236
- const { mode, fast } = resizeOptions(options);
237
- const image = this.__resize__(...this.__resized_size__(width, height, fit), mode, fast);
239
+ const { mode } = resizeOptions(options);
240
+ const image = this.__resize__(...this.__resized_size__(width, height, fit), mode);
238
241
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
239
242
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
240
243
  return this.__apply__(image);
@@ -272,9 +275,10 @@ export class Image {
272
275
  if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) {
273
276
  const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height };
274
277
  const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
278
+ const resized = this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region);
275
279
  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
280
  this.__moved__?.(fx, fy, region.x, region.y);
277
- return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, resizeOpts.fast, region));
281
+ return this.__apply__(resized);
278
282
  }
279
283
  this.resize(resizedWidth, resizedHeight, resizeOpts);
280
284
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
@@ -288,7 +292,7 @@ export class Image {
288
292
  return [width, Math.max(1, Math.round(this.height / this.width * Math.floor(width)))];
289
293
  return [width, height];
290
294
  }
291
- __resize__(width, height, mode = 'bilinear', fast = true, region) {
295
+ __resize__(width, height, mode = 'bilinear', region) {
292
296
  width = Math.floor(width);
293
297
  height = Math.floor(height);
294
298
  if (width < 1)
@@ -300,7 +304,7 @@ export class Image {
300
304
  return this.__resize_nearest_neighbor__(width, height);
301
305
  const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX;
302
306
  const image = new Image(region?.width ?? width, region?.height ?? height);
303
- resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
307
+ resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, true, region);
304
308
  return image;
305
309
  }
306
310
  __resize_nearest_neighbor__(width, height) {
@@ -356,6 +360,7 @@ export class Image {
356
360
  return this.__apply__(this.__crop__(...bounds));
357
361
  }
358
362
  __trim_bounds__(color, { tolerance = 0 }) {
363
+ finite(tolerance, 'tolerance');
359
364
  if (!(tolerance >= 0 && tolerance <= 1))
360
365
  throw new RangeError('Invalid tolerance, it has to be between 0 and 1');
361
366
  const bitmap = this.bitmap;
@@ -409,12 +414,11 @@ export class Image {
409
414
  return image;
410
415
  }
411
416
  cropCircle(options = {}) {
412
- checkOptions(options, 'cropCircle({ size: \'cover\' })');
413
- const { size = 'contain', feathering = 0 } = options;
414
- finite(feathering, 'feathering');
415
- if (size !== 'contain' && size !== 'cover')
416
- throw new TypeError(`Invalid circle size: ${String(size)}`);
417
- const radius = (size === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
417
+ checkOptions(options, 'cropCircle({ fit: \'cover\' })');
418
+ const { fit = 'contain', feathering = 0 } = options;
419
+ unitInterval(feathering, 'feathering');
420
+ oneOf(fit, CIRCLE_FITS, 'fit');
421
+ const radius = (fit === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
418
422
  const cx = this.width / 2, cy = this.height / 2;
419
423
  const band = Math.min(1, Math.max(0, feathering)) * radius;
420
424
  for (let y = 0; y < this.height; y++) {
@@ -458,11 +462,11 @@ export class Image {
458
462
  }
459
463
  return this;
460
464
  }
461
- opacity(opacity) {
462
- opacity = finite(opacity, 'opacity value');
463
- if (opacity < 0)
465
+ opacity(factor) {
466
+ factor = finite(factor, 'opacity value');
467
+ if (factor < 0)
464
468
  throw new RangeError('Invalid opacity value');
465
- this.__set_channel_value__(opacity, 3);
469
+ this.__set_channel_value__(factor, 3);
466
470
  return this;
467
471
  }
468
472
  red(factor) {
@@ -514,12 +518,11 @@ export class Image {
514
518
  }
515
519
  composite(source, options = {}) {
516
520
  checkOptions(options, 'composite(source, { x: 10, y: 20 })');
517
- const { opacity = 1, mode = 'normal' } = options;
518
- let x = options.x ?? 0, y = options.y ?? 0;
519
- x = Math.trunc(finite(x, 'x'));
520
- y = Math.trunc(finite(y, 'y'));
521
- if (isNaN(opacity) || opacity < 0 || opacity > 1)
522
- throw new RangeError('Invalid composite opacity');
521
+ if (!(source instanceof Image))
522
+ throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { x: 10, y: 20 })');
523
+ const { opacity = 1, mode = 'normal', x: givenX = 0, y: givenY = 0 } = options;
524
+ const x = Math.trunc(finite(givenX, 'x')), y = Math.trunc(finite(givenY, 'y'));
525
+ unitInterval(opacity, 'opacity');
523
526
  const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
524
527
  if (opacity === 0)
525
528
  return this;
@@ -731,8 +734,7 @@ export class Image {
731
734
  return this;
732
735
  }
733
736
  blur(radius) {
734
- if (!Number.isFinite(radius) || radius < 0)
735
- throw new RangeError('Invalid blur radius');
737
+ nonNegative(radius, 'blur radius');
736
738
  const map = this.__gain_map__;
737
739
  if (map && radius * map.width / this.width >= 0.5)
738
740
  map.image = map.image.clone().blur(radius * map.width / this.width);
@@ -745,8 +747,6 @@ export class Image {
745
747
  }
746
748
  quantize(options = {}) {
747
749
  checkOptions(options, 'image.quantize({ colors: 16 })');
748
- if (typeof options !== 'object' || options === null)
749
- throw new TypeError('quantize takes an options object');
750
750
  const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options;
751
751
  if (colors !== undefined && palette !== undefined)
752
752
  throw new TypeError('quantize takes colors or palette, not both');
@@ -812,11 +812,8 @@ export class Image {
812
812
  if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
813
813
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
814
814
  const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
815
- if (typeof options !== 'object' || options === null)
816
- throw new TypeError('transform takes an options object');
817
815
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
818
- if (!TRANSFORM_MODES.includes(mode))
819
- throw new TypeError(`transform mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
816
+ oneOf(mode, TRANSFORM_MODES, 'transform mode');
820
817
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
821
818
  finite(pivotX, 'origin x');
822
819
  finite(pivotY, 'origin y');
@@ -918,6 +915,7 @@ export class Image {
918
915
  : { left: 0, top: 0, right: 0, bottom: 0 });
919
916
  }
920
917
  __shape_layer__(margin) {
918
+ checkGrowth(this.width + 2 * margin, this.height + 2 * margin, 'The shadow or outline');
921
919
  const layer = new Image(this.width + 2 * margin, this.height + 2 * margin);
922
920
  for (let y = 0; y < this.height; y++)
923
921
  for (let x = 0; x < this.width; x++)
@@ -927,6 +925,7 @@ export class Image {
927
925
  __under__(layer, layerX, layerY, grow) {
928
926
  const { left, top, right, bottom } = grow;
929
927
  const width = this.width + left + right, height = this.height + top + bottom;
928
+ checkGrowth(width, height, 'The shadow or outline');
930
929
  const result = new Image(width, height);
931
930
  result.composite(layer, { x: layerX + left, y: layerY + top });
932
931
  const map = this.__gain_map__;
@@ -943,11 +942,8 @@ export class Image {
943
942
  }
944
943
  sharpen(options = {}) {
945
944
  checkOptions(options, 'sharpen({ amount: 0.5 })');
946
- const { amount = 1, radius = 1 } = options;
947
- if (!Number.isFinite(amount) || amount < 0)
948
- throw new RangeError('Invalid sharpen amount');
949
- if (!Number.isFinite(radius) || radius <= 0)
950
- throw new RangeError('Invalid sharpen radius');
945
+ const { amount: givenAmount = 1, radius: givenRadius = 1 } = options;
946
+ const amount = nonNegative(givenAmount, 'sharpen amount'), radius = positive(givenRadius, 'sharpen radius');
951
947
  const blurred = premultiply(this.bitmap);
952
948
  gaussianBlur(blurred, this.width, this.height, radius);
953
949
  const bitmap = this.bitmap;
@@ -1010,6 +1006,8 @@ export class Image {
1010
1006
  checkOptions(options, 'colorToAlpha({ color: 0xffffffff })');
1011
1007
  const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options;
1012
1008
  let color = colorOption;
1009
+ finite(transparencyThreshold, 'transparencyThreshold');
1010
+ finite(opacityThreshold, 'opacityThreshold');
1013
1011
  if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
1014
1012
  throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
1015
1013
  const bitmap = this.bitmap;
@@ -1060,8 +1058,8 @@ export class Image {
1060
1058
  }
1061
1059
  dominantColor(options = {}) {
1062
1060
  checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1063
- const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = options;
1064
- const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4;
1061
+ const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options;
1062
+ const threshold = Math.min(256, Math.max(0, finite(bwThreshold, 'threshold')));
1065
1063
  const pixels = this.__bytes__();
1066
1064
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1067
1065
  || quantize.dominantColor(pixels, () => true);
@@ -1070,8 +1068,7 @@ export class Image {
1070
1068
  rotate(angle, options = {}) {
1071
1069
  checkOptions(options, 'rotate(angle, { expand: false })');
1072
1070
  const { expand = true, mode = 'bilinear' } = options;
1073
- if (!TRANSFORM_MODES.includes(mode))
1074
- throw new TypeError(`rotate mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`);
1071
+ oneOf(mode, TRANSFORM_MODES, 'rotate mode');
1075
1072
  angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1076
1073
  if (angle === 0)
1077
1074
  return this;
@@ -1097,6 +1094,16 @@ export class Image {
1097
1094
  else
1098
1095
  dst[x * height + height - 1 - y] = i;
1099
1096
  }
1097
+ if (!expand && out.width !== width) {
1098
+ const canvas = new Image(width, height), target = canvas.__u32__, turned = out.__u32__;
1099
+ const left = Math.floor((width - out.width) / 2), top = Math.floor((height - out.height) / 2);
1100
+ for (let y = Math.max(0, top); y < Math.min(height, top + out.height); y++)
1101
+ for (let x = Math.max(0, left); x < Math.min(width, left + out.width); x++)
1102
+ target[y * width + x] = turned[(y - top) * out.width + x - left];
1103
+ rotateGainMap(width, height);
1104
+ this.__moved__?.(1, 1, 0, 0);
1105
+ return this.__apply__(canvas);
1106
+ }
1100
1107
  rotateGainMap(out.width, out.height);
1101
1108
  this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2);
1102
1109
  return this.__apply__(out);
@@ -1107,6 +1114,10 @@ export class Image {
1107
1114
  const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
1108
1115
  const out = new Image(outWidth, outHeight);
1109
1116
  rotateGainMap(outWidth, outHeight);
1117
+ if (mode === 'bilinear' && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos)) {
1118
+ this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2);
1119
+ return this.__apply__(out);
1120
+ }
1110
1121
  const inverse = [cos, sin, -sin, cos,
1111
1122
  width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2];
1112
1123
  sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode);
@@ -1114,7 +1125,7 @@ export class Image {
1114
1125
  return this.__apply__(out);
1115
1126
  }
1116
1127
  flip(direction) {
1117
- oneOf(direction, ['horizontal', 'vertical'], 'flip direction');
1128
+ oneOf(direction, FLIP_DIRECTIONS, 'flip direction');
1118
1129
  const u32 = this.__u32__;
1119
1130
  const { width, height } = this;
1120
1131
  if (direction === 'horizontal') {
@@ -1172,9 +1183,9 @@ export class Image {
1172
1183
  }
1173
1184
  roundCorners(options = {}) {
1174
1185
  checkOptions(options, 'roundCorners({ radius: 10 })');
1175
- let radius = options.radius ?? Math.min(this.width, this.height) / 4;
1176
- radius = finite(radius, 'radius');
1177
- radius = Math.max(0, Math.min(radius, this.width / 2, this.height / 2));
1186
+ const { radius: givenRadius = Math.min(this.width, this.height) / 4 } = options;
1187
+ let radius = nonNegative(givenRadius, 'radius');
1188
+ radius = Math.min(radius, this.width / 2, this.height / 2);
1178
1189
  const size = Math.ceil(radius);
1179
1190
  for (let y = 0; y < size; y++) {
1180
1191
  for (let x = 0; x < size; x++) {
@@ -1190,7 +1201,7 @@ export class Image {
1190
1201
  }
1191
1202
  fisheye(options = {}) {
1192
1203
  checkOptions(options, 'fisheye({ strength: 3 })');
1193
- const strength = finite(options.strength ?? 2, 'strength');
1204
+ const strength = positive(options.strength === undefined ? 2 : options.strength, 'strength');
1194
1205
  const r = new Image(this.width, this.height);
1195
1206
  const w = this.width;
1196
1207
  const h = this.height;
@@ -1229,28 +1240,27 @@ export class Image {
1229
1240
  }
1230
1241
  async encodeJPEG(options = {}) {
1231
1242
  checkOptions(options, 'encodeJPEG({ quality: 80 })');
1232
- const { quality = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1233
- if (subsampling !== undefined && subsampling !== '4:4:4' && subsampling !== '4:2:0')
1234
- throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1243
+ const { quality: qualityOption = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1244
+ const quality = checkQuality(qualityOption);
1245
+ if (subsampling !== undefined)
1246
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1235
1247
  const backgroundColor = checkColor(background, 'background');
1236
1248
  const m = resolveMetadata(metadata);
1237
1249
  const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1238
1250
  const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1239
1251
  const gainMap = source.__gain_map__;
1240
1252
  if (!gainMap || gainMapOption === false)
1241
- return jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), base);
1253
+ return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1242
1254
  const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1243
1255
  let width, height;
1244
1256
  if (scale !== undefined) {
1245
- const s = finite(scale, 'gain map scale');
1246
- if (!(s > 0 && s <= 1))
1247
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1257
+ const s = gainMapScale(scale);
1248
1258
  width = Math.max(1, Math.round(this.width * s));
1249
1259
  height = Math.max(1, Math.round(this.height * s));
1250
1260
  }
1251
1261
  const params = gainMap.__params__();
1252
1262
  const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1253
- const primary = jpeg.encode(source.__bytes__(), source.width, source.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1263
+ const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) });
1254
1264
  return gainMapCodec.finish(primary, map);
1255
1265
  }
1256
1266
  __flattened__(background, withGainMap) {
@@ -1303,8 +1313,7 @@ export class Image {
1303
1313
  const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options;
1304
1314
  checkEffort(effort, 2);
1305
1315
  checkThreads(threads);
1306
- if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
1307
- throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1316
+ oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1308
1317
  const exif = exifData(resolveMetadata(metadata));
1309
1318
  return avifEnc.encode(this.__bytes__(), this.width, this.height, {
1310
1319
  quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads, gainMap: this.__gain_map_pixels__(gainMap)
@@ -1318,9 +1327,7 @@ export class Image {
1318
1327
  const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1319
1328
  let map = gainMap.image;
1320
1329
  if (scale !== undefined) {
1321
- const s = finite(scale, 'gain map scale');
1322
- if (!(s > 0 && s <= 1))
1323
- throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1330
+ const s = gainMapScale(scale);
1324
1331
  const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1325
1332
  if (width !== map.width || height !== map.height)
1326
1333
  map = map.clone().resize(width, height);
@@ -1344,10 +1351,8 @@ export class Image {
1344
1351
  checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
1345
1352
  const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1346
1353
  checkThreads(threads);
1347
- if (!(Number(maxPixels) > 0))
1348
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1349
- if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
1350
- throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
1354
+ pixelLimit(maxPixels);
1355
+ oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
1351
1356
  const data = view(input);
1352
1357
  const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1353
1358
  const decoded = await decoding(() => {
@@ -1398,6 +1403,8 @@ export class Image {
1398
1403
  const { icc, cicp, colorSpace } = decoded;
1399
1404
  (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
1400
1405
  }
1406
+ if (!(decoded.width >= 1 && decoded.height >= 1) || decoded.pixels.length !== decoded.width * decoded.height * 4)
1407
+ throw new Error('Image: damaged or truncated image data');
1401
1408
  const image = new Image(decoded.width, decoded.height);
1402
1409
  image.bitmap = alignedPixels(decoded.pixels);
1403
1410
  if (gainMap && ImageType.isJPEG(dataView)) {
@@ -1405,7 +1412,7 @@ export class Image {
1405
1412
  const found = gainMapCodec.find(data);
1406
1413
  const size = found && gainMapCodec.dimensions(found.map);
1407
1414
  if (found && size && size.width * size.height <= maxPixels)
1408
- image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple);
1415
+ image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple, maxPixels);
1409
1416
  }
1410
1417
  catch {
1411
1418
  image.__gain_map__ = null;
@@ -1479,14 +1486,11 @@ export class Image {
1479
1486
  }
1480
1487
  static async renderSVG(svg, options = {}) {
1481
1488
  checkOptions(options, 'renderSVG(svg, { width: 512 })');
1482
- const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, fonts = [], images: givenImages = {} } = options;
1483
- if (!(Number(maxPixels) > 0))
1484
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1485
- const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
1486
- if (!(Number(maxLayerPixels) > 0))
1487
- throw new RangeError(`maxLayerPixels must be a positive number, not ${maxLayerPixels}`);
1488
- if (!(Number(maxImagePixels) > 0))
1489
- throw new RangeError(`maxImagePixels must be a positive number, not ${maxImagePixels}`);
1489
+ const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
1490
+ pixelLimit(maxPixels);
1491
+ const { maxLayerPixels = 4 * maxPixels, maxImagePixels = maxPixels } = options;
1492
+ pixelLimit(maxLayerPixels, 'maxLayerPixels');
1493
+ pixelLimit(maxImagePixels, 'maxImagePixels');
1490
1494
  const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1491
1495
  if (sizes > 1)
1492
1496
  throw new TypeError('renderSVG() takes one of width, height and scale');
@@ -1508,7 +1512,7 @@ export class Image {
1508
1512
  const source = typeof svg === 'string' ? svg : view(svg);
1509
1513
  const images = new Map();
1510
1514
  const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
1511
- let imagePixels = Number(maxImagePixels);
1515
+ let imagePixels = maxImagePixels;
1512
1516
  for (const { href, data } of svgRenderer.imageReferences(source)) {
1513
1517
  const value = given.get(href) ?? data;
1514
1518
  if (!value)
@@ -1539,7 +1543,7 @@ export class Image {
1539
1543
  images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1540
1544
  }
1541
1545
  }
1542
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), Number(maxPixels), Number(maxLayerPixels));
1546
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels, maxLayerPixels);
1543
1547
  const image = new Image(width, height);
1544
1548
  image.bitmap.set(pixels);
1545
1549
  return image;
@@ -1550,14 +1554,11 @@ export class Image {
1550
1554
  if (options.font === undefined)
1551
1555
  throw new TypeError('renderText(text, options) needs the font in the options');
1552
1556
  const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1553
- if (!(Number(maxPixels) > 0))
1554
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
1555
- const { maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks } = options;
1556
- const layout = new TextLayout({ maxWidth, maxHeight, wrapStyle, horizontalAlign, verticalAlign, wrapHardBreaks });
1557
+ pixelLimit(maxPixels);
1558
+ const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
1559
+ const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1557
1560
  const axes = textRenderer.axisValues(variations);
1558
- const size = finite(options.size, 'font size');
1559
- if (size < 0)
1560
- throw new RangeError(`Invalid font size: ${size}`);
1561
+ const size = positive(options.size, 'font size');
1561
1562
  if (finite(strokeWidth, 'stroke width') < 0)
1562
1563
  throw new RangeError('Invalid stroke width');
1563
1564
  const fonts = Array.isArray(font) ? font : [font];
@@ -1565,7 +1566,15 @@ export class Image {
1565
1566
  throw new RangeError('No font given');
1566
1567
  const [r, g, b, a] = Colors.toRGBA(color);
1567
1568
  const pad = Math.ceil(strokeWidth);
1568
- 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);
1569
+ if (layout.width !== undefined && layout.width <= 2 * pad)
1570
+ throw new RangeError(`The width (${layout.width}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1571
+ if (layout.height !== undefined && layout.height <= 2 * pad)
1572
+ throw new RangeError(`The height (${layout.height}) leaves no room for the text inside the ${strokeWidth} pixel outline`);
1573
+ if (layout.width !== undefined)
1574
+ layout.width -= 2 * pad;
1575
+ if (layout.height !== undefined)
1576
+ layout.height -= 2 * pad;
1577
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, maxPixels, pad);
1569
1578
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1570
1579
  const coverage = new Uint8Array(width * height);
1571
1580
  for (let y = 0; y < rendered.height; y++)
@@ -1650,8 +1659,7 @@ export function resizeArguments(widthOrOptions, height, options) {
1650
1659
  const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions;
1651
1660
  if (width === undefined && optionsHeight === undefined)
1652
1661
  throw new TypeError('resize() needs a width, a height or both');
1653
- if (!['fill', 'inside', 'contain', 'cover'].includes(fit))
1654
- throw new TypeError(`fit must be 'fill', 'inside', 'contain' or 'cover', not ${String(fit)}`);
1662
+ oneOf(fit, RESIZE_FITS, 'fit');
1655
1663
  return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit];
1656
1664
  }
1657
1665
  export function insideSize(width, height, boxWidth, boxHeight) {
@@ -1662,7 +1670,7 @@ export function insideSize(width, height, boxWidth, boxHeight) {
1662
1670
  }
1663
1671
  const RESIZE_MODES = ['nearest-neighbor', 'bilinear', 'bicubic', 'area'];
1664
1672
  function resizeOptions(options) {
1665
- return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode'), fast: options?.fast ?? true };
1673
+ return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode') };
1666
1674
  }
1667
1675
  const hardLight = (b, s) => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1));
1668
1676
  const BLEND_MODES = {
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ import { Image, DecodeOptions } from './image.js';
7
7
  import { Animation } from './animation.js';
8
8
  export { Image } from './image.js';
9
9
  export { Colors } from './colors.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, 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';
11
11
  export { Frame } from './frame.js';
12
12
  export type { FrameDisposalMode, FrameOptions } from './frame.js';
13
13
  export { GainMap } from './gainmap.js';
@@ -17,6 +17,7 @@ export type { AnimationOptions, AnimationCanvasOptions, AnimationEncodeOptions,
17
17
  export { AnimationEncoder } from './animation-encoder.js';
18
18
  export type { TextLayoutOptions, WrapStyle, HorizontalAlign, VerticalAlign } from './text-layout.js';
19
19
  export { ImageType } from './image-type.js';
20
+ export { LimitError } from './util/limits.js';
20
21
  export type { ImageTypeName } from './image-type.js';
21
22
  export type { ToneMapping } from './codecs/hdr.js';
22
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,7 @@
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. Without metadata, the files only say which software made them (`software`), so the same
12
+ * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
13
13
  * image always encodes to the same bytes
14
14
  */
15
15
  export interface Metadata {
@@ -21,10 +21,16 @@ export interface Metadata {
21
21
  description?: string;
22
22
  /** The image's copyright info */
23
23
  copyright?: string;
24
- /** The image's creation time. Default: none (left out) */
25
- creationTime?: string | number | Date;
26
- /** The software used to create the image. Default: `'ImageScript'` (without a version), `''` leaves it out */
27
- software?: string;
24
+ /**
25
+ * The image's creation time
26
+ * @defaultValue None (`null` leaves it out, too)
27
+ */
28
+ creationTime?: string | number | Date | null;
29
+ /**
30
+ * The software used to create the image
31
+ * @defaultValue `'ImageScript'` (without a version), `null` leaves it out
32
+ */
33
+ software?: string | null;
28
34
  /** A disclaimer for the image */
29
35
  disclaimer?: string;
30
36
  /** A warning for the image */
package/dist/metadata.js CHANGED
@@ -4,7 +4,7 @@ const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software',
4
4
  export function resolveMetadata(metadata = {}) {
5
5
  const { creationTime, software } = metadata || {};
6
6
  const resolved = {};
7
- if (creationTime !== undefined) {
7
+ if (creationTime !== undefined && creationTime !== null) {
8
8
  const time = new Date(creationTime);
9
9
  if (isNaN(time.getTime()))
10
10
  throw new RangeError('Invalid creation time');
package/dist/package.json CHANGED
@@ -1 +1 @@
1
- {"type":"module"}
1
+ {"type":"module","sideEffects":false}