imagescript 3.14.0 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/image.js CHANGED
@@ -32,6 +32,9 @@ import { rotateBilinear } from "./util/rotate.js";
32
32
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
33
33
  import { isOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from "./util/options.js";
34
34
  import { MAX_PIXELS, decoding } from "./util/limits.js";
35
+ import { GainMap } from "./gainmap.js";
36
+ import * as gain from "./util/gain.js";
37
+ import * as gainMapCodec from "./codecs/gainmap.js";
35
38
  function featureList(features) {
36
39
  if (typeof features !== 'object' || features === null)
37
40
  throw new TypeError('Features must be an object');
@@ -51,6 +54,7 @@ export class Image {
51
54
  __view__;
52
55
  __u32__;
53
56
  __bitmap__;
57
+ __gain_map__ = null;
54
58
  constructor(width, height) {
55
59
  width = ~~width;
56
60
  height = ~~height;
@@ -62,6 +66,14 @@ export class Image {
62
66
  this.__height__ = height;
63
67
  this.__set_bitmap__(new Uint8ClampedArray(width * height * 4));
64
68
  }
69
+ get gainMap() {
70
+ return this.__gain_map__;
71
+ }
72
+ set gainMap(gainMap) {
73
+ if (gainMap !== null && !(gainMap instanceof GainMap))
74
+ throw new TypeError('The gain map has to be a GainMap or null');
75
+ this.__gain_map__ = gainMap;
76
+ }
65
77
  get bitmap() {
66
78
  return this.__bitmap__;
67
79
  }
@@ -213,6 +225,10 @@ export class Image {
213
225
  }
214
226
  fill(color) {
215
227
  const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
228
+ if (typeof color !== 'function')
229
+ color = checkColor(color);
230
+ if (this.__gain_map__)
231
+ this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height);
216
232
  if (typeof color === 'function') {
217
233
  let offset = 0;
218
234
  for (let y = 0; y < this.height; y++)
@@ -220,7 +236,6 @@ export class Image {
220
236
  view.setUint32(offset, color(x, y), false);
221
237
  }
222
238
  else {
223
- color = checkColor(color);
224
239
  if (!this.bitmap.length)
225
240
  return this;
226
241
  view.setUint32(0, color, false);
@@ -234,6 +249,7 @@ export class Image {
234
249
  image.__width__ = this.width;
235
250
  image.__height__ = this.height;
236
251
  image.__set_bitmap__(new Uint8ClampedArray(this.bitmap));
252
+ image.__gain_map__ = this.__gain_map__ ? this.__gain_map__.clone() : null;
237
253
  return image;
238
254
  }
239
255
  static get RESIZE_NEAREST_NEIGHBOR() {
@@ -254,6 +270,7 @@ export class Image {
254
270
  scale(factor, modeOrOptions) {
255
271
  const { mode, fast } = resizeOptions(modeOrOptions);
256
272
  const image = this.__scale__(factor, mode, fast);
273
+ this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
257
274
  return this.__apply__(image);
258
275
  }
259
276
  __scale__(factor, mode = Image.RESIZE_BILINEAR, fast = true) {
@@ -264,6 +281,7 @@ export class Image {
264
281
  resize(width, height, modeOrOptions) {
265
282
  const { mode, fast } = resizeOptions(modeOrOptions);
266
283
  const image = this.__resize__(width, height, mode, fast);
284
+ this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height);
267
285
  return this.__apply__(image);
268
286
  }
269
287
  contain(width, height, modeOrOptions) {
@@ -277,18 +295,32 @@ export class Image {
277
295
  const options = resizeOptions(modeOrOptions);
278
296
  const result = new Image(width, height);
279
297
  this.contain(width, height, options);
280
- result.composite(this, (width - this.width) / 2, (height - this.height) / 2);
298
+ const x = (width - this.width) / 2 | 0, y = (height - this.height) / 2 | 0;
299
+ result.composite(this, x, y);
300
+ this.__gain_map__?.__transform__(this.width, this.height, result.width, result.height, (X, Y) => [X - x, Y - y]);
281
301
  return this.__apply__(result);
282
302
  }
283
303
  cover(width, height, modeOrOptions) {
284
304
  const options = resizeOptions(modeOrOptions);
285
305
  width = Math.floor(width);
286
306
  height = Math.floor(height);
307
+ if (!(width >= 1 && Number.isFinite(width)))
308
+ throw new RangeError('Image has to be at least 1 pixel wide');
309
+ if (!(height >= 1 && Number.isFinite(height)))
310
+ throw new RangeError('Image has to be at least 1 pixel high');
287
311
  const scale = Math.max(width / this.width, height / this.height);
288
- this.resize(Math.max(width, Math.round(this.width * scale)), Math.max(height, Math.round(this.height * scale)), options);
312
+ const resizedWidth = Math.max(width, Math.round(this.width * scale)), resizedHeight = Math.max(height, Math.round(this.height * scale));
313
+ if (options.mode !== Image.RESIZE_NEAREST_NEIGHBOR && width >= 1 && height >= 1) {
314
+ const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height };
315
+ this.__rescaled__?.(resizedWidth, resizedHeight);
316
+ const fx = resizedWidth / this.width, fy = resizedHeight / this.height;
317
+ this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy));
318
+ return this.__apply__(this.__resize__(resizedWidth, resizedHeight, options.mode, options.fast, region));
319
+ }
320
+ this.resize(resizedWidth, resizedHeight, options);
289
321
  return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height);
290
322
  }
291
- __resize__(width, height, mode = Image.RESIZE_BILINEAR, fast = true) {
323
+ __resize__(width, height, mode = Image.RESIZE_BILINEAR, fast = true, region) {
292
324
  if (width === Image.RESIZE_AUTO && height === Image.RESIZE_AUTO)
293
325
  throw new Error('RESIZE_AUTO can only be used for either width or height, not for both');
294
326
  else if (width === Image.RESIZE_AUTO)
@@ -306,8 +338,8 @@ export class Image {
306
338
  const filter = mode === Image.RESIZE_BILINEAR ? TRIANGLE : mode === Image.RESIZE_BICUBIC ? CUBIC : mode === Image.RESIZE_AREA ? BOX : null;
307
339
  if (!filter)
308
340
  throw new Error('Invalid resize mode');
309
- const image = new Image(width, height);
310
- resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast);
341
+ const image = new Image(region?.width ?? width, region?.height ?? height);
342
+ resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region);
311
343
  return image;
312
344
  }
313
345
  __resize_nearest_neighbor__(width, height) {
@@ -322,10 +354,23 @@ export class Image {
322
354
  return image;
323
355
  }
324
356
  crop(x, y, width, height) {
325
- return this.__apply__(this.__crop__(...this.__crop_bounds__(x, y, width, height)));
357
+ const bounds = this.__crop_bounds__(x, y, width, height);
358
+ this.__crop_gain_map__(this, ...bounds);
359
+ return this.__apply__(this.__crop__(...bounds));
360
+ }
361
+ __crop_gain_map__(target, x, y, width, height) {
362
+ const map = this.__gain_map__;
363
+ if (!map)
364
+ return;
365
+ const copy = target === this ? map : map.clone();
366
+ copy.__transform__(this.width, this.height, width, height, (X, Y) => [X + x, Y + y]);
367
+ target.__gain_map__ = copy;
326
368
  }
327
369
  region(x, y, width, height) {
328
- return this.__crop__(...this.__crop_bounds__(x, y, width, height));
370
+ const bounds = this.__crop_bounds__(x, y, width, height);
371
+ const image = this.__crop__(...bounds);
372
+ this.__crop_gain_map__(image, ...bounds);
373
+ return image;
329
374
  }
330
375
  __crop_bounds__(x, y, width, height) {
331
376
  x = ~~finite(x, 'x');
@@ -340,7 +385,10 @@ export class Image {
340
385
  }
341
386
  trim(color, options = {}) {
342
387
  const bounds = this.__trim_bounds__(color, options);
343
- return bounds ? this.__apply__(this.__crop__(...bounds)) : this;
388
+ if (!bounds)
389
+ return this;
390
+ this.__crop_gain_map__(this, ...bounds);
391
+ return this.__apply__(this.__crop__(...bounds));
344
392
  }
345
393
  __trim_bounds__(color, { tolerance = 0 }) {
346
394
  if (!(tolerance >= 0 && tolerance <= 1))
@@ -401,10 +449,17 @@ export class Image {
401
449
  width = ~~finite(width, 'width');
402
450
  height = ~~finite(height, 'height');
403
451
  if (typeof color !== 'function')
404
- return this.__fast_box__(x, y, width, height, checkColor(color));
405
- for (let tY = Math.max(0, -y); tY < height && tY + y < this.height; tY++)
406
- for (let tX = Math.max(0, -x); tX < width && tX + x < this.width; tX++)
407
- this.__set_pixel__(tX + x, tY + y, color(tX, tY));
452
+ this.__fast_box__(x, y, width, height, checkColor(color));
453
+ else
454
+ for (let tY = Math.max(0, -y); tY < height && tY + y < this.height; tY++)
455
+ for (let tX = Math.max(0, -x); tX < width && tX + x < this.width; tX++)
456
+ this.__set_pixel__(tX + x, tY + y, color(tX, tY));
457
+ if (this.__gain_map__)
458
+ gain.redraw(this, this.__gain_map__, Math.max(0, x), Math.max(0, y), Math.min(this.width, x + width), Math.min(this.height, y + height), (_x, _y, S, _boost, out) => {
459
+ out[0] = S[0];
460
+ out[1] = S[1];
461
+ out[2] = S[2];
462
+ });
408
463
  return this;
409
464
  }
410
465
  __fast_box__(x, y, width, height, color) {
@@ -439,6 +494,15 @@ export class Image {
439
494
  this.__blend_pixel__(px, py, value, coverage);
440
495
  }
441
496
  }
497
+ const map = this.__gain_map__;
498
+ if (map) {
499
+ const oS = map.offsetSDR, oH = map.offsetHDR;
500
+ gain.redraw(this, map, Math.max(0, Math.floor(cx - radius)), Math.max(0, Math.floor(cy - radius)), Math.min(this.width, Math.ceil(cx + radius)), Math.min(this.height, Math.ceil(cy + radius)), (px, py, S, boost, out) => {
501
+ const coverage = Math.min(1, Math.max(0, circleCoverage(px, py, cx, cy, radius)));
502
+ for (let c = 0; c < 3; c++)
503
+ out[c] = coverage * S[c] + (1 - coverage) * ((S[c] + oS[c]) * boost[c] - oH[c]);
504
+ });
505
+ }
442
506
  return this;
443
507
  }
444
508
  __blend_pixel__(x, y, color, amount) {
@@ -485,6 +549,8 @@ export class Image {
485
549
  return this;
486
550
  }
487
551
  red(factor, absoluteOrOptions = false) {
552
+ if (this.__gain_map__)
553
+ return this.__recolor__(image => image.red(factor, absoluteOrOptions));
488
554
  const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
489
555
  factor = finite(factor, 'red factor');
490
556
  if (factor < 0)
@@ -493,6 +559,8 @@ export class Image {
493
559
  return this;
494
560
  }
495
561
  green(factor, absoluteOrOptions = false) {
562
+ if (this.__gain_map__)
563
+ return this.__recolor__(image => image.green(factor, absoluteOrOptions));
496
564
  const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
497
565
  factor = finite(factor, 'green factor');
498
566
  if (factor < 0)
@@ -501,6 +569,8 @@ export class Image {
501
569
  return this;
502
570
  }
503
571
  blue(factor, absoluteOrOptions = false) {
572
+ if (this.__gain_map__)
573
+ return this.__recolor__(image => image.blue(factor, absoluteOrOptions));
504
574
  const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
505
575
  factor = finite(factor, 'blue factor');
506
576
  if (factor < 0)
@@ -513,6 +583,8 @@ export class Image {
513
583
  this.bitmap[i] = value * (absolute ? 255 : this.bitmap[i]);
514
584
  }
515
585
  lightness(value, absoluteOrOptions = false) {
586
+ if (this.__gain_map__)
587
+ return this.__recolor__(image => image.lightness(value, absoluteOrOptions));
516
588
  const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
517
589
  value = finite(value, 'lightness value');
518
590
  if (value < 0)
@@ -520,6 +592,8 @@ export class Image {
520
592
  return this.__map_hsla__(c => { c.l = value * (absolute ? 1 : c.l); });
521
593
  }
522
594
  saturation(value, absoluteOrOptions = false) {
595
+ if (this.__gain_map__)
596
+ return this.__recolor__(image => image.saturation(value, absoluteOrOptions), true);
523
597
  const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions;
524
598
  value = finite(value, 'saturation value');
525
599
  if (value < 0)
@@ -537,10 +611,12 @@ export class Image {
537
611
  const blend = BLEND_MODES[mode];
538
612
  if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
539
613
  throw new RangeError(`Invalid blend mode: ${mode}`);
540
- if (mode !== 'normal')
541
- return this.__blend__(source, x, y, opacity, blend);
542
614
  if (opacity === 0)
543
615
  return this;
616
+ if (this.__gain_map__ || source.__gain_map__)
617
+ return this.__composite_gain__(source, x, y, opacity, mode);
618
+ if (mode !== 'normal')
619
+ return this.__blend__(source, x, y, opacity, blend);
544
620
  const left = Math.max(0, x), top = Math.max(0, y);
545
621
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
546
622
  const dst = this.bitmap, src = source.bitmap;
@@ -567,6 +643,49 @@ export class Image {
567
643
  }
568
644
  return this;
569
645
  }
646
+ __composite_gain__(source, x, y, opacity, mode) {
647
+ const left = Math.max(0, x), top = Math.max(0, y);
648
+ const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
649
+ if (right <= left || bottom <= top)
650
+ return this;
651
+ const before = this.__crop__(left, top, right - left, bottom - top).bitmap, beforeWidth = right - left;
652
+ const ownMap = this.__gain_map__, sourceMap = source.__gain_map__;
653
+ this.__gain_map__ = source.__gain_map__ = null;
654
+ try {
655
+ this.composite(source, x, y, { opacity, mode });
656
+ }
657
+ finally {
658
+ this.__gain_map__ = ownMap;
659
+ source.__gain_map__ = sourceMap;
660
+ }
661
+ const blend = mode !== 'normal';
662
+ const map = this.__gain_map__ ??= gain.neutralMap(sourceMap, source.width, this.width, this.height);
663
+ if (sourceMap)
664
+ map.hdrCapacityMax = Math.max(map.hdrCapacityMax, sourceMap.hdrCapacityMax);
665
+ const sample = gain.gainSampler(source);
666
+ const sourceOS = sourceMap?.offsetSDR ?? [0, 0, 0], sourceOH = sourceMap?.offsetHDR ?? [0, 0, 0];
667
+ const oS = map.offsetSDR, oH = map.offsetHDR;
668
+ const src = source.bitmap, Gs = [0, 0, 0];
669
+ gain.redraw(this, map, left, top, right, bottom, (px, py, S, boost, out) => {
670
+ const s = 4 * ((py - y) * source.width + px - x), b = 4 * ((py - top) * beforeWidth + px - left);
671
+ const as = src[s + 3] / 255 * opacity, ab = before[b + 3] / 255;
672
+ const ao = as + ab * (1 - as);
673
+ if (sample)
674
+ sample(px - x, py - y, Gs);
675
+ for (let c = 0; c < 3; c++) {
676
+ const Sd = gain.LINEAR[before[b + c]], Ss = gain.LINEAR[src[s + c]];
677
+ const Hd = (Sd + oS[c]) * boost[c] - oH[c];
678
+ const Hs = sample ? (Ss + sourceOS[c]) * 2 ** Gs[c] - sourceOH[c] : Ss;
679
+ if (blend && ab === 1) {
680
+ out[c] = (S[c] + oS[c]) * boost[c] - oH[c];
681
+ continue;
682
+ }
683
+ const share = Math.abs(Ss - Sd) > 1e-4 ? Math.min(1, Math.max(0, (S[c] - Sd) / (Ss - Sd))) : ao > 0 ? as / ao : 0;
684
+ out[c] = ao > 0 ? share * Hs + (1 - share) * Hd : 0;
685
+ }
686
+ }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.gainMapMax ?? [0])));
687
+ return this;
688
+ }
570
689
  __blend__(source, x, y, opacity, blend) {
571
690
  const left = Math.max(0, x), top = Math.max(0, y);
572
691
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
@@ -591,6 +710,8 @@ export class Image {
591
710
  return this;
592
711
  }
593
712
  invert() {
713
+ if (this.__gain_map__)
714
+ return this.__unboost__(image => image.invert());
594
715
  const bitmap = this.bitmap;
595
716
  for (let i = 0; i < bitmap.length; i += 4) {
596
717
  bitmap[i] = 255 - bitmap[i];
@@ -600,9 +721,13 @@ export class Image {
600
721
  return this;
601
722
  }
602
723
  invertLightness() {
724
+ if (this.__gain_map__)
725
+ return this.__unboost__(image => image.invertLightness());
603
726
  return this.__map_hsla__(c => { c.l = 1 - c.l; });
604
727
  }
605
728
  invertValue() {
729
+ if (this.__gain_map__)
730
+ return this.__unboost__(image => image.invertValue());
606
731
  const bitmap = this.bitmap;
607
732
  for (let i = 0; i < bitmap.length; i += 4) {
608
733
  const max = Math.max(bitmap[i], bitmap[i + 1], bitmap[i + 2]);
@@ -618,6 +743,8 @@ export class Image {
618
743
  return this;
619
744
  }
620
745
  hueShift(degrees) {
746
+ if (this.__gain_map__)
747
+ return this.__recolor__(image => image.hueShift(degrees), true);
621
748
  degrees = finite(degrees, 'hue shift');
622
749
  return this.__map_hsla__(c => { c.h += degrees / 360; });
623
750
  }
@@ -676,6 +803,9 @@ export class Image {
676
803
  blur(radius) {
677
804
  if (!Number.isFinite(radius) || radius < 0)
678
805
  throw new RangeError('Invalid blur radius');
806
+ const map = this.__gain_map__;
807
+ if (map && radius * map.width / this.width >= 0.5)
808
+ map.image = map.image.clone().blur(radius * map.width / this.width);
679
809
  if (boxBlurRGBA(this.bitmap, this.width, this.height, radius))
680
810
  return this;
681
811
  const pixels = premultiply(this.bitmap);
@@ -704,30 +834,40 @@ export class Image {
704
834
  return this;
705
835
  }
706
836
  brightness(factor) {
837
+ if (this.__gain_map__)
838
+ return this.__recolor__(image => image.brightness(factor), false, v => v * factor);
707
839
  factor = finite(factor, 'brightness factor');
708
840
  if (factor < 0)
709
841
  throw new RangeError('Invalid brightness factor');
710
842
  return this.__map_channels__(v => v * factor);
711
843
  }
712
844
  contrast(factor) {
845
+ if (this.__gain_map__)
846
+ return this.__recolor__(image => image.contrast(factor), false, v => (v - 0.5) * factor + 0.5);
713
847
  factor = finite(factor, 'contrast factor');
714
848
  if (factor < 0)
715
849
  throw new RangeError('Invalid contrast factor');
716
850
  return this.__map_channels__(v => (v - 127.5) * factor + 127.5);
717
851
  }
718
852
  gamma(gamma) {
853
+ if (this.__gain_map__)
854
+ return this.__recolor__(image => image.gamma(gamma), false, v => Math.max(0, v) ** (1 / gamma));
719
855
  gamma = finite(gamma, 'gamma');
720
856
  if (gamma <= 0)
721
857
  throw new RangeError('Invalid gamma');
722
858
  return this.__map_channels__(v => 255 * (v / 255) ** (1 / gamma));
723
859
  }
724
860
  greyscale() {
861
+ if (this.__gain_map__)
862
+ return this.__recolor__(image => image.greyscale(), true);
725
863
  const bitmap = this.bitmap;
726
864
  for (let i = 0; i < bitmap.length; i += 4)
727
865
  bitmap[i] = bitmap[i + 1] = bitmap[i + 2] = bitmap[i] * 19595 + bitmap[i + 1] * 38470 + bitmap[i + 2] * 7471 + 0x8000 >> 16;
728
866
  return this;
729
867
  }
730
868
  sepia() {
869
+ if (this.__gain_map__)
870
+ return this.__recolor__(image => image.sepia(), true);
731
871
  const bitmap = this.bitmap;
732
872
  for (let i = 0; i < bitmap.length; i += 4) {
733
873
  const r = bitmap[i], g = bitmap[i + 1], b = bitmap[i + 2];
@@ -803,6 +943,13 @@ export class Image {
803
943
  return this;
804
944
  const { width, height } = this;
805
945
  const src = this.__u32__;
946
+ const rotateGainMap = (outWidth, outHeight) => {
947
+ const rad = angle * Math.PI / 180, sin = Math.sin(rad), cos = Math.cos(rad);
948
+ this.__gain_map__?.__transform__(width, height, outWidth, outHeight, (X, Y) => {
949
+ const dx = X - outWidth / 2, dy = Y - outHeight / 2;
950
+ return [dx * cos - dy * sin + width / 2, dx * sin + dy * cos + height / 2];
951
+ });
952
+ };
806
953
  if (angle === 90 || angle === 180 || angle === 270) {
807
954
  const out = new Image(angle === 180 ? width : height, angle === 180 ? height : width);
808
955
  const dst = out.__u32__;
@@ -816,6 +963,7 @@ export class Image {
816
963
  else
817
964
  dst[x * height + height - 1 - y] = i;
818
965
  }
966
+ rotateGainMap(out.width, out.height);
819
967
  return this.__apply__(out);
820
968
  }
821
969
  const rad = angle * Math.PI / 180;
@@ -823,6 +971,7 @@ export class Image {
823
971
  const outWidth = resize ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width;
824
972
  const outHeight = resize ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height;
825
973
  const out = new Image(outWidth, outHeight);
974
+ rotateGainMap(outWidth, outHeight);
826
975
  if (fast && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos))
827
976
  return this.__apply__(out);
828
977
  const s8 = this.bitmap, d8 = out.bitmap;
@@ -895,11 +1044,40 @@ export class Image {
895
1044
  }
896
1045
  else
897
1046
  throw new RangeError('Invalid flip direction');
1047
+ this.__gain_map__?.__transform__(width, height, width, height, direction === 'horizontal' ? (X, Y) => [width - X, Y] : (X, Y) => [X, height - Y]);
898
1048
  return this;
899
1049
  }
900
1050
  __bytes__() {
901
1051
  return new Uint8Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
902
1052
  }
1053
+ __unboost__(apply) {
1054
+ const map = this.__gain_map__;
1055
+ this.__gain_map__ = null;
1056
+ try {
1057
+ apply(this);
1058
+ }
1059
+ finally {
1060
+ this.__gain_map__ = gain.neutralMap(map, this.width, this.width, this.height);
1061
+ }
1062
+ return this;
1063
+ }
1064
+ __recolor__(apply, chromaOnly = false, exact) {
1065
+ const map = this.__gain_map__;
1066
+ this.__gain_map__ = null;
1067
+ try {
1068
+ if (chromaOnly && map.channels === 1) {
1069
+ apply(this);
1070
+ return this;
1071
+ }
1072
+ const before = this.__resize__(map.width, map.height);
1073
+ apply(this);
1074
+ gain.recolor(map, before, apply, exact);
1075
+ return this;
1076
+ }
1077
+ finally {
1078
+ this.__gain_map__ = map;
1079
+ }
1080
+ }
903
1081
  __apply__(image) {
904
1082
  this.__width__ = image.__width__;
905
1083
  this.__height__ = image.__height__;
@@ -1011,6 +1189,13 @@ export class Image {
1011
1189
  ru32[y * w + x] = tu32[ny * w + nx];
1012
1190
  }
1013
1191
  }
1192
+ this.__gain_map__?.__transform__(w, h, w, h, (X, Y) => {
1193
+ const xco = X / w - 0.5, yco = Y / h - 0.5, dfc = Math.sqrt(xco ** 2 + yco ** 2);
1194
+ if (dfc === 0)
1195
+ return [X, Y];
1196
+ const dis = 2 * dfc ** strength;
1197
+ return [(dis * xco / dfc + 0.5) * w, (dis * yco / dfc + 0.5) * h];
1198
+ });
1014
1199
  return this.__apply__(r);
1015
1200
  }
1016
1201
  async encode(compressionOrOptions = 4, metadataArgument = {}) {
@@ -1027,16 +1212,32 @@ export class Image {
1027
1212
  return this.encode(compressionOrOptions, metadata);
1028
1213
  }
1029
1214
  async encodeJPEG(qualityOrOptions = 90) {
1030
- const { quality = 90, metadata = {} } = isOptions(qualityOrOptions) ? qualityOrOptions : { quality: qualityOrOptions };
1215
+ const { quality = 90, metadata = {}, gainMap: gainMapOption = true } = isOptions(qualityOrOptions) ? qualityOrOptions : { quality: qualityOrOptions };
1031
1216
  const m = resolveMetadata(metadata);
1032
- return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1217
+ const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined };
1218
+ const gainMap = this.__gain_map__;
1219
+ if (!gainMap || gainMapOption === false)
1220
+ return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), base);
1221
+ const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {};
1222
+ let width, height;
1223
+ if (scale !== undefined) {
1224
+ const s = finite(scale, 'gain map scale');
1225
+ if (!(s > 0 && s <= 1))
1226
+ throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1227
+ width = Math.max(1, Math.round(this.width * s));
1228
+ height = Math.max(1, Math.round(this.height * s));
1229
+ }
1230
+ const params = gainMap.__params__();
1231
+ const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params);
1232
+ const primary = jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) });
1233
+ return gainMapCodec.finish(primary, map);
1033
1234
  }
1034
1235
  async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = {}) {
1035
1236
  checkThreads(threads);
1036
1237
  const exif = exifData(resolveMetadata(metadata));
1037
1238
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
1038
1239
  if (!lossy)
1039
- return webp.encode(this.__bytes__(), this.width, this.height, exif, threads);
1240
+ return webp.encode(this.__bytes__(), this.width, this.height, exif, threads, effort);
1040
1241
  return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif);
1041
1242
  }
1042
1243
  async encodeTGA({ metadata = {} } = {}) {
@@ -1049,29 +1250,46 @@ export class Image {
1049
1250
  async encodeQOI() {
1050
1251
  return qoi.encode(this.__bytes__(), this.width, this.height);
1051
1252
  }
1052
- async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1253
+ async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1053
1254
  checkEffort(effort, 2);
1054
1255
  checkThreads(threads);
1055
1256
  if (subsampling !== '4:4:4' && subsampling !== '4:2:0')
1056
1257
  throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`);
1057
1258
  const exif = exifData(resolveMetadata(metadata));
1058
- return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads });
1259
+ return avifEnc.encode(this.__bytes__(), this.width, this.height, {
1260
+ quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads, gainMap: this.__gain_map_pixels__(gainMap)
1261
+ });
1059
1262
  }
1060
- async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {} } = {}) {
1263
+ __gain_map_pixels__(option) {
1264
+ const gainMap = this.__gain_map__;
1265
+ if (!gainMap || option === false)
1266
+ return undefined;
1267
+ const { quality = 90, scale } = typeof option === 'object' && option !== null ? option : {};
1268
+ const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality'));
1269
+ let map = gainMap.image;
1270
+ if (scale !== undefined) {
1271
+ const s = finite(scale, 'gain map scale');
1272
+ if (!(s > 0 && s <= 1))
1273
+ throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`);
1274
+ const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s));
1275
+ if (width !== map.width || height !== map.height)
1276
+ map = map.clone().resize(width, height);
1277
+ }
1278
+ return { pixels: map.__bytes__(), width: map.width, height: map.height, params: gainMap.__params__(), quality: mapQuality };
1279
+ }
1280
+ async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = {}) {
1061
1281
  checkEffort(effort, 2);
1062
1282
  checkThreads(threads);
1063
- let distance = 0;
1064
- if (quality !== undefined) {
1065
- const q = checkQuality(quality);
1066
- distance = q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
1067
- }
1068
- return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)), distance, effort, threads);
1283
+ const distanceOf = (q) => q >= 100 ? 0 : q >= 30 ? 0.1 + (100 - q) * 0.09 : 53 / 3000 * q * q - 23 / 20 * q + 25;
1284
+ const distance = quality === undefined ? 0 : distanceOf(checkQuality(quality));
1285
+ const map = this.__gain_map_pixels__(gainMap);
1286
+ return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)), distance, effort, threads, map && { ...map, distance: distanceOf(map.quality) });
1069
1287
  }
1070
1288
  async encodePNM() {
1071
1289
  return netpbm.encode(this.__bytes__(), this.width, this.height);
1072
1290
  }
1073
1291
  static async decode(input, options = {}) {
1074
- const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads() } = options;
1292
+ const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
1075
1293
  checkThreads(threads);
1076
1294
  if (!(Number(maxPixels) > 0))
1077
1295
  throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
@@ -1098,9 +1316,9 @@ export class Image {
1098
1316
  return { width, height, pixels };
1099
1317
  };
1100
1318
  if (ImageType.isAVIF(dataView))
1101
- return avif.decode(data, maxPixels, toneMapping, threads);
1319
+ return avif.decode(data, maxPixels, toneMapping, threads, gainMap);
1102
1320
  if (ImageType.isJXL(dataView))
1103
- return jxl.decode(data, maxPixels, toneMapping, threads);
1321
+ return jxl.decode(data, maxPixels, toneMapping, threads, gainMap);
1104
1322
  if (ImageType.isBMP(dataView))
1105
1323
  return bitmap(bmp.decode(data, maxPixels));
1106
1324
  if (ImageType.isICO(dataView))
@@ -1123,7 +1341,36 @@ export class Image {
1123
1341
  }
1124
1342
  const image = new Image(decoded.width, decoded.height);
1125
1343
  image.bitmap = decoded.pixels;
1126
- return applyOrientation && decoded.orientation ? image.__orient__(decoded.orientation) : image;
1344
+ if (gainMap && ImageType.isJPEG(dataView)) {
1345
+ try {
1346
+ const found = gainMapCodec.find(data);
1347
+ const size = found && gainMapCodec.dimensions(found.map);
1348
+ if (found && size && size.width * size.height <= maxPixels)
1349
+ image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple);
1350
+ }
1351
+ catch {
1352
+ image.__gain_map__ = null;
1353
+ }
1354
+ }
1355
+ if (decoded.gainMap) {
1356
+ const { width, height, pixels, params } = decoded.gainMap;
1357
+ const map = new Image(width, height);
1358
+ map.bitmap = pixels;
1359
+ image.__gain_map__ = GainMap.__from_pixels__(map, params);
1360
+ }
1361
+ if (applyOrientation && decoded.orientation && decoded.orientation > 1) {
1362
+ image.__orient__(decoded.orientation);
1363
+ const map = image.__gain_map__;
1364
+ if (map) {
1365
+ try {
1366
+ map.image = map.image.__orient__(decoded.orientation);
1367
+ }
1368
+ catch {
1369
+ image.__gain_map__ = null;
1370
+ }
1371
+ }
1372
+ }
1373
+ return image;
1127
1374
  }
1128
1375
  __orient__(orientation) {
1129
1376
  if (orientation <= 1 || orientation > 8)
package/dist/index.d.ts CHANGED
@@ -6,6 +6,8 @@ export { Image } from './image.js';
6
6
  export type { Color, ColorFunction, ResizeMode, SVGScaleMode, PNGMetadata, TextStyle, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, AdjustOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, SVGOptions, TextOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.js';
7
7
  export { Frame } from './frame.js';
8
8
  export type { FrameDisposalModeName, FrameDisposalModeId, FrameOptions } from './frame.js';
9
+ export { GainMap } from './gainmap.js';
10
+ export type { GainMapOptions } from './gainmap.js';
9
11
  export { GIF } from './gif.js';
10
12
  export { Animation } from './animation.js';
11
13
  export type { AnimationOptions, AnimationDecodeOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.js';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { view } from "./util/mem.js";
7
7
  import { ImageType } from "./image-type.js";
8
8
  export { Image } from "./image.js";
9
9
  export { Frame } from "./frame.js";
10
+ export { GainMap } from "./gainmap.js";
10
11
  export { GIF } from "./gif.js";
11
12
  export { Animation } from "./animation.js";
12
13
  export { AnimationEncoder } from "./animation-encoder.js";