imagescript 4.0.0-rc.3 → 4.0.0-rc.5

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
@@ -26,15 +26,18 @@ import { encode as utf8 } from "./util/utf8.js";
26
26
  import { resample, BOX, TRIANGLE, CUBIC } from "./util/resample.js";
27
27
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
28
28
  import { Colors, wrapHue, hue2rgb } from "./colors.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";
29
+ import { isOptions, checkOptions, finite, nonNegative, positive, unitInterval, oneOf, pixelLimit, checkThreads, gainMapEmbed, boolean, 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";
31
31
  import { GainMap } from "./gainmap.js";
32
32
  import * as gain from "./util/gain.js";
33
33
  import { multiply, invert } from "./util/matrix.js";
34
34
  import { sampleAffine } from "./util/affine.js";
35
+ import { rotateBilinear } from "./util/rotate.js";
35
36
  import * as gainMapCodec from "./codecs/gainmap.js";
37
+ import { describe } from "./util/inspect.js";
36
38
  const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
37
39
  const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
40
+ const CIRCLE_FITS = ['contain', 'cover'];
38
41
  const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
39
42
  export const TONE_MAPPINGS = ['reinhard', 'clamp'];
40
43
  export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
@@ -46,6 +49,8 @@ function featureList(features) {
46
49
  throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`);
47
50
  if (typeof value === 'boolean')
48
51
  return [tag, value ? 1 : 0];
52
+ if (typeof value !== 'number')
53
+ throw new TypeError(`The value of the OpenType feature ${tag} must be a boolean or a number, not ${value === null ? 'null' : typeof value}`);
49
54
  if (!Number.isInteger(value) || value < 0 || value > 255)
50
55
  throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`);
51
56
  return [tag, value];
@@ -79,7 +84,7 @@ export class Image {
79
84
  set gainMap(gainMap) {
80
85
  if (gainMap !== null && !(gainMap instanceof GainMap))
81
86
  throw new TypeError('The gain map has to be a GainMap or null');
82
- this.__gain_map__ = gainMap;
87
+ this.__gain_map__ = gainMap?.clone() ?? null;
83
88
  }
84
89
  get bitmap() {
85
90
  return this.__bitmap__;
@@ -111,13 +116,16 @@ export class Image {
111
116
  }
112
117
  *pixels() {
113
118
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
119
+ const width = this.width, height = this.height;
114
120
  let offset = 0;
115
- for (let y = 0; y < this.height; y++)
116
- for (let x = 0; x < this.width; x++, offset += 4)
121
+ for (let y = 0; y < height; y++)
122
+ for (let x = 0; x < width; x++, offset += 4)
117
123
  yield [x, y, view.getUint32(offset, false)];
118
124
  }
119
125
  static linearGradient(width, height, options) {
120
126
  checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })');
127
+ if (options === undefined || options.stops === undefined)
128
+ throw new TypeError('Image.linearGradient(width, height, { stops }) needs the stops in the options');
121
129
  const { stops, angle = 180 } = options;
122
130
  const color = gradientFunction(stops);
123
131
  finite(angle, 'angle');
@@ -136,6 +144,8 @@ export class Image {
136
144
  checkOptions(options, 'Image.radialGradient(100, 50, { stops })');
137
145
  const image = new Image(width, height);
138
146
  ({ width, height } = image);
147
+ if (options === undefined || options.stops === undefined)
148
+ throw new TypeError('Image.radialGradient(width, height, { stops }) needs the stops in the options');
139
149
  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
150
  const color = gradientFunction(stops);
141
151
  finite(cx, 'x');
@@ -186,10 +196,12 @@ export class Image {
186
196
  if (typeof color !== 'function')
187
197
  color = checkColor(color);
188
198
  if (typeof color === 'function') {
199
+ const pixels = new Uint8ClampedArray(this.bitmap.length), out = new DataView(pixels.buffer);
189
200
  let offset = 0;
190
201
  for (let y = 0; y < this.height; y++)
191
202
  for (let x = 0; x < this.width; x++, offset += 4)
192
- view.setUint32(offset, checkColor(color(x, y)), false);
203
+ out.setUint32(offset, checkColor(color(x, y)), false);
204
+ this.bitmap.set(pixels);
193
205
  }
194
206
  else {
195
207
  view.setUint32(0, color, false);
@@ -211,6 +223,7 @@ export class Image {
211
223
  scale(factor, options) {
212
224
  checkOptions(options, 'scale(factor, { mode: \'area\' })');
213
225
  const { mode } = resizeOptions(options);
226
+ finite(factor, 'scale factor');
214
227
  const image = this.__scale__(factor, mode);
215
228
  this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
216
229
  this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0);
@@ -270,9 +283,10 @@ export class Image {
270
283
  if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) {
271
284
  const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height };
272
285
  const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
286
+ const resized = this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region);
273
287
  this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
274
288
  this.__moved__?.(fx, fy, region.x, region.y);
275
- return this.__apply__(this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region));
289
+ return this.__apply__(resized);
276
290
  }
277
291
  this.resize(resizedWidth, resizedHeight, resizeOpts);
278
292
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
@@ -354,6 +368,7 @@ export class Image {
354
368
  return this.__apply__(this.__crop__(...bounds));
355
369
  }
356
370
  __trim_bounds__(color, { tolerance = 0 }) {
371
+ finite(tolerance, 'tolerance');
357
372
  if (!(tolerance >= 0 && tolerance <= 1))
358
373
  throw new RangeError('Invalid tolerance, it has to be between 0 and 1');
359
374
  const bitmap = this.bitmap;
@@ -407,12 +422,11 @@ export class Image {
407
422
  return image;
408
423
  }
409
424
  cropCircle(options = {}) {
410
- checkOptions(options, 'cropCircle({ size: \'cover\' })');
411
- const { size = 'contain', feathering = 0 } = options;
412
- finite(feathering, 'feathering');
413
- if (size !== 'contain' && size !== 'cover')
414
- throw new TypeError(`Invalid circle size: ${String(size)}`);
415
- const radius = (size === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
425
+ checkOptions(options, 'cropCircle({ fit: \'cover\' })');
426
+ const { fit = 'contain', feathering = 0 } = options;
427
+ unitInterval(feathering, 'feathering');
428
+ oneOf(fit, CIRCLE_FITS, 'fit');
429
+ const radius = (fit === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2;
416
430
  const cx = this.width / 2, cy = this.height / 2;
417
431
  const band = Math.min(1, Math.max(0, feathering)) * radius;
418
432
  for (let y = 0; y < this.height; y++) {
@@ -514,12 +528,9 @@ export class Image {
514
528
  checkOptions(options, 'composite(source, { x: 10, y: 20 })');
515
529
  if (!(source instanceof Image))
516
530
  throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { 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');
531
+ const { opacity = 1, mode = 'normal', x: givenX = 0, y: givenY = 0 } = options;
532
+ const x = Math.trunc(finite(givenX, 'x')), y = Math.trunc(finite(givenY, 'y'));
533
+ unitInterval(opacity, 'opacity');
523
534
  const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES), 'blend mode')];
524
535
  if (opacity === 0)
525
536
  return this;
@@ -529,7 +540,8 @@ export class Image {
529
540
  return this.__blend__(source, x, y, opacity, blend);
530
541
  const left = Math.max(0, x), top = Math.max(0, y);
531
542
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
532
- const dst = this.bitmap, src = source.bitmap;
543
+ const dst = this.bitmap;
544
+ const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap;
533
545
  for (let row = top; row < bottom; row++) {
534
546
  for (let column = left, s = 4 * ((row - y) * source.width + left - x), d = 4 * (row * this.width + left); column < right; column++, s += 4, d += 4) {
535
547
  const sa = src[s + 3];
@@ -619,7 +631,8 @@ export class Image {
619
631
  __blend__(source, x, y, opacity, blend) {
620
632
  const left = Math.max(0, x), top = Math.max(0, y);
621
633
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
622
- const dst = this.bitmap, src = source.bitmap;
634
+ const dst = this.bitmap;
635
+ const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap;
623
636
  for (let row = top; row < bottom; row++) {
624
637
  for (let column = left; column < right; column++) {
625
638
  const s = 4 * ((row - y) * source.width + column - x);
@@ -731,8 +744,7 @@ export class Image {
731
744
  return this;
732
745
  }
733
746
  blur(radius) {
734
- if (!Number.isFinite(radius) || radius < 0)
735
- throw new RangeError('Invalid blur radius');
747
+ nonNegative(radius, 'blur radius');
736
748
  const map = this.__gain_map__;
737
749
  if (map && radius * map.width / this.width >= 0.5)
738
750
  map.image = map.image.clone().blur(radius * map.width / this.width);
@@ -780,10 +792,12 @@ export class Image {
780
792
  return this;
781
793
  }
782
794
  colorMatrix(matrix) {
783
- if (matrix === null || typeof matrix !== 'object' || (matrix.length !== 9 && matrix.length !== 20))
795
+ if (matrix === null || typeof matrix !== 'object')
796
+ throw new TypeError(`colorMatrix() takes an array of 9 or 20 values, not ${matrix === null ? 'null' : typeof matrix}`);
797
+ if (matrix.length !== 9 && matrix.length !== 20)
784
798
  throw new RangeError('A color matrix has 9 or 20 values');
785
799
  const m = new Float64Array(20);
786
- const value = (v) => finite(typeof v === 'number' ? v : NaN, 'color matrix value');
800
+ const value = (v) => finite(v, 'color matrix value');
787
801
  if (matrix.length === 20)
788
802
  for (let i = 0; i < 20; i++)
789
803
  m[i] = value(matrix[i]);
@@ -807,11 +821,16 @@ export class Image {
807
821
  }
808
822
  transform(matrix, options = {}) {
809
823
  checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })');
810
- if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6)
824
+ if (matrix === null || typeof matrix !== 'object')
825
+ throw new TypeError(`transform() takes an array of 6 values, like transform([1, 0, 0, 1, 0, 0]), not ${matrix === null ? 'null' : typeof matrix}`);
826
+ if (matrix.length !== 6)
811
827
  throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]');
812
- const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value'));
828
+ const values = Array.from({ length: 6 }, (_, i) => finite(matrix[i], 'transform value'));
813
829
  const { origin = {}, expand = true, mode = 'bilinear' } = options;
830
+ if (typeof origin !== 'object' || origin === null)
831
+ throw new TypeError(`transform() takes an origin object like { x: 10, y: 20 }, not ${origin === null ? 'null' : typeof origin}`);
814
832
  oneOf(mode, TRANSFORM_MODES, 'transform mode');
833
+ boolean(expand, 'expand');
815
834
  const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin;
816
835
  finite(pivotX, 'origin x');
817
836
  finite(pivotY, 'origin y');
@@ -848,6 +867,7 @@ export class Image {
848
867
  dropShadow(options = {}) {
849
868
  checkOptions(options, 'image.dropShadow({ blur: 8 })');
850
869
  const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options;
870
+ boolean(expand, 'expand');
851
871
  finite(x, 'x');
852
872
  finite(y, 'y');
853
873
  if (finite(blur, 'blur') < 0)
@@ -889,6 +909,7 @@ export class Image {
889
909
  outline(options = {}) {
890
910
  checkOptions(options, 'image.outline({ width: 4 })');
891
911
  const { width = 1, color = 0x000000ff, expand = true } = options;
912
+ boolean(expand, 'expand');
892
913
  if (finite(width, 'outline width') < 0)
893
914
  throw new RangeError('Invalid outline width');
894
915
  const [r, g, b, a] = Colors.toRGBA(checkColor(color));
@@ -913,6 +934,7 @@ export class Image {
913
934
  : { left: 0, top: 0, right: 0, bottom: 0 });
914
935
  }
915
936
  __shape_layer__(margin) {
937
+ checkGrowth(this.width + 2 * margin, this.height + 2 * margin, 'The shadow or outline');
916
938
  const layer = new Image(this.width + 2 * margin, this.height + 2 * margin);
917
939
  for (let y = 0; y < this.height; y++)
918
940
  for (let x = 0; x < this.width; x++)
@@ -922,6 +944,7 @@ export class Image {
922
944
  __under__(layer, layerX, layerY, grow) {
923
945
  const { left, top, right, bottom } = grow;
924
946
  const width = this.width + left + right, height = this.height + top + bottom;
947
+ checkGrowth(width, height, 'The shadow or outline');
925
948
  const result = new Image(width, height);
926
949
  result.composite(layer, { x: layerX + left, y: layerY + top });
927
950
  const map = this.__gain_map__;
@@ -938,11 +961,8 @@ export class Image {
938
961
  }
939
962
  sharpen(options = {}) {
940
963
  checkOptions(options, 'sharpen({ amount: 0.5 })');
941
- const { amount = 1, radius = 1 } = options;
942
- if (!Number.isFinite(amount) || amount < 0)
943
- throw new RangeError('Invalid sharpen amount');
944
- if (!Number.isFinite(radius) || radius <= 0)
945
- throw new RangeError('Invalid sharpen radius');
964
+ const { amount: givenAmount = 1, radius: givenRadius = 1 } = options;
965
+ const amount = nonNegative(givenAmount, 'sharpen amount'), radius = positive(givenRadius, 'sharpen radius');
946
966
  const blurred = premultiply(this.bitmap);
947
967
  gaussianBlur(blurred, this.width, this.height, radius);
948
968
  const bitmap = this.bitmap;
@@ -1005,6 +1025,8 @@ export class Image {
1005
1025
  checkOptions(options, 'colorToAlpha({ color: 0xffffffff })');
1006
1026
  const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options;
1007
1027
  let color = colorOption;
1028
+ finite(transparencyThreshold, 'transparencyThreshold');
1029
+ finite(opacityThreshold, 'opacityThreshold');
1008
1030
  if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold))
1009
1031
  throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1');
1010
1032
  const bitmap = this.bitmap;
@@ -1056,7 +1078,11 @@ export class Image {
1056
1078
  dominantColor(options = {}) {
1057
1079
  checkOptions(options, 'dominantColor({ ignoreBlack: false })');
1058
1080
  const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options;
1059
- const threshold = Math.min(256, Math.max(0, finite(bwThreshold, 'threshold')));
1081
+ boolean(ignoreBlack, 'ignoreBlack');
1082
+ boolean(ignoreWhite, 'ignoreWhite');
1083
+ const threshold = finite(bwThreshold, 'threshold');
1084
+ if (threshold < 0 || threshold > 256)
1085
+ throw new RangeError(`threshold has to be between 0 and 256, not ${threshold}`);
1060
1086
  const pixels = this.__bytes__();
1061
1087
  const color = quantize.dominantColor(pixels, (r, g, b) => !(ignoreBlack && Math.max(r, g, b) < threshold) && !(ignoreWhite && Math.min(r, g, b) > 255 - threshold))
1062
1088
  || quantize.dominantColor(pixels, () => true);
@@ -1066,6 +1092,7 @@ export class Image {
1066
1092
  checkOptions(options, 'rotate(angle, { expand: false })');
1067
1093
  const { expand = true, mode = 'bilinear' } = options;
1068
1094
  oneOf(mode, TRANSFORM_MODES, 'rotate mode');
1095
+ boolean(expand, 'expand');
1069
1096
  angle = ((-finite(angle, 'angle') % 360) + 360) % 360;
1070
1097
  if (angle === 0)
1071
1098
  return this;
@@ -1111,6 +1138,10 @@ export class Image {
1111
1138
  const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
1112
1139
  const out = new Image(outWidth, outHeight);
1113
1140
  rotateGainMap(outWidth, outHeight);
1141
+ if (mode === 'bilinear' && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos)) {
1142
+ this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2);
1143
+ return this.__apply__(out);
1144
+ }
1114
1145
  const inverse = [cos, sin, -sin, cos,
1115
1146
  width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2];
1116
1147
  sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode);
@@ -1176,9 +1207,9 @@ export class Image {
1176
1207
  }
1177
1208
  roundCorners(options = {}) {
1178
1209
  checkOptions(options, 'roundCorners({ radius: 10 })');
1179
- let radius = options.radius ?? Math.min(this.width, this.height) / 4;
1180
- radius = finite(radius, 'radius');
1181
- radius = Math.max(0, Math.min(radius, this.width / 2, this.height / 2));
1210
+ const { radius: givenRadius = Math.min(this.width, this.height) / 4 } = options;
1211
+ let radius = nonNegative(givenRadius, 'radius');
1212
+ radius = Math.min(radius, this.width / 2, this.height / 2);
1182
1213
  const size = Math.ceil(radius);
1183
1214
  for (let y = 0; y < size; y++) {
1184
1215
  for (let x = 0; x < size; x++) {
@@ -1194,7 +1225,7 @@ export class Image {
1194
1225
  }
1195
1226
  fisheye(options = {}) {
1196
1227
  checkOptions(options, 'fisheye({ strength: 3 })');
1197
- const strength = finite(options.strength ?? 2, 'strength');
1228
+ const strength = positive(options.strength === undefined ? 2 : options.strength, 'strength');
1198
1229
  const r = new Image(this.width, this.height);
1199
1230
  const w = this.width;
1200
1231
  const h = this.height;
@@ -1238,24 +1269,31 @@ export class Image {
1238
1269
  if (subsampling !== undefined)
1239
1270
  oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1240
1271
  const backgroundColor = checkColor(background, 'background');
1272
+ const embed = gainMapEmbed(gainMapOption);
1241
1273
  const m = resolveMetadata(metadata);
1242
- const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling };
1243
- const source = this.__flattened__(backgroundColor, gainMapOption !== false) ?? this;
1274
+ const source = this.__flattened__(backgroundColor, embed !== null) ?? this;
1244
1275
  const gainMap = source.__gain_map__;
1245
- if (!gainMap || gainMapOption === false)
1276
+ const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined, subsampling, gray: source.__is_gray__() };
1277
+ if (!gainMap || !embed)
1246
1278
  return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1247
- const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1279
+ const { quality: mapQuality, scale } = embed;
1248
1280
  let width, height;
1249
1281
  if (scale !== undefined) {
1250
- const s = gainMapScale(scale);
1251
- width = Math.max(1, Math.round(this.width * s));
1252
- height = Math.max(1, Math.round(this.height * s));
1282
+ width = Math.max(1, Math.round(this.width * scale));
1283
+ height = Math.max(1, Math.round(this.height * scale));
1253
1284
  }
1254
1285
  const params = gainMap.__params__();
1255
- const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1286
+ const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality, width, height), params);
1256
1287
  const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) });
1257
1288
  return gainMapCodec.finish(primary, map);
1258
1289
  }
1290
+ __is_gray__() {
1291
+ const px = this.bitmap;
1292
+ for (let i = 0; i < px.length; i += 4)
1293
+ if (px[i] !== px[i + 1] || px[i] !== px[i + 2])
1294
+ return false;
1295
+ return true;
1296
+ }
1259
1297
  __flattened__(background, withGainMap) {
1260
1298
  const pixels = this.bitmap;
1261
1299
  let opaque = true;
@@ -1313,15 +1351,14 @@ export class Image {
1313
1351
  });
1314
1352
  }
1315
1353
  __gain_map_pixels__(option) {
1354
+ const embed = gainMapEmbed(option);
1316
1355
  const gainMap = this.__gain_map__;
1317
- if (!gainMap || option === false)
1356
+ if (!gainMap || !embed)
1318
1357
  return undefined;
1319
- const { quality = 90, scale } = typeof option === 'object' && option !== null ? option : {};
1320
- const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1358
+ const { quality: mapQuality = 90, scale } = embed;
1321
1359
  let map = gainMap.image;
1322
1360
  if (scale !== undefined) {
1323
- const s = gainMapScale(scale);
1324
- const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1361
+ const width = Math.max(1, Math.round(this.width * scale)), height = Math.max(1, Math.round(this.height * scale));
1325
1362
  if (width !== map.width || height !== map.height)
1326
1363
  map = map.clone().resize(width, height);
1327
1364
  }
@@ -1346,6 +1383,9 @@ export class Image {
1346
1383
  checkThreads(threads);
1347
1384
  pixelLimit(maxPixels);
1348
1385
  oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
1386
+ boolean(applyOrientation, 'applyOrientation');
1387
+ boolean(applyColorProfile, 'applyColorProfile');
1388
+ boolean(gainMap, 'gainMap');
1349
1389
  const data = view(input);
1350
1390
  const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
1351
1391
  const decoded = await decoding(() => {
@@ -1396,6 +1436,8 @@ export class Image {
1396
1436
  const { icc, cicp, colorSpace } = decoded;
1397
1437
  (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels);
1398
1438
  }
1439
+ if (!(decoded.width >= 1 && decoded.height >= 1) || decoded.pixels.length !== decoded.width * decoded.height * 4)
1440
+ throw new Error('Image: damaged or truncated image data');
1399
1441
  const image = new Image(decoded.width, decoded.height);
1400
1442
  image.bitmap = alignedPixels(decoded.pixels);
1401
1443
  if (gainMap && ImageType.isJPEG(dataView)) {
@@ -1479,14 +1521,14 @@ export class Image {
1479
1521
  checkOptions(options, 'renderSVG(svg, { width: 512 })');
1480
1522
  const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
1481
1523
  pixelLimit(maxPixels);
1482
- const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
1524
+ const { maxLayerPixels = 4 * maxPixels, maxImagePixels = maxPixels } = options;
1483
1525
  pixelLimit(maxLayerPixels, 'maxLayerPixels');
1484
1526
  pixelLimit(maxImagePixels, 'maxImagePixels');
1485
1527
  const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
1486
1528
  if (sizes > 1)
1487
1529
  throw new TypeError('renderSVG() takes one of width, height and scale');
1488
1530
  const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
1489
- const size = finite(givenWidth ?? givenHeight ?? scale ?? 1, `SVG ${mode}`);
1531
+ const size = finite(mode === 'width' ? givenWidth : mode === 'height' ? givenHeight : scale === undefined ? 1 : scale, `SVG ${mode}`);
1490
1532
  if (mode === 'scale' && size <= 0)
1491
1533
  throw new RangeError('SVG scale must be > 0');
1492
1534
  if (mode !== 'scale' && size < 1)
@@ -1503,7 +1545,7 @@ export class Image {
1503
1545
  const source = typeof svg === 'string' ? svg : view(svg);
1504
1546
  const images = new Map();
1505
1547
  const shown = (href) => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href);
1506
- let imagePixels = Number(maxImagePixels);
1548
+ let imagePixels = maxImagePixels;
1507
1549
  for (const { href, data } of svgRenderer.imageReferences(source)) {
1508
1550
  const value = given.get(href) ?? data;
1509
1551
  if (!value)
@@ -1534,7 +1576,7 @@ export class Image {
1534
1576
  images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) });
1535
1577
  }
1536
1578
  }
1537
- const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), Number(maxPixels), Number(maxLayerPixels));
1579
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images, (Array.isArray(fonts) ? fonts : [fonts]).map(font => view(font)), maxPixels, maxLayerPixels);
1538
1580
  const image = new Image(width, height);
1539
1581
  image.bitmap.set(pixels);
1540
1582
  return image;
@@ -1546,12 +1588,11 @@ export class Image {
1546
1588
  throw new TypeError('renderText(text, options) needs the font in the options');
1547
1589
  const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
1548
1590
  pixelLimit(maxPixels);
1591
+ boolean(hinting, 'hinting');
1549
1592
  const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
1550
1593
  const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
1551
1594
  const axes = textRenderer.axisValues(variations);
1552
- const size = finite(options.size, 'font size');
1553
- if (size < 0)
1554
- throw new RangeError(`Invalid font size: ${size}`);
1595
+ const size = positive(options.size, 'font size');
1555
1596
  if (finite(strokeWidth, 'stroke width') < 0)
1556
1597
  throw new RangeError('Invalid stroke width');
1557
1598
  const fonts = Array.isArray(font) ? font : [font];
@@ -1567,7 +1608,7 @@ export class Image {
1567
1608
  layout.width -= 2 * pad;
1568
1609
  if (layout.height !== undefined)
1569
1610
  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);
1611
+ 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);
1571
1612
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1572
1613
  const coverage = new Uint8Array(width * height);
1573
1614
  for (let y = 0; y < rendered.height; y++)
@@ -1790,3 +1831,4 @@ function distanceTransform(f, n, d, v, z, nearest) {
1790
1831
  nearest[q] = v[j];
1791
1832
  }
1792
1833
  }
1834
+ describe(Image, image => ({ width: image.width, height: image.height }));
@@ -9,6 +9,9 @@
9
9
  * | GIF | software, comment (comment extensions) |
10
10
  * | TGA | author, comment, creation time, software (extension area) |
11
11
  *
12
+ * The Exif and TGA text fields are ASCII in the file format; other characters are written as UTF-8, which readers
13
+ * that follow the format show wrongly. PNG text chunks take any text.
14
+ *
12
15
  * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same
13
16
  * image always encodes to the same bytes
14
17
  */
@@ -21,9 +24,15 @@ export interface Metadata {
21
24
  description?: string;
22
25
  /** The image's copyright info */
23
26
  copyright?: string;
24
- /** The image's creation time. Default: none (`null` leaves it out, too) */
27
+ /**
28
+ * The image's creation time
29
+ * @defaultValue None (`null` leaves it out, too)
30
+ */
25
31
  creationTime?: string | number | Date | null;
26
- /** The software used to create the image. Default: `'ImageScript'` (without a version), `null` leaves it out */
32
+ /**
33
+ * The software used to create the image
34
+ * @defaultValue `'ImageScript'` (without a version), `null` leaves it out
35
+ */
27
36
  software?: string | null;
28
37
  /** A disclaimer for the image */
29
38
  disclaimer?: string;
package/dist/metadata.js CHANGED
@@ -2,7 +2,9 @@ import { encode as utf8 } from "./util/utf8.js";
2
2
  import * as exif from "./codecs/exif.js";
3
3
  const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', 'disclaimer', 'warning', 'source', 'comment'];
4
4
  export function resolveMetadata(metadata = {}) {
5
- const { creationTime, software } = metadata || {};
5
+ if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata))
6
+ throw new TypeError(`metadata takes an object, like { title: 'Sunset' }, not ${metadata === null ? 'null' : Array.isArray(metadata) ? 'an array' : typeof metadata}`);
7
+ const { creationTime, software } = metadata;
6
8
  const resolved = {};
7
9
  if (creationTime !== undefined && creationTime !== null) {
8
10
  const time = new Date(creationTime);
@@ -11,9 +13,12 @@ export function resolveMetadata(metadata = {}) {
11
13
  resolved.creationTime = time;
12
14
  }
13
15
  for (const key of TEXT_FIELDS) {
14
- const value = key === 'software' && software === undefined ? 'ImageScript' : metadata?.[key];
15
- if (value)
16
- resolved[key] = String(value);
16
+ const value = key === 'software' && software === undefined ? 'ImageScript' : metadata[key];
17
+ if (value === undefined || value === null || value === '')
18
+ continue;
19
+ if (typeof value !== 'string')
20
+ throw new TypeError(`metadata ${key} must be a string, not ${typeof value}`);
21
+ resolved[key] = value;
17
22
  }
18
23
  return resolved;
19
24
  }
@@ -32,6 +37,8 @@ export function pngText(m) {
32
37
  };
33
38
  }
34
39
  export function exifData(m) {
40
+ if (!m.description && !m.software && !m.creationTime && !m.author && !m.copyright)
41
+ return undefined;
35
42
  return exif.encode({
36
43
  description: m.description,
37
44
  software: m.software,
package/dist/package.json CHANGED
@@ -1 +1 @@
1
- {"type":"module"}
1
+ {"type":"module","sideEffects":false}