imagescript 3.11.0 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # ImageScript
2
2
  ##### zero-dependency JavaScript image manipulation
3
3
  [![Discord Server](https://img.shields.io/discord/691713541262147687.svg?label=Discord&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2&style=for-the-badge)](https://discord.gg/8hPrwAH)
4
- [![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge)](https://imagescript.matmen.dev/)
4
+ [![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge)](https://imagescript.dev/)
5
5
  [![Github](https://img.shields.io/badge/Github-Repository-181717?logo=github&style=for-the-badge)](https://github.com/matmen/ImageScript)
6
6
  [![NPM](https://nodei.co/npm/imagescript.png)](https://www.npmjs.com/package/imagescript)
7
7
 
@@ -50,27 +50,27 @@ Coordinates start at `(0, 0)`, the top left pixel. For a bigger example, see the
50
50
  | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
51
51
  | TIFF, ICO/CUR, Radiance HDR | ✓ | |
52
52
 
53
- [Animations](https://imagescript.matmen.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
53
+ [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
54
54
  and encoded as GIF, APNG or WebP, all at once or
55
- [frame by frame](https://imagescript.matmen.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
55
+ [frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
56
56
  P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them.
57
57
 
58
- - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
59
- all scripts, color emoji
60
- - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), including text (with fonts you pass
58
+ - [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
59
+ all scripts, color emoji, variable fonts
60
+ - [SVG rendering](https://imagescript.dev/classes/Image.html#rendersvg), including text (with fonts you pass
61
61
  or fonts embedded in the SVG)
62
- - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
63
- [cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
64
- [rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
65
- [trimming](https://imagescript.matmen.dev/classes/Image.html#trim),
66
- [rounded corners](https://imagescript.matmen.dev/classes/Image.html#roundcorners), ...
67
- - [Compositing](https://imagescript.matmen.dev/classes/Image.html#composite) with opacity and blend modes
68
- - Filters and color adjustments: [blur](https://imagescript.matmen.dev/classes/Image.html#blur),
69
- [sharpen](https://imagescript.matmen.dev/classes/Image.html#sharpen),
70
- [brightness](https://imagescript.matmen.dev/classes/Image.html#brightness),
71
- [hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...
72
-
73
- The [documentation](https://imagescript.matmen.dev/) covers the full API. When upgrading from an older major version,
62
+ - [Resizing](https://imagescript.dev/classes/Image.html#resize),
63
+ [cropping](https://imagescript.dev/classes/Image.html#crop),
64
+ [rotating](https://imagescript.dev/classes/Image.html#rotate),
65
+ [trimming](https://imagescript.dev/classes/Image.html#trim),
66
+ [rounded corners](https://imagescript.dev/classes/Image.html#roundcorners), ...
67
+ - [Compositing](https://imagescript.dev/classes/Image.html#composite) with opacity and blend modes
68
+ - Filters and color adjustments: [blur](https://imagescript.dev/classes/Image.html#blur),
69
+ [sharpen](https://imagescript.dev/classes/Image.html#sharpen),
70
+ [brightness](https://imagescript.dev/classes/Image.html#brightness),
71
+ [hueShift](https://imagescript.dev/classes/Image.html#hueshift), ...
72
+
73
+ The [documentation](https://imagescript.dev/) covers the full API. When upgrading from an older major version,
74
74
  see the [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md). [bench/](bench/README.md)
75
75
  compares ImageScript's speed and file sizes with Jimp, sharp and other libraries.
76
76
 
@@ -12,7 +12,7 @@ following projects, under their own licenses. Each derived file says so in its h
12
12
  | [font-rs](https://github.com/raphlinus/font-rs) by Raph Levien | `src/render/text.ts` (the `Rasterizer` class, also used for SVGs) | Apache-2.0 |
13
13
  | [RFC 9649](https://www.rfc-editor.org/rfc/rfc9649) (WebP Image Format) | `src/codecs/vp8l.ts` (lossless bitstream, short distance code table), `src/codecs/webp.ts` (container) | BSD-3-Clause (Revised BSD) |
14
14
  | [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386) (VP8 Data Format and Decoding Guide, with the libvpx reference decoder) | `src/codecs/vp8-tables.ts` (probability and quantizer tables), `src/codecs/vp8.ts` (decoding procedures) | BSD-3-Clause |
15
- | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`), `src/codecs/sharpyuv.ts` (the sharp RGB to YUV conversion, libsharpyuv) | BSD-3-Clause |
15
+ | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`), `src/codecs/sharpyuv.ts` (the sharp RGB to YUV conversion, libsharpyuv), `src/codecs/vp8l.ts` (the lossless encoder's entropy analysis and color transform search) | BSD-3-Clause |
16
16
  | [dav1d](https://code.videolan.org/videolan/dav1d) by VideoLAN, the dav1d authors and Two Orioles | `src/codecs/av1/*` (the AV1 decoder, and the encoder's syntax, contexts and reconstruction mirrored from it: bitstream parsing, symbol decoding, prediction, inverse transforms, loop filters, film grain; the tables in `src/codecs/av1/data.ts`, generated from dav1d by `scripts/av1-tables.c`) | BSD-2-Clause |
17
17
  | [libaom](https://aomedia.googlesource.com/aom/) by the Alliance for Open Media | `src/codecs/av1/msac-enc.ts` (the symbol encoder), `src/codecs/av1/fdct.ts` (the forward Walsh-Hadamard transform), `src/codecs/av1/encode.ts` (the loop filter level from the quantizer), `src/codecs/avif-enc.ts` (the quantizer to qindex table) | BSD-2-Clause |
18
18
  | [libavif](https://github.com/AOMediaCodec/libavif) by Joe Drago | `src/codecs/avif.ts` (YUV to RGB conversion with bilinear chroma upsampling, alpha range expansion and unpremultiplication) | BSD-2-Clause |
@@ -540,7 +540,7 @@ async function decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, to
540
540
  else if (box.type === 'imir')
541
541
  pixels = mirror(pixels, width, height, d[box.start] & 1);
542
542
  }
543
- return { width, height, pixels, icc };
543
+ return { width, height, pixels, icc, cicp: icc ? undefined : [color.primaries, color.transfer] };
544
544
  }
545
545
  function iccOf(d, it) {
546
546
  for (const { box } of it.props) {
@@ -662,5 +662,5 @@ async function decodeSequence(d, moov, maxPixels, toneMapping) {
662
662
  return fromFrame(decodeAV1(data, 0, data.length, { maxPixels }));
663
663
  };
664
664
  const color = frame(colorTrack);
665
- return { width: color.width, height: color.height, pixels: await toRgba(color, alphaTrack ? frame(alphaTrack) : null, toneMapping) };
665
+ return { width: color.width, height: color.height, pixels: await toRgba(color, alphaTrack ? frame(alphaTrack) : null, toneMapping), cicp: [color.primaries, color.transfer] };
666
666
  }
@@ -1,7 +1,9 @@
1
1
  /*!
2
2
  * WebP lossless (VP8L) bitstream, as specified in RFC 9649 ("WebP Image Format") section 3 onwards, including its
3
3
  * table of short distance codes. Copyright (c) 2024 IETF Trust and the persons identified as the document authors,
4
- * Revised BSD License (see THIRD_PARTY_NOTICES.md)
4
+ * Revised BSD License (see THIRD_PARTY_NOTICES.md). The encoder's choice of transforms follows libwebp's entropy
5
+ * analysis (src/enc/vp8l_enc.c, AnalyzeEntropy), its color transform search libwebp's (src/enc/predictor_enc.c).
6
+ * Copyright (c) 2012 Google Inc., BSD-3-Clause License
5
7
  */
6
8
  import { ByteWriter } from "../util/bytes.js";
7
9
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
@@ -1177,6 +1179,202 @@ async function writeImage(w, pixels, width, isMain, threads = null) {
1177
1179
  const subPixels = (a, b) => ((a | 0x00ff00ff) - (b & 0xff00ff00) & 0xff00ff00 | (a | 0xff00ff00) - (b & 0x00ff00ff) & 0x00ff00ff) >>> 0;
1178
1180
  const BYTE_COST = Uint8Array.from({ length: 256 }, (_, c) => c < 128 ? c : 256 - c);
1179
1181
  const residualCost = (r) => BYTE_COST[r & 255] + BYTE_COST[r >>> 8 & 255] + BYTE_COST[r >>> 16 & 255] + BYTE_COST[r >>> 24];
1182
+ function redBlueBits(p) {
1183
+ const red = new Uint32Array(256), blue = new Uint32Array(256);
1184
+ for (let i = 0; i < p.length; i++) {
1185
+ red[p[i] >> 16 & 255]++;
1186
+ blue[p[i] & 255]++;
1187
+ }
1188
+ let bits = 0;
1189
+ for (const h of [red, blue])
1190
+ for (const n of h)
1191
+ if (n)
1192
+ bits += n * Math.log2(p.length / n);
1193
+ return bits;
1194
+ }
1195
+ const slog = (v) => v ? v * Math.log2(v) : 0;
1196
+ let SLOG;
1197
+ function crossColorCost(accumulated, accumulatedSlogs, accumulatedLogs, counts, touched, n, accumulatedSum, accumulatedSlog) {
1198
+ const table = SLOG;
1199
+ let sum = accumulatedSlog, sumX = 0;
1200
+ for (let k = 0; k < n; k++) {
1201
+ const i = touched[k], x = counts[i], y = accumulated[i];
1202
+ sumX += x;
1203
+ if (x + y < table.length)
1204
+ sum += table[x] + table[x + y] - accumulatedSlogs[i];
1205
+ else {
1206
+ const t = x / y;
1207
+ sum += table[x] + x * accumulatedLogs[i] + (x + y) * (t - t * t / 2 + t * t * t / 3) * Math.LOG2E;
1208
+ }
1209
+ }
1210
+ let bias = 3 * counts[0], weight = 240;
1211
+ for (let i = 1; i < 16; i++) {
1212
+ bias += weight * (counts[i] + counts[256 - i]) / 100;
1213
+ weight *= 0.6;
1214
+ }
1215
+ return slog(sumX) + slog(sumX + accumulatedSum) - sum - bias / 10;
1216
+ }
1217
+ function colorTransform(p, width, height, bits) {
1218
+ const size = 1 << bits, blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1219
+ const image = new Uint32Array(blocksX * blocksY);
1220
+ const accumulatedRed = new Uint32Array(256), accumulatedBlue = new Uint32Array(256), histo = new Uint32Array(256), touched = new Int32Array(256);
1221
+ const green = new Int32Array(size * size), red = new Int32Array(size * size), redByte = new Int32Array(size * size), blue = new Int32Array(size * size);
1222
+ const s8 = (v) => v << 24 >> 24;
1223
+ SLOG ??= Float64Array.from({ length: 65536 }, (_, v) => slog(v));
1224
+ const redSlogs = new Float64Array(256), blueSlogs = new Float64Array(256), redLogs = new Float64Array(256), blueLogs = new Float64Array(256);
1225
+ const sums = (h, slogs, logs) => {
1226
+ let total = 0, entropy = 0;
1227
+ for (let i = 0; i < 256; i++) {
1228
+ total += h[i];
1229
+ entropy += slogs[i] = slog(h[i]);
1230
+ logs[i] = h[i] ? Math.log2(h[i]) : 0;
1231
+ }
1232
+ return [total, entropy];
1233
+ };
1234
+ let prevX = [0, 0, 0], prevY = [0, 0, 0];
1235
+ for (let by = 0; by < blocksY; by++) {
1236
+ for (let bx = 0; bx < blocksX; bx++) {
1237
+ const x0 = bx * size, y0 = by * size, x1 = Math.min(width, x0 + size), y1 = Math.min(height, y0 + size);
1238
+ if (by) {
1239
+ const above = image[(by - 1) * blocksX + bx];
1240
+ prevY = [above & 255, above >> 8 & 255, above >> 16 & 255];
1241
+ }
1242
+ let count = 0;
1243
+ for (let y = y0; y < y1; y++)
1244
+ for (let i = y * width + x0 + (y & 3), end = y * width + x1; i < end; i += 4, count++) {
1245
+ const v = p[i];
1246
+ green[count] = s8(v >> 8);
1247
+ red[count] = s8(v >> 16);
1248
+ redByte[count] = v >> 16 & 255;
1249
+ blue[count] = v & 255;
1250
+ }
1251
+ const [redSum, redSlog] = sums(accumulatedRed, redSlogs, redLogs);
1252
+ const redCost = (gtr) => {
1253
+ const m = s8(gtr);
1254
+ let n = 0;
1255
+ for (let k = 0; k < count; k++) {
1256
+ const v = redByte[k] - (m * green[k] >> 5) & 255;
1257
+ if (!histo[v]++)
1258
+ touched[n++] = v;
1259
+ }
1260
+ let cost = crossColorCost(accumulatedRed, redSlogs, redLogs, histo, touched, n, redSum, redSlog);
1261
+ for (let k = 0; k < n; k++)
1262
+ histo[touched[k]] = 0;
1263
+ if ((gtr & 255) === prevX[0])
1264
+ cost -= 3;
1265
+ if ((gtr & 255) === prevY[0])
1266
+ cost -= 3;
1267
+ if (gtr === 0)
1268
+ cost -= 3;
1269
+ return cost;
1270
+ };
1271
+ let gtr = 0, best = redCost(0);
1272
+ for (let iter = 0; iter < 6; iter++) {
1273
+ const step = 32 >> iter;
1274
+ for (const offset of [-step, step]) {
1275
+ const cost = redCost(gtr + offset);
1276
+ if (cost < best)
1277
+ [best, gtr] = [cost, gtr + offset];
1278
+ }
1279
+ }
1280
+ const [blueSum, blueSlog] = sums(accumulatedBlue, blueSlogs, blueLogs);
1281
+ const blueCost = (gtb, rtb) => {
1282
+ const mg = s8(gtb), mr = s8(rtb);
1283
+ let n = 0;
1284
+ for (let k = 0; k < count; k++) {
1285
+ const v = blue[k] - (mg * green[k] >> 5) - (mr * red[k] >> 5) & 255;
1286
+ if (!histo[v]++)
1287
+ touched[n++] = v;
1288
+ }
1289
+ let cost = crossColorCost(accumulatedBlue, blueSlogs, blueLogs, histo, touched, n, blueSum, blueSlog);
1290
+ for (let k = 0; k < n; k++)
1291
+ histo[touched[k]] = 0;
1292
+ if ((gtb & 255) === prevX[1])
1293
+ cost -= 3;
1294
+ if ((gtb & 255) === prevY[1])
1295
+ cost -= 3;
1296
+ if ((rtb & 255) === prevX[2])
1297
+ cost -= 3;
1298
+ if ((rtb & 255) === prevY[2])
1299
+ cost -= 3;
1300
+ if (gtb === 0)
1301
+ cost -= 3;
1302
+ if (rtb === 0)
1303
+ cost -= 3;
1304
+ return cost;
1305
+ };
1306
+ let gtb = 0, rtb = 0;
1307
+ best = blueCost(0, 0);
1308
+ for (const step of [16, 8, 4]) {
1309
+ for (const [dg, dr] of [[0, -1], [0, 1], [-1, 0], [1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1]]) {
1310
+ const cost = blueCost(gtb + dg * step, rtb + dr * step);
1311
+ if (cost < best)
1312
+ [best, gtb, rtb] = [cost, gtb + dg * step, rtb + dr * step];
1313
+ }
1314
+ }
1315
+ prevX = [gtr & 255, gtb & 255, rtb & 255];
1316
+ image[by * blocksX + bx] = (0xff000000 | prevX[2] << 16 | prevX[1] << 8 | prevX[0]) >>> 0;
1317
+ const mgr = s8(gtr), mgb = s8(gtb), mrb = s8(rtb);
1318
+ for (let y = y0; y < y1; y++)
1319
+ for (let i = y * width + x0, end = y * width + x1; i < end; i++) {
1320
+ const v = p[i], g = s8(v >> 8), rs = s8(v >> 16);
1321
+ const r = (v >> 16) - (mgr * g >> 5) & 255, b = v - (mgb * g >> 5) - (mrb * rs >> 5) & 255;
1322
+ p[i] = (v & 0xff00ff00 | r << 16 | b) >>> 0;
1323
+ }
1324
+ for (let y = y0; y < y1; y++)
1325
+ for (let i = y * width + x0, end = y * width + x1; i < end; i++) {
1326
+ const v = p[i];
1327
+ if (i >= 2 && v === p[i - 2] && v === p[i - 1])
1328
+ continue;
1329
+ if (i >= width + 2 && p[i - 2] === p[i - width - 2] && p[i - 1] === p[i - width - 1] && v === p[i - width])
1330
+ continue;
1331
+ accumulatedRed[v >> 16 & 255]++;
1332
+ accumulatedBlue[v & 255]++;
1333
+ }
1334
+ }
1335
+ }
1336
+ return image;
1337
+ }
1338
+ function analyze(argb, width, height, bits) {
1339
+ const h = Array.from({ length: 12 }, () => new Uint32Array(256));
1340
+ let prev = argb[0];
1341
+ for (let i = 0; i < argb.length; i++) {
1342
+ const p = argb[i], d = subPixels(p, prev);
1343
+ prev = p;
1344
+ if (d === 0 || (i >= width && p === argb[i - width]))
1345
+ continue;
1346
+ h[0][p >>> 24]++;
1347
+ h[1][p >> 16 & 255]++;
1348
+ h[2][p >> 8 & 255]++;
1349
+ h[3][p & 255]++;
1350
+ h[4][d >>> 24]++;
1351
+ h[5][d >> 16 & 255]++;
1352
+ h[6][d >> 8 & 255]++;
1353
+ h[7][d & 255]++;
1354
+ h[8][(p >> 16) - (p >> 8) & 255]++;
1355
+ h[9][p - (p >> 8) & 255]++;
1356
+ h[10][(d >> 16) - (d >> 8) & 255]++;
1357
+ h[11][d - (d >> 8) & 255]++;
1358
+ }
1359
+ for (const k of [4, 5, 6, 7, 10, 11])
1360
+ h[k][0]++;
1361
+ const bitsOf = (counts) => {
1362
+ let total = 0, sum = 0;
1363
+ for (const n of counts)
1364
+ total += n;
1365
+ for (const n of counts)
1366
+ if (n)
1367
+ sum += n * Math.log2(total / n);
1368
+ return sum;
1369
+ };
1370
+ const e = h.map(bitsOf), blocks = subSize(width, bits) * subSize(height, bits);
1371
+ const entropy = [
1372
+ e[0] + e[1] + e[2] + e[3], e[4] + e[5] + e[6] + e[7] + blocks * Math.log2(14),
1373
+ e[0] + e[8] + e[2] + e[9], e[4] + e[10] + e[6] + e[11] + blocks * Math.log2(24),
1374
+ ];
1375
+ const best = entropy.indexOf(Math.min(...entropy));
1376
+ return { predict: best === 1 || best === 3, subtractGreen: best >= 2 };
1377
+ }
1180
1378
  async function applyPredictor(p, width, height, bits, threads) {
1181
1379
  const blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1182
1380
  const task = {
@@ -1283,7 +1481,8 @@ async function encodeWith(argb, width, height, colors, threads) {
1283
1481
  for (let i = 0; i < pixels.length && !redBlue; i++)
1284
1482
  if (pixels[i] & 0x00ff00ff)
1285
1483
  redBlue = true;
1286
- if (redBlue) {
1484
+ const { predict, subtractGreen } = analyze(argb, width, height, 4);
1485
+ if (redBlue && subtractGreen) {
1287
1486
  w.write(1, 1);
1288
1487
  w.write(2, 2);
1289
1488
  for (let i = 0; i < pixels.length; i++) {
@@ -1292,11 +1491,25 @@ async function encodeWith(argb, width, height, colors, threads) {
1292
1491
  }
1293
1492
  }
1294
1493
  const bits = 4;
1295
- w.write(1, 1);
1296
- w.write(0, 2);
1297
- w.write(bits - 2, 3);
1298
- const modes = await applyPredictor(pixels, width, height, bits, threads);
1299
- await writeImage(w, modes, subSize(width, bits), false);
1494
+ if (predict) {
1495
+ w.write(1, 1);
1496
+ w.write(0, 2);
1497
+ w.write(bits - 2, 3);
1498
+ const modes = await applyPredictor(pixels, width, height, bits, threads);
1499
+ await writeImage(w, modes, subSize(width, bits), false);
1500
+ if (redBlue) {
1501
+ const colorBits = 5, before = pixels.slice(), multipliers = colorTransform(pixels, width, height, colorBits);
1502
+ const changed = multipliers.reduce((n, m) => n + (m !== 0xff000000 ? 1 : 0), 0);
1503
+ if (changed && redBlueBits(pixels) + 12 * changed >= redBlueBits(before))
1504
+ pixels.set(before);
1505
+ else if (changed) {
1506
+ w.write(1, 1);
1507
+ w.write(1, 2);
1508
+ w.write(colorBits - 2, 3);
1509
+ await writeImage(w, multipliers, subSize(width, colorBits), false);
1510
+ }
1511
+ }
1512
+ }
1300
1513
  }
1301
1514
  w.write(0, 1);
1302
1515
  await writeImage(w, pixels, codedWidth, true, threads);
package/dist/image.d.ts CHANGED
@@ -148,11 +148,11 @@ export interface DecodeOptions {
148
148
  /** Whether to rotate/mirror JPEGs, TIFFs, PNGs and WebPs as their orientation tag (Exif or XMP) says. Default: `true` */
149
149
  applyOrientation?: boolean;
150
150
  /**
151
- * Whether to convert the colors of images with an embedded ICC profile (PNG, JPEG, WebP, AVIF, TIFF) to sRGB, like
152
- * browsers show them: wide gamut photos (Display P3 from phones, Adobe RGB, ProPhoto) look as intended instead of
153
- * washed out. Matrix/TRC profiles (RGB and gray) are applied, relative colorimetric (colors outside sRGB are
154
- * clipped); profiles with only lookup tables, CMYK ones and ones that are sRGB anyway leave the pixels as they are.
155
- * Default: `true`
151
+ * Whether to convert the colors of images with an embedded ICC profile (PNG, JPEG, WebP, AVIF, JPEG XL, TIFF), and
152
+ * of AVIFs with other color primaries than sRGB's (Display P3, BT.2020), to sRGB, like browsers show them: wide
153
+ * gamut photos (Display P3 from phones, Adobe RGB, ProPhoto) look as intended instead of washed out. Matrix/TRC
154
+ * profiles (RGB and gray) are applied, relative colorimetric (colors outside sRGB are clipped); profiles with only
155
+ * lookup tables, CMYK ones and ones that are sRGB anyway leave the pixels as they are. Default: `true`
156
156
  */
157
157
  applyColorProfile?: boolean;
158
158
  /**
@@ -238,6 +238,15 @@ export interface TextStyle {
238
238
  * `kern`), a number picks an alternate (`salt: 2`). Fonts without a feature ignore it. Default: `{}`
239
239
  */
240
240
  features?: Record<string, boolean | number>;
241
+ /**
242
+ * The instance of variable fonts, by their axes: `weight` (1-1000, like CSS's `font-weight`: 400 regular, 700
243
+ * bold), `width` (percent of the normal width: 75 condensed, 125 expanded), `slant` (degrees, negative leans
244
+ * right), `italic` (`true`/`false`), `opticalSize` (the size the glyphs are designed for, in pixels; default: the
245
+ * font size, like browsers' `font-optical-sizing: auto`), and other axes by their 4-character tag (like Roboto
246
+ * Flex's `GRAD: 50`). Values outside an axis's range are clamped, axes a font doesn't have are ignored, fonts
247
+ * without axes aren't affected. Default: `{}` (the fonts' default instances)
248
+ */
249
+ variations?: Record<string, number | boolean>;
241
250
  }
242
251
  /** Options of {@link Image.cropCircle} */
243
252
  export interface CropCircleOptions {
package/dist/image.js CHANGED
@@ -22,7 +22,7 @@ import * as quantize from "./codecs/quantize.js";
22
22
  import * as textRenderer from "./render/text.js";
23
23
  import * as svgRenderer from "./render/svg.js";
24
24
  import { view } from "./util/mem.js";
25
- import { profileTransform } from "./util/icc.js";
25
+ import { cicpTransform, profileTransform } from "./util/icc.js";
26
26
  import { ImageType } from "./image-type.js";
27
27
  import { TextLayout } from "./text-layout.js";
28
28
  import { resolveMetadata, pngText, exifData } from "./metadata.js";
@@ -1114,8 +1114,8 @@ export class Image {
1114
1114
  return tga.decode(data, maxPixels);
1115
1115
  throw new Error('Unsupported image type');
1116
1116
  });
1117
- if (applyColorProfile && decoded.icc)
1118
- profileTransform(decoded.icc)?.(decoded.pixels);
1117
+ if (applyColorProfile)
1118
+ (decoded.icc ? profileTransform(decoded.icc) : decoded.cicp ? cicpTransform(...decoded.cicp) : null)?.(decoded.pixels);
1119
1119
  const image = new Image(decoded.width, decoded.height);
1120
1120
  image.bitmap = decoded.pixels;
1121
1121
  return applyOrientation && decoded.orientation ? image.__orient__(decoded.orientation) : image;
@@ -1208,7 +1208,8 @@ export class Image {
1208
1208
  }
1209
1209
  static async renderText(font, size, text, colorOrOptions = 0xffffffff, layoutArgument, styleArgument = {}) {
1210
1210
  const options = isOptions(colorOrOptions) ? colorOrOptions : { ...styleArgument, color: colorOrOptions, layout: layoutArgument };
1211
- const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {} } = options;
1211
+ const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options;
1212
+ const axes = textRenderer.axisValues(variations);
1212
1213
  size = finite(size, 'font size');
1213
1214
  if (finite(strokeWidth, 'stroke width') < 0)
1214
1215
  throw new RangeError('Invalid stroke width');
@@ -1216,7 +1217,7 @@ export class Image {
1216
1217
  if (!fonts.length)
1217
1218
  throw new RangeError('No font given');
1218
1219
  const [r, g, b, a] = Image.colorToRGBA(color);
1219
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features));
1220
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes);
1220
1221
  const pad = Math.ceil(strokeWidth);
1221
1222
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1222
1223
  const coverage = new Uint8Array(width * height);
@@ -1,3 +1,4 @@
1
+ import { Gvar, ItemVariationStore, cvarDeltas, deltaSetIndexMap, normalize, parseAvar, parseFvar } from "./variations.js";
1
2
  const MAX_COMMANDS = 100000;
2
3
  export class Font {
3
4
  data;
@@ -16,6 +17,10 @@ export class Font {
16
17
  outlineCache;
17
18
  kernTable;
18
19
  variation;
20
+ axes;
21
+ coords = [];
22
+ variationTables = null;
23
+ instances = null;
19
24
  constructor(data) {
20
25
  this.data = data;
21
26
  this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
@@ -63,6 +68,62 @@ export class Font {
63
68
  this.outlineCache = new Map();
64
69
  this.kernTable = this.tables.kern && parseKern(this, this.tables.kern.offset) || null;
65
70
  this.variation = parseVariations(this, this.tables.cmap.offset);
71
+ this.axes = this.tables.fvar ? parseFvar(this, this.tables.fvar.offset) : [];
72
+ }
73
+ get vary() {
74
+ if (this.variationTables)
75
+ return this.variationTables;
76
+ const t = this.tables, at = (tag) => t[tag].offset;
77
+ const hvar = t.HVAR ? (() => {
78
+ const o = at('HVAR'), map = this.u32(o + 8);
79
+ return { store: new ItemVariationStore(this, o + this.u32(o + 4)), advances: map ? deltaSetIndexMap(this, o + map) : null };
80
+ })() : null;
81
+ const mvar = t.MVAR && this.u16(at('MVAR') + 10) ? (() => {
82
+ const o = at('MVAR'), size = this.u16(o + 6), count = this.u16(o + 8), records = new Map();
83
+ for (let i = 0; i < count; i++) {
84
+ const r = o + 12 + i * size;
85
+ records.set(String.fromCharCode(...this.data.subarray(r, r + 4)), [this.u16(r + 4), this.u16(r + 6)]);
86
+ }
87
+ return { store: new ItemVariationStore(this, o + this.u16(o + 10)), records };
88
+ })() : null;
89
+ const gdef = t.GDEF && this.u16(at('GDEF') + 2) >= 3 && this.u32(at('GDEF') + 14) ? new ItemVariationStore(this, at('GDEF') + this.u32(at('GDEF') + 14)) : null;
90
+ const base = Object.getPrototypeOf(this) instanceof Font ? Object.getPrototypeOf(this) : this;
91
+ base.variationTables = {
92
+ avar: t.avar ? parseAvar(this, at('avar'), this.axes.length) : null,
93
+ gvar: t.gvar && this.outlines === 'glyf' ? new Gvar(this, at('gvar')) : null,
94
+ hvar, mvar, gdef,
95
+ };
96
+ return base.variationTables;
97
+ }
98
+ withVariations(values) {
99
+ if (!this.axes.length)
100
+ return this;
101
+ const coords = normalize(this.axes, this.vary.avar, values);
102
+ if (coords.every(c => c === 0))
103
+ return Object.getPrototypeOf(this) instanceof Font ? Object.getPrototypeOf(this) : this;
104
+ const base = Object.getPrototypeOf(this) instanceof Font ? Object.getPrototypeOf(this) : this;
105
+ const key = coords.join(',');
106
+ const cached = base.instances?.get(key);
107
+ if (cached)
108
+ return cached;
109
+ const instance = Object.create(base);
110
+ (base.instances ??= new Map()).set(key, instance);
111
+ instance.coords = coords;
112
+ instance.outlineCache = new Map();
113
+ const metric = (tag, value) => {
114
+ const item = this.vary.mvar?.records.get(tag);
115
+ return item ? value + this.vary.mvar.store.delta(coords, item[0], item[1]) : value;
116
+ };
117
+ instance.ascender = metric('hasc', base.ascender);
118
+ instance.descender = metric('hdsc', base.descender);
119
+ instance.lineGap = metric('hlgn', base.lineGap);
120
+ return instance;
121
+ }
122
+ variationDelta(outer, inner) {
123
+ return this.coords.length && this.vary.gdef ? this.vary.gdef.delta(this.coords, outer, inner) : 0;
124
+ }
125
+ cvtDeltas(count) {
126
+ return this.coords.length && this.tables.cvar ? cvarDeltas(this, this.tables.cvar.offset, this.axes.length, this.coords, count) : null;
66
127
  }
67
128
  u8(o) { return this.data[o]; }
68
129
  i8(o) { return this.view.getInt8(o); }
@@ -76,14 +137,45 @@ export class Font {
76
137
  advance(glyph) {
77
138
  const hmtx = this.tables.hmtx.offset;
78
139
  const index = Math.min(glyph, this.numberOfHMetrics - 1);
79
- return this.u16(hmtx + index * 4);
140
+ const advance = this.u16(hmtx + index * 4);
141
+ if (!this.coords.length)
142
+ return advance;
143
+ const hvar = this.vary.hvar;
144
+ if (hvar) {
145
+ const [outer, inner] = hvar.advances ? hvar.advances(glyph) : [0, glyph];
146
+ return advance + hvar.store.delta(this.coords, outer, inner);
147
+ }
148
+ const phantom = this.phantomDeltas(glyph);
149
+ return phantom ? advance + phantom[2] - phantom[0] : advance;
150
+ }
151
+ phantomDeltas(glyph) {
152
+ const varied = this.varied(glyph);
153
+ return varied && varied.deltas && varied.deltas.subarray(2 * varied.count);
154
+ }
155
+ varied(glyph) {
156
+ if (this.outlines !== 'glyf' || glyph >= this.numGlyphs)
157
+ return null;
158
+ const offset = this.glyfOffset(glyph);
159
+ const gvar = this.coords.length ? this.vary.gvar : null;
160
+ if (offset < 0)
161
+ return { count: 0, deltas: gvar ? gvar.deltas(glyph, this.coords, 4, null, [], []) : null, simple: null };
162
+ const contours = this.i16(offset);
163
+ if (contours < 0) {
164
+ const count = this.components(offset).components.length;
165
+ return { count, deltas: gvar ? gvar.deltas(glyph, this.coords, count + 4, null, [], []) : null, simple: null };
166
+ }
167
+ const simple = this.simplePoints(offset, contours);
168
+ if (!simple)
169
+ return null;
170
+ const count = simple.xs.length;
171
+ return { count, deltas: gvar ? gvar.deltas(glyph, this.coords, count + 4, simple.ends, simple.xs, simple.ys) : null, simple };
80
172
  }
81
173
  variationGlyph(codepoint, selector) {
82
174
  const glyph = this.variation ? this.variation(codepoint, selector) : 0;
83
175
  return glyph < 0 ? this.glyphIndex(codepoint) : glyph;
84
176
  }
85
177
  extents(glyph) {
86
- if (this.outlines === 'glyf' && glyph < this.numGlyphs) {
178
+ if (this.outlines === 'glyf' && glyph < this.numGlyphs && !this.coords.length) {
87
179
  const o = this.glyfOffset(glyph);
88
180
  if (o < 0)
89
181
  return { xMin: 0, yMin: 0, xMax: 0, yMax: 0 };
@@ -114,13 +206,16 @@ export class Font {
114
206
  return null;
115
207
  const contourCount = this.i16(offset);
116
208
  const xMin = this.i16(offset + 2);
209
+ const varied = this.coords.length ? this.varied(glyph) : null, d = varied?.deltas;
210
+ const at = (i, axis) => d ? Math.round(d[2 * i + axis]) : 0;
211
+ const origin = d && varied ? at(varied.count, 0) : 0;
117
212
  if (contourCount < 0) {
118
213
  const { components, end } = this.components(offset);
119
214
  const instructions = components[components.length - 1].flags & 0x100 ? this.data.subarray(end + 2, end + 2 + this.u16(end)) : new Uint8Array(0);
120
215
  return {
121
- xs: [], ys: [], on: [], ends: [], instructions, xMin,
122
- components: components.map(({ glyph, flags, arg1, arg2, matrix }) => ({
123
- glyph, dx: flags & 2 ? arg1 : 0, dy: flags & 2 ? arg2 : 0, matrix,
216
+ xs: [], ys: [], on: [], ends: [], instructions, xMin: xMin + origin,
217
+ components: components.map(({ glyph, flags, arg1, arg2, matrix }, i) => ({
218
+ glyph, dx: flags & 2 ? arg1 + at(i, 0) : 0, dy: flags & 2 ? arg2 + at(i, 1) : 0, matrix,
124
219
  round: (flags & 4) !== 0, match: flags & 2 ? null : [arg1, arg2], useMetrics: (flags & 0x200) !== 0,
125
220
  })),
126
221
  };
@@ -129,7 +224,10 @@ export class Font {
129
224
  if (!points)
130
225
  return null;
131
226
  const { xs, ys, flags, ends, instructions } = points;
132
- return { xs: Array.from(xs), ys: Array.from(ys), on: Array.from(flags, f => (f & 1) === 1), ends, instructions, xMin, components: null };
227
+ return {
228
+ xs: Array.from(xs, (x, i) => x + at(i, 0)), ys: Array.from(ys, (y, i) => y + at(i, 1)), on: Array.from(flags, f => (f & 1) === 1), ends,
229
+ instructions, xMin: xMin + origin, components: null,
230
+ };
133
231
  }
134
232
  glyfOffset(glyph) {
135
233
  const loca = this.tables.loca.offset;
@@ -231,31 +329,38 @@ export class Font {
231
329
  return [];
232
330
  const contours = this.i16(offset);
233
331
  if (contours >= 0) {
234
- const path = this.simpleGlyph(offset, contours);
332
+ const path = this.simpleGlyph(offset, contours, glyph);
235
333
  expanding.budget -= path.length;
236
334
  return expanding.budget >= 0 ? path : [];
237
335
  }
238
336
  expanding.expanding.add(glyph);
239
- const path = this.compositeGlyph(offset, expanding);
337
+ const path = this.compositeGlyph(offset, expanding, glyph);
240
338
  expanding.expanding.delete(glyph);
241
339
  return path;
242
340
  }
243
- simpleGlyph(offset, contourCount) {
341
+ simpleGlyph(offset, contourCount, glyph) {
244
342
  const points = this.simplePoints(offset, contourCount);
245
343
  if (!points)
246
344
  return [];
345
+ let xs = points.xs, ys = points.ys;
346
+ const d = this.coords.length ? this.varied(glyph)?.deltas : null;
347
+ if (d) {
348
+ xs = Float64Array.from(points.xs, (x, i) => x + d[2 * i]);
349
+ ys = Float64Array.from(points.ys, (y, i) => y + d[2 * i + 1]);
350
+ }
247
351
  const path = [];
248
352
  let first = 0;
249
353
  for (const last of points.ends) {
250
- contourToPath(path, points.xs, points.ys, points.flags, first, last);
354
+ contourToPath(path, xs, ys, points.flags, first, last);
251
355
  first = last + 1;
252
356
  }
253
357
  return path;
254
358
  }
255
- compositeGlyph(offset, expanding) {
359
+ compositeGlyph(offset, expanding, composite) {
256
360
  const path = [];
257
- for (const { glyph, flags, arg1, arg2, matrix: [a, b, c, d] } of this.components(offset).components) {
258
- const dx = flags & 2 ? arg1 : 0, dy = flags & 2 ? arg2 : 0;
361
+ const deltas = this.coords.length ? this.varied(composite)?.deltas : null;
362
+ for (const [k, { glyph, flags, arg1, arg2, matrix: [a, b, c, d] }] of this.components(offset).components.entries()) {
363
+ const dx = flags & 2 ? arg1 + (deltas ? deltas[2 * k] : 0) : 0, dy = flags & 2 ? arg2 + (deltas ? deltas[2 * k + 1] : 0) : 0;
259
364
  for (const command of this.glyfOutline(glyph, expanding)) {
260
365
  const transformed = [command[0]];
261
366
  for (let i = 1; i < command.length; i += 2) {
@@ -111,6 +111,10 @@ export class Hinter {
111
111
  this.cvt = new Int16Array(cvt.length >> 1);
112
112
  for (let i = 0; i < this.cvt.length; i++)
113
113
  this.cvt[i] = font.i16(font.tables['cvt '].offset + i * 2);
114
+ const deltas = font.cvtDeltas(this.cvt.length);
115
+ if (deltas)
116
+ for (let i = 0; i < this.cvt.length; i++)
117
+ this.cvt[i] = Math.round(this.cvt[i] + deltas[i]);
114
118
  const maxp = font.tables.maxp.offset;
115
119
  const version = font.u32(maxp);
116
120
  this.maxTwilight = version >= 0x10000 ? font.u16(maxp + 16) : 0;