imagescript 3.7.0 → 3.8.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.d.ts CHANGED
@@ -79,6 +79,13 @@ export interface WebPEncodeOptions {
79
79
  * quantized values. Default: `2`: about a quarter of the time of 4 (cwebp's default) for files about 5% larger
80
80
  */
81
81
  effort?: number;
82
+ /**
83
+ * For lossy compression: convert to YUV like libwebp's sharp conversion (cwebp's `-sharp_yuv`, the same file),
84
+ * which picks the color planes so that colored edges (red text on blue, thin colored lines) stay sharp instead of
85
+ * bleeding. It takes about twice the time at the default effort; photos get about as large, images with many
86
+ * hard color edges a lot larger (1200x800 red and blue squares: 2.7 times). Default: `false`
87
+ */
88
+ sharpYuv?: boolean;
82
89
  /** Metadata to include, see {@link Metadata} */
83
90
  metadata?: Metadata;
84
91
  }
@@ -172,6 +179,12 @@ export interface TextStyle {
172
179
  * pixels. Fonts without instructions (and CFF/OpenType outlines) aren't affected. Default: `true`
173
180
  */
174
181
  hinting?: boolean;
182
+ /**
183
+ * OpenType features by their tags, for the whole text: `true` turns one on (like `tnum` for tabular numbers,
184
+ * `smcp` for small caps, `ss01` for a stylistic set), `false` off (also the ones on by default, like `liga` or
185
+ * `kern`), a number picks an alternate (`salt: 2`). Fonts without a feature ignore it. Default: `{}`
186
+ */
187
+ features?: Record<string, boolean | number>;
175
188
  }
176
189
  /** Options of {@link Image.cropCircle} */
177
190
  export interface CropCircleOptions {
@@ -463,6 +476,16 @@ export declare class Image {
463
476
  * @param height The new images height
464
477
  */
465
478
  crop(x: number, y: number, width: number, height: number): this;
479
+ /**
480
+ * Copies a region of the image into a new image, this one stays unchanged (like {@link Image.crop} on a clone,
481
+ * without copying the whole image). The region is clipped to the image, so the result can be smaller than the
482
+ * requested size
483
+ * @param x The x offset (0-based)
484
+ * @param y The y offset (0-based)
485
+ * @param width The region's width
486
+ * @param height The region's height
487
+ */
488
+ region(x: number, y: number, width: number, height: number): Image;
466
489
  /**
467
490
  * Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background.
468
491
  * Frames keep their position: their offsets move by the trimmed amount. An image that only has the color stays
@@ -767,7 +790,7 @@ export declare class Image {
767
790
  * quality
768
791
  * @param options See {@link WebPEncodeOptions}
769
792
  */
770
- encodeWebP({ quality, effort, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
793
+ encodeWebP({ quality, effort, sharpYuv, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
771
794
  /**
772
795
  * Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)
773
796
  * @param options See {@link EncodeOptions}
@@ -826,8 +849,9 @@ export declare class Image {
826
849
  static get SVG_MODE_HEIGHT(): 3;
827
850
  /**
828
851
  * Creates a new image from the given SVG
829
- * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, strokes, clip paths, masks and opacity;
830
- * text, images, filters and patterns are not rendered
852
+ * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
853
+ * masks, opacity, filters (all primitives and the filter functions) and images embedded as data URIs (PNG, JPEG,
854
+ * GIF, WebP, SVG); text is not rendered
831
855
  * @param svg The SVG content
832
856
  * @param options See {@link SVGOptions}
833
857
  * @return The rendered SVG graphic
package/dist/image.js CHANGED
@@ -2,6 +2,7 @@ import * as png from "./codecs/png.js";
2
2
  import * as jpeg from "./codecs/jpeg.js";
3
3
  import * as tiff from "./codecs/tiff.js";
4
4
  import * as webp from "./codecs/webp.js";
5
+ import * as gif from "./codecs/gif.js";
5
6
  import * as tga from "./codecs/tga.js";
6
7
  import * as bmp from "./codecs/bmp.js";
7
8
  import * as ico from "./codecs/ico.js";
@@ -24,6 +25,19 @@ import { rotateBilinear } from "./util/rotate.js";
24
25
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
25
26
  import { isOptions, finite, color as checkColor } from "./util/options.js";
26
27
  import { MAX_PIXELS, decoding } from "./util/limits.js";
28
+ function featureList(features) {
29
+ if (typeof features !== 'object' || features === null)
30
+ throw new TypeError('Features must be an object');
31
+ return Object.entries(features).map(([tag, value]) => {
32
+ if (!/^[\x20-\x7e]{4}$/.test(tag))
33
+ throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`);
34
+ if (typeof value === 'boolean')
35
+ return [tag, value ? 1 : 0];
36
+ if (!Number.isInteger(value) || value < 0 || value > 255)
37
+ throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`);
38
+ return [tag, value];
39
+ });
40
+ }
27
41
  export class Image {
28
42
  __width__;
29
43
  __height__;
@@ -301,6 +315,12 @@ export class Image {
301
315
  return image;
302
316
  }
303
317
  crop(x, y, width, height) {
318
+ return this.__apply__(this.__crop__(...this.__crop_bounds__(x, y, width, height)));
319
+ }
320
+ region(x, y, width, height) {
321
+ return this.__crop__(...this.__crop_bounds__(x, y, width, height));
322
+ }
323
+ __crop_bounds__(x, y, width, height) {
304
324
  x = ~~finite(x, 'x');
305
325
  y = ~~finite(y, 'y');
306
326
  width = ~~finite(width, 'width');
@@ -309,7 +329,7 @@ export class Image {
309
329
  const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
310
330
  if (right <= left || bottom <= top)
311
331
  throw new RangeError('Crop region does not overlap the image');
312
- return this.__apply__(this.__crop__(left, top, right - left, bottom - top));
332
+ return [left, top, right - left, bottom - top];
313
333
  }
314
334
  trim(color, options = {}) {
315
335
  const bounds = this.__trim_bounds__(color, options);
@@ -510,26 +530,27 @@ export class Image {
510
530
  const blend = BLEND_MODES[mode];
511
531
  if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
512
532
  throw new RangeError(`Invalid blend mode: ${mode}`);
513
- if (opacity !== 1 || mode !== 'normal')
533
+ if (mode !== 'normal')
514
534
  return this.__blend__(source, x, y, opacity, blend);
535
+ if (opacity === 0)
536
+ return this;
515
537
  const left = Math.max(0, x), top = Math.max(0, y);
516
538
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
517
539
  const dst = this.bitmap, src = source.bitmap;
518
- const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, dst.length >> 2);
519
- const src32 = new Uint32Array(src.buffer, src.byteOffset, src.length >> 2);
520
540
  for (let row = top; row < bottom; row++) {
521
- for (let column = left; column < right; column++) {
522
- const sp = (row - y) * source.width + column - x, s = 4 * sp;
541
+ 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) {
523
542
  const sa = src[s + 3];
524
543
  if (sa === 0)
525
544
  continue;
526
- const dp = row * this.width + column, d = 4 * dp;
527
545
  const da = dst[d + 3];
528
- if (sa === 255 || da === 0) {
529
- dst32[dp] = src32[sp];
546
+ if ((sa === 255 && opacity === 1) || da === 0) {
547
+ dst[d] = src[s];
548
+ dst[d + 1] = src[s + 1];
549
+ dst[d + 2] = src[s + 2];
550
+ dst[d + 3] = sa * opacity;
530
551
  continue;
531
552
  }
532
- const fa = sa / 255, ba = da / 255 * (1 - fa);
553
+ const fa = sa / 255 * opacity, ba = da / 255 * (1 - fa);
533
554
  const a = fa + ba;
534
555
  dst[d] = (src[s] * fa + dst[d] * ba) / a;
535
556
  dst[d + 1] = (src[s + 1] * fa + dst[d + 1] * ba) / a;
@@ -1004,7 +1025,7 @@ export class Image {
1004
1025
  const m = resolveMetadata(metadata);
1005
1026
  return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1006
1027
  }
1007
- async encodeWebP({ quality, effort = 2, metadata = {} } = {}) {
1028
+ async encodeWebP({ quality, effort = 2, sharpYuv = false, metadata = {} } = {}) {
1008
1029
  const exif = exifData(resolveMetadata(metadata));
1009
1030
  if (quality === undefined)
1010
1031
  return webp.encode(this.__bytes__(), this.width, this.height, exif);
@@ -1013,7 +1034,7 @@ export class Image {
1013
1034
  throw new RangeError(`quality must be 0-100, not ${q}`);
1014
1035
  if (!Number.isInteger(effort) || effort < 0 || effort > 6)
1015
1036
  throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
1016
- return webp.encodeLossy(this.__bytes__(), this.width, this.height, q, exif, effort);
1037
+ return webp.encodeLossy(this.__bytes__(), this.width, this.height, q, exif, effort, sharpYuv);
1017
1038
  }
1018
1039
  async encodeTGA({ metadata = {} } = {}) {
1019
1040
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
@@ -1153,14 +1174,32 @@ export class Image {
1153
1174
  throw new RangeError('SVG scale must be > 0');
1154
1175
  if (mode !== Image.SVG_MODE_SCALE && size < 1)
1155
1176
  throw new RangeError('SVG size must be >= 1');
1156
- const { width, height, pixels } = svgRenderer.render(typeof svg === 'string' ? svg : view(svg), mode, size);
1177
+ const source = typeof svg === 'string' ? svg : view(svg);
1178
+ const images = new Map();
1179
+ for (const { href, data } of svgRenderer.embeddedImages(source)) {
1180
+ if (images.has(href))
1181
+ continue;
1182
+ try {
1183
+ if (ImageType.getType(data) === 'gif') {
1184
+ const decoded = gif.decode(data, true);
1185
+ images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1186
+ }
1187
+ else {
1188
+ const image = await Image.decode(data);
1189
+ images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1190
+ }
1191
+ }
1192
+ catch {
1193
+ }
1194
+ }
1195
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images);
1157
1196
  const image = new Image(width, height);
1158
1197
  image.bitmap.set(pixels);
1159
1198
  return image;
1160
1199
  }
1161
1200
  static async renderText(font, size, text, colorOrOptions = 0xffffffff, layoutArgument, styleArgument = {}) {
1162
1201
  const options = isOptions(colorOrOptions) ? colorOrOptions : { ...styleArgument, color: colorOrOptions, layout: layoutArgument };
1163
- const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true } = options;
1202
+ const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {} } = options;
1164
1203
  size = finite(size, 'font size');
1165
1204
  if (finite(strokeWidth, 'stroke width') < 0)
1166
1205
  throw new RangeError('Invalid stroke width');
@@ -1168,7 +1207,7 @@ export class Image {
1168
1207
  if (!fonts.length)
1169
1208
  throw new RangeError('No font given');
1170
1209
  const [r, g, b, a] = Image.colorToRGBA(color);
1171
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0);
1210
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features));
1172
1211
  const pad = Math.ceil(strokeWidth);
1173
1212
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1174
1213
  const coverage = new Uint8Array(width * height);
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export type { FrameDisposalModeName, FrameDisposalModeId, FrameOptions } from '.
9
9
  export { GIF } from './gif.js';
10
10
  export { Animation } from './animation.js';
11
11
  export type { AnimationOptions, AnimationDecodeOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.js';
12
+ export { AnimationEncoder } from './animation-encoder.js';
13
+ export type { AnimationEncoderOptions, WebPAnimationEncoderOptions, GIFAnimationEncoderOptions, APNGAnimationEncoderOptions } from './animation-encoder.js';
12
14
  export { TextLayout } from './text-layout.js';
13
15
  export type { TextLayoutOptions, WrapStyle, HorizontalAlign, VerticalAlign } from './text-layout.js';
14
16
  export { ImageType } from './image-type.js';
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ export { Image } from "./image.js";
9
9
  export { Frame } from "./frame.js";
10
10
  export { GIF } from "./gif.js";
11
11
  export { Animation } from "./animation.js";
12
+ export { AnimationEncoder } from "./animation-encoder.js";
12
13
  export { TextLayout } from "./text-layout.js";
13
14
  export { ImageType } from "./image-type.js";
14
15
  export function decode(data, onlyFirstFrameOrOptions = false) {