smallpeg 0.13.1 → 0.14.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/README.md CHANGED
@@ -1,71 +1,84 @@
1
1
  # smallpeg
2
2
 
3
- A JPEG encoder, lossless optimizer and decoder written from the JPEG
4
- standard in Rust, compiled to WebAssembly for Node and the browser. No
5
- dependencies and no native binaries: the package is JavaScript glue plus
6
- one `.wasm` file of about 190 KB.
7
-
8
- - **Encode** gray, RGB or RGBA pixels (for example from a canvas) with
9
- trellis quantization, per-image Huffman tables and optimized progressive
10
- scans.
11
- - **Optimize** an existing JPEG without changing a pixel.
12
- - **Strip metadata** such as EXIF and GPS position, keeping the color
13
- profile and orientation.
14
- - **Decode**, read the header, fix EXIF orientation, crop and resize
15
- (Lanczos3, optionally in linear light).
3
+ [![npm](https://img.shields.io/npm/v/smallpeg.svg)](https://www.npmjs.com/package/smallpeg)
4
+ [![CI](https://github.com/sawapi/smallpeg/actions/workflows/ci.yml/badge.svg)](https://github.com/sawapi/smallpeg/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/smallpeg.svg)](#license)
6
+
7
+ A JPEG encoder, lossless optimizer and decoder for Node and the browser,
8
+ compiled to WebAssembly from a dependency-free Rust library, with
9
+ TypeScript types.
10
+
11
+ [Website](https://sawapi.github.io/smallpeg/) ·
12
+ [API](https://github.com/sawapi/smallpeg/blob/main/docs/npm-api.md) ·
13
+ [GitHub](https://github.com/sawapi/smallpeg) ·
14
+ [Changelog](https://github.com/sawapi/smallpeg/blob/main/CHANGELOG.md)
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install smallpeg
20
+ ```
16
21
 
17
22
  ## Node
18
23
 
19
24
  ```js
20
- import { encode, optimize, stripMetadata } from "smallpeg";
25
+ import { encode, optimize } from "smallpeg";
21
26
  import { readFileSync, writeFileSync } from "node:fs";
22
27
 
23
- // rgb: width * height * 3 bytes
24
- const jpeg = encode(rgb, width, height, 3, 80);
28
+ // data: width * height * channels bytes (1 gray, 3 RGB, 4 RGBA)
29
+ const jpeg = encode({ data: rgb, width, height }, { quality: 80 });
25
30
 
26
- // same pixels, fewer bytes (compare lengths: an optimized file may not shrink)
31
+ // Same pixels, fewer bytes (an already optimized file may not shrink).
27
32
  const input = readFileSync("photo.jpg");
28
33
  const smaller = optimize(input);
29
34
  if (smaller && smaller.length < input.length) writeFileSync("photo.jpg", smaller);
30
-
31
- // remove EXIF, GPS and XMP
32
- const clean = stripMetadata(input);
33
35
  ```
34
36
 
35
- ## Browser and bundlers
36
-
37
- The browser build has to load its `.wasm` before use:
37
+ ## Browser
38
38
 
39
39
  ```js
40
- import init, { encode } from "smallpeg/web";
40
+ import { init, encode } from "smallpeg/web";
41
41
 
42
- await init(); // fetches smallpeg_wasm_bg.wasm next to the module
43
- const { data, width, height } = ctx.getImageData(0, 0, w, h);
44
- const jpeg = encode(data, width, height, 4, 80); // RGBA, alpha onto white
42
+ await init(); // loads the .wasm file once
43
+ const jpeg = encode(ctx.getImageData(0, 0, w, h)); // RGBA, alpha onto white
45
44
  const blob = new Blob([jpeg], { type: "image/jpeg" });
46
45
  ```
47
46
 
48
- Run it in a Web Worker for large images: encoding is synchronous.
47
+ Encoding is synchronous; for large images, run it in a Web Worker.
49
48
 
50
- ## API
49
+ ## Features
50
+
51
+ - **Encode** gray, RGB or RGBA pixels, such as a canvas `ImageData`.
52
+ - **Optimize** an existing JPEG losslessly: same pixels, fewer bytes.
53
+ - **Strip metadata** such as EXIF and GPS position, keeping the color
54
+ profile and orientation.
55
+ - **Decode**, read the header, fix EXIF orientation, crop and resize.
56
+ - **Handle untrusted input**: functions that read JPEG bytes return
57
+ `undefined` for anything they cannot handle.
51
58
 
52
59
  | Function | Returns |
53
60
  |---|---|
54
- | `encode(pixels, width, height, channels, quality = 80, fullColor = false)` | JPEG bytes. `channels` is 1, 3 or 4 (RGBA). `fullColor` keeps chroma at full resolution (4:4:4) |
55
- | `optimize(jpeg, baseline = false)` | Re-coded JPEG with identical pixels, or `undefined` if the file cannot be re-coded |
61
+ | `encode(image, { quality, fullColor })` | JPEG bytes |
62
+ | `optimize(jpeg, { baseline })` | Re-coded JPEG with identical pixels, or `undefined` |
56
63
  | `stripMetadata(jpeg)` | JPEG without metadata, or `undefined` |
57
64
  | `info(jpeg)` | `{ width, height, components, progressive, orientation }`, or `undefined` |
58
- | `decode(jpeg)` | `{ width, height, channels, pixels }` (gray or RGB, as stored), or `undefined` |
59
- | `applyOrientation(pixels, width, height, channels, orientation)` | Upright `{ width, height, channels, pixels }` |
60
- | `resize(pixels, width, height, channels, newWidth, newHeight, linear = false)` | Resized pixels |
61
- | `crop(pixels, width, height, channels, x, y, cropWidth, cropHeight)` | Cropped pixels, or `undefined` if the rectangle is not inside the image |
62
- | `fitWithin(width, height, maxWidth, maxHeight)` | `[width, height]` that fits, keeping the aspect ratio; never enlarges |
65
+ | `decode(jpeg)` | Image (gray or RGB), or `undefined` |
66
+ | `applyOrientation(image, orientation)` | Upright image |
67
+ | `resize(image, width, height, { linear })` | Resized image |
68
+ | `crop(image, { x, y, width, height })` | Cropped image, or `undefined` |
69
+ | `fitWithin(width, height, maxWidth, maxHeight)` | `[width, height]` that fits |
70
+ | `init(wasm?)`, `initSync(bytes)` | Load the WebAssembly module (browser build; no-ops in Node) |
71
+
72
+ Images are plain `{ data, width, height, channels }` objects, and every
73
+ image a function returns can be passed to the next. Details, options and
74
+ errors are in the [API documentation](https://github.com/sawapi/smallpeg/blob/main/docs/npm-api.md).
75
+
76
+ ## Requirements
63
77
 
64
- Functions that read JPEG bytes accept untrusted input and return
65
- `undefined` for anything they cannot handle. A pixel buffer whose length
66
- does not match its dimensions throws an `Error`.
78
+ Node 22.12 or later, or a current browser (directly or through a bundler).
79
+ TypeScript types need TypeScript 5.7 or later.
67
80
 
68
81
  ## License
69
82
 
70
- MIT OR Apache-2.0, at your option. The Rust crate is
71
- [`smallpeg`](https://crates.io/crates/smallpeg).
83
+ MIT OR Apache-2.0, at your option. The Rust library is
84
+ [`smallpeg` on crates.io](https://crates.io/crates/smallpeg).
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Bytes this package hands back. They are always fresh copies backed by a
3
+ * plain `ArrayBuffer`, so they work as a `BlobPart`, and 4-channel pixels
4
+ * can be viewed as the `Uint8ClampedArray` that `new ImageData` takes.
5
+ */
6
+ export type Bytes = Uint8Array<ArrayBuffer>;
7
+ /** 1 (gray), 3 (RGB) or 4 (RGBA, or any four-channel layout). */
8
+ export type Channels = 1 | 3 | 4;
9
+ /**
10
+ * Pixels to encode, resize, crop or turn: `width * height * channels`
11
+ * bytes, interleaved, top row first. A canvas `ImageData` fits as is.
12
+ */
13
+ export interface ImageInput {
14
+ data: Uint8Array | Uint8ClampedArray;
15
+ width: number;
16
+ height: number;
17
+ /** Worked out from the length of `data` when left out. */
18
+ channels?: Channels | undefined;
19
+ }
20
+ /** Pixels returned by `decode`, `resize`, `crop` and `applyOrientation`. */
21
+ export interface Image {
22
+ data: Bytes;
23
+ width: number;
24
+ height: number;
25
+ channels: Channels;
26
+ }
27
+ /** Options for `encode`. Every field is optional. */
28
+ export interface EncodeOptions {
29
+ /** An integer from 1 to 100. Default 80. */
30
+ quality?: number | undefined;
31
+ /**
32
+ * Keep chroma at full resolution (4:4:4) instead of halving it (4:2:0):
33
+ * sharper colored text and lines, larger files. Default false.
34
+ */
35
+ fullColor?: boolean | undefined;
36
+ }
37
+ /** Options for `optimize`. */
38
+ export interface OptimizeOptions {
39
+ /**
40
+ * Write baseline sequential output instead of progressive, for targets
41
+ * that dislike progressive JPEGs (PDF embedding, for example).
42
+ * Default false.
43
+ */
44
+ baseline?: boolean | undefined;
45
+ }
46
+ /** Options for `resize`. */
47
+ export interface ResizeOptions {
48
+ /**
49
+ * Filter in linear light, which keeps fine light-and-dark detail from
50
+ * darkening when reducing. Assumes sRGB; 1 or 3 channels only.
51
+ * Default false.
52
+ */
53
+ linear?: boolean | undefined;
54
+ }
55
+ /** A rectangle in pixels; `x` and `y` are its top-left corner. */
56
+ export interface Rect {
57
+ x: number;
58
+ y: number;
59
+ width: number;
60
+ height: number;
61
+ }
62
+ /** EXIF orientation: 1 is upright; 5 to 8 swap width and height. */
63
+ export type Orientation = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
64
+ /** Frame-header facts about a JPEG, returned by `info`. */
65
+ export interface JpegInfo {
66
+ width: number;
67
+ height: number;
68
+ /** 1 (gray), 3 (color) or 4 (CMYK / YCCK); 2 in rare files. */
69
+ components: 1 | 2 | 3 | 4;
70
+ /** True for progressive files. */
71
+ progressive: boolean;
72
+ /** EXIF orientation, 1 to 8 (1 when the file has none). */
73
+ orientation: Orientation;
74
+ }
75
+ interface Freeable {
76
+ free(): void;
77
+ }
78
+ interface GlueImage extends Freeable {
79
+ readonly width: number;
80
+ readonly height: number;
81
+ readonly channels: number;
82
+ take_pixels(): Uint8Array;
83
+ }
84
+ interface GlueInfo extends Freeable {
85
+ readonly width: number;
86
+ readonly height: number;
87
+ readonly components: number;
88
+ readonly progressive: boolean;
89
+ readonly orientation: number;
90
+ }
91
+ export interface Bindings {
92
+ encode: (pixels: Uint8Array, width: number, height: number, channels: number, quality?: number | null, full_color?: boolean | null) => Uint8Array;
93
+ optimize: (jpeg: Uint8Array, baseline: boolean) => Uint8Array | undefined;
94
+ strip_metadata: (jpeg: Uint8Array) => Uint8Array | undefined;
95
+ info: (jpeg: Uint8Array) => GlueInfo | undefined;
96
+ decode: (jpeg: Uint8Array) => GlueImage | undefined;
97
+ apply_orientation: (pixels: Uint8Array, width: number, height: number, channels: number, orientation: number) => GlueImage;
98
+ resize: (pixels: Uint8Array, width: number, height: number, channels: number, new_width: number, new_height: number, linear: boolean) => Uint8Array;
99
+ crop: (pixels: Uint8Array, width: number, height: number, channels: number, x: number, y: number, crop_width: number, crop_height: number) => Uint8Array | undefined;
100
+ fit_within: (width: number, height: number, max_width: number, max_height: number) => Uint32Array;
101
+ }
102
+ type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
103
+ /**
104
+ * For each glue function, whether its parameter list is exactly the one in
105
+ * `Bindings` (both directions, so a parameter the glue gained, lost or
106
+ * changed shows up). The entry points assert it is all `true`.
107
+ */
108
+ export type ParamsMatch<G extends Pick<Bindings, keyof Bindings>> = {
109
+ [K in keyof Bindings]: Same<Parameters<G[K]>, Parameters<Bindings[K]>>;
110
+ };
111
+ /** The functions both entry points export. */
112
+ export interface Api {
113
+ encode(image: ImageInput, options?: EncodeOptions): Bytes;
114
+ optimize(jpeg: Uint8Array, options?: OptimizeOptions): Bytes | undefined;
115
+ stripMetadata(jpeg: Uint8Array): Bytes | undefined;
116
+ info(jpeg: Uint8Array): JpegInfo | undefined;
117
+ decode(jpeg: Uint8Array): Image | undefined;
118
+ applyOrientation(image: ImageInput, orientation: number): Image;
119
+ resize(image: ImageInput, width: number, height: number, options?: ResizeOptions): Image;
120
+ crop(image: ImageInput, rect: Rect): Image | undefined;
121
+ fitWithin(width: number, height: number, maxWidth: number, maxHeight: number): [width: number, height: number];
122
+ }
123
+ export declare function makeApi(glue: Bindings, ensureReady?: () => void): Api;
124
+ export {};
package/dist/core.mjs ADDED
@@ -0,0 +1,185 @@
1
+ // The typed API shared by the Node and browser entry points. The
2
+ // wasm-bindgen glue is an implementation detail: its result classes hold
3
+ // wasm memory, so they are copied into plain objects here and freed.
4
+ const MAX_U32 = 0xffff_ffff;
5
+ /** Largest resize output, the same 100 megapixels the decoder accepts. */
6
+ const MAX_PIXELS = 100_000_000;
7
+ /** A value for an error message: strings quoted, everything else as is. */
8
+ function show(v) {
9
+ if (typeof v === "string")
10
+ return JSON.stringify(v);
11
+ if (Array.isArray(v))
12
+ return "an array";
13
+ try {
14
+ return String(v);
15
+ }
16
+ catch {
17
+ return Object.prototype.toString.call(v); // e.g. a null-prototype object
18
+ }
19
+ }
20
+ /** Throws unless `v` is an integer in `min..=max`. */
21
+ function int(name, v, min, max = MAX_U32) {
22
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max) {
23
+ const msg = `smallpeg: ${name} must be an integer from ${min} to ${max}, got ${show(v)}`;
24
+ throw typeof v === "number" ? new RangeError(msg) : new TypeError(msg);
25
+ }
26
+ return v;
27
+ }
28
+ /** JPEG input: a `Uint8Array` (a Node `Buffer` is one). */
29
+ function jpegBytes(jpeg) {
30
+ if (!(jpeg instanceof Uint8Array)) {
31
+ throw new TypeError("smallpeg: the JPEG must be a Uint8Array (a Node Buffer is fine)");
32
+ }
33
+ return jpeg;
34
+ }
35
+ /** Pixel input: a `Uint8Array`, or a canvas's `Uint8ClampedArray`. */
36
+ function pixelBytes(data) {
37
+ if (data instanceof Uint8Array)
38
+ return data;
39
+ if (data instanceof Uint8ClampedArray) {
40
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
41
+ }
42
+ throw new TypeError("smallpeg: image data must be a Uint8Array or Uint8ClampedArray");
43
+ }
44
+ /** `options` as an object: `undefined` and `null` mean defaults. */
45
+ function opts(options) {
46
+ if (options === undefined || options === null)
47
+ return {};
48
+ if (typeof options !== "object" || Array.isArray(options)) {
49
+ throw new TypeError(`smallpeg: options must be an object, got ${show(options)}`);
50
+ }
51
+ return options;
52
+ }
53
+ /** A boolean option; left out means false. */
54
+ function flag(value, name) {
55
+ if (value === undefined)
56
+ return false;
57
+ if (typeof value !== "boolean") {
58
+ throw new TypeError(`smallpeg: ${name} must be a boolean, got ${show(value)}`);
59
+ }
60
+ return value;
61
+ }
62
+ /** The glue's byte results are copies out of WebAssembly memory. */
63
+ function owned(data) {
64
+ return data;
65
+ }
66
+ function channelsOf(image) {
67
+ if (image.channels !== undefined) {
68
+ const c = image.channels;
69
+ if (c === 1 || c === 3 || c === 4)
70
+ return c;
71
+ const msg = `smallpeg: channels must be 1, 3 or 4, got ${show(c)}`;
72
+ throw typeof c === "number" ? new RangeError(msg) : new TypeError(msg);
73
+ }
74
+ const area = Number.isInteger(image.width) && Number.isInteger(image.height) ? image.width * image.height : 0;
75
+ const c = area > 0 ? image.data.length / area : 0;
76
+ if (c === 1 || c === 3 || c === 4)
77
+ return c;
78
+ throw new RangeError(`smallpeg: ${image.data.length} bytes is not 1, 3 or 4 channels of ${image.width}x${image.height}`);
79
+ }
80
+ /** The image's fields, checked, in the order the glue takes them. */
81
+ function unpack(image) {
82
+ if (typeof image !== "object" || image === null) {
83
+ throw new TypeError("smallpeg: the image must be an object { data, width, height, channels? }");
84
+ }
85
+ const data = pixelBytes(image.data);
86
+ const width = int("width", image.width, 1);
87
+ const height = int("height", image.height, 1);
88
+ const channels = channelsOf(image);
89
+ if (data.length !== width * height * channels) {
90
+ throw new RangeError(`smallpeg: expected ${width * height * channels} bytes for ${width}x${height} with ${channels} channel(s), got ${data.length}`);
91
+ }
92
+ return [data, width, height, channels];
93
+ }
94
+ function take(img) {
95
+ try {
96
+ return {
97
+ data: owned(img.take_pixels()),
98
+ width: img.width,
99
+ height: img.height,
100
+ channels: img.channels,
101
+ };
102
+ }
103
+ finally {
104
+ img.free();
105
+ }
106
+ }
107
+ export function makeApi(glue, ensureReady = () => { }) {
108
+ function encode(image, options) {
109
+ ensureReady();
110
+ const args = unpack(image);
111
+ const o = opts(options);
112
+ const quality = o.quality === undefined ? undefined : int("quality", o.quality, 1, 100);
113
+ return owned(glue.encode(...args, quality, flag(o.fullColor, "fullColor")));
114
+ }
115
+ function optimize(jpeg, options) {
116
+ ensureReady();
117
+ const input = jpegBytes(jpeg);
118
+ const out = glue.optimize(input, flag(opts(options).baseline, "baseline"));
119
+ return out && owned(out);
120
+ }
121
+ function stripMetadata(jpeg) {
122
+ ensureReady();
123
+ const out = glue.strip_metadata(jpegBytes(jpeg));
124
+ return out && owned(out);
125
+ }
126
+ function info(jpeg) {
127
+ ensureReady();
128
+ const i = glue.info(jpegBytes(jpeg));
129
+ if (!i)
130
+ return undefined;
131
+ try {
132
+ return {
133
+ width: i.width,
134
+ height: i.height,
135
+ components: i.components,
136
+ progressive: i.progressive,
137
+ orientation: i.orientation,
138
+ };
139
+ }
140
+ finally {
141
+ i.free();
142
+ }
143
+ }
144
+ function decode(jpeg) {
145
+ ensureReady();
146
+ const img = glue.decode(jpegBytes(jpeg));
147
+ return img ? take(img) : undefined;
148
+ }
149
+ function applyOrientation(image, orientation) {
150
+ ensureReady();
151
+ if (typeof orientation !== "number") {
152
+ throw new TypeError(`smallpeg: orientation must be a number, got ${show(orientation)}`);
153
+ }
154
+ const o = Number.isInteger(orientation) && orientation >= 1 && orientation <= 8 ? orientation : 1;
155
+ return take(glue.apply_orientation(...unpack(image), o));
156
+ }
157
+ function resize(image, width, height, options) {
158
+ ensureReady();
159
+ const args = unpack(image);
160
+ const w = int("width", width, 1);
161
+ const h = int("height", height, 1);
162
+ if (w * h > MAX_PIXELS) {
163
+ throw new RangeError(`smallpeg: ${w}x${h} is over the ${MAX_PIXELS / 1e6} megapixel limit for resize`);
164
+ }
165
+ const data = glue.resize(...args, w, h, flag(opts(options).linear, "linear"));
166
+ return { data: owned(data), width: w, height: h, channels: args[3] };
167
+ }
168
+ function crop(image, rect) {
169
+ ensureReady();
170
+ const args = unpack(image);
171
+ if (typeof rect !== "object" || rect === null) {
172
+ throw new TypeError("smallpeg: the rectangle must be an object { x, y, width, height }");
173
+ }
174
+ const [x, y] = [int("x", rect.x, 0), int("y", rect.y, 0)];
175
+ const [w, h] = [int("width", rect.width, 0), int("height", rect.height, 0)];
176
+ const data = glue.crop(...args, x, y, w, h);
177
+ return data ? { data: owned(data), width: w, height: h, channels: args[3] } : undefined;
178
+ }
179
+ function fitWithin(width, height, maxWidth, maxHeight) {
180
+ ensureReady();
181
+ const [w, h] = glue.fit_within(int("width", width, 1), int("height", height, 1), int("maxWidth", maxWidth, 1), int("maxHeight", maxHeight, 1));
182
+ return [w, h];
183
+ }
184
+ return { encode, optimize, stripMetadata, info, decode, applyOrientation, resize, crop, fitWithin };
185
+ }
@@ -0,0 +1,73 @@
1
+ import { type Api } from "./core.mjs";
2
+ /** Does nothing in Node; present so code shared with the browser build can always `await init()`. */
3
+ export declare function init(_wasm?: unknown): Promise<void>;
4
+ /** Does nothing in Node; present so code shared with the browser build can call `initSync(bytes)`. */
5
+ export declare function initSync(_module?: unknown): void;
6
+ export default init;
7
+ export type { Bytes, Channels, EncodeOptions, Image, ImageInput, JpegInfo, OptimizeOptions, Orientation, Rect, ResizeOptions, } from "./core.mjs";
8
+ /**
9
+ * Encode pixels as a JPEG. 4 channels are RGBA: alpha is flattened onto
10
+ * white.
11
+ *
12
+ * @throws {RangeError} if the data length does not match the dimensions,
13
+ * or `quality` is not an integer from 1 to 100.
14
+ * @throws {TypeError} for arguments of the wrong kind.
15
+ * @throws {Error} if a dimension is above 65535.
16
+ */
17
+ export declare const encode: Api["encode"];
18
+ /**
19
+ * Make an existing JPEG smaller without changing a pixel. `undefined` if
20
+ * the file is not one this can re-code. An already optimized file can come
21
+ * out larger; compare lengths.
22
+ */
23
+ export declare const optimize: Api["optimize"];
24
+ /**
25
+ * Remove EXIF (including GPS), XMP, comments and other metadata without
26
+ * touching the image data. Keeps the color profile and orientation.
27
+ * `undefined` if the file cannot be parsed.
28
+ */
29
+ export declare const stripMetadata: Api["stripMetadata"];
30
+ /**
31
+ * Read a JPEG's frame header without decoding it. `undefined` if the bytes
32
+ * are not a JPEG this library understands.
33
+ */
34
+ export declare const info: Api["info"];
35
+ /**
36
+ * Decode a grayscale or color JPEG to 1-channel gray or 3-channel RGB
37
+ * pixels, as stored (see `applyOrientation`). `undefined` for CMYK files,
38
+ * codings this library does not decode, malformed input, or frames over
39
+ * 100 megapixels.
40
+ */
41
+ export declare const decode: Api["decode"];
42
+ /**
43
+ * Turn pixels upright for an EXIF orientation (`info(jpeg).orientation`).
44
+ * A number outside 1 to 8 leaves them as they are.
45
+ *
46
+ * @throws {RangeError} if the data length does not match the dimensions.
47
+ * @throws {TypeError} if `orientation` is not a number.
48
+ */
49
+ export declare const applyOrientation: Api["applyOrientation"];
50
+ /**
51
+ * Resize with a Lanczos3 filter. 4 channels are filtered independently.
52
+ *
53
+ * @throws {RangeError} if the data length does not match the dimensions,
54
+ * a new size is not an integer of at least 1, or the result would be over
55
+ * 100 megapixels.
56
+ * @throws {Error} if `linear` is set for 4 channels.
57
+ */
58
+ export declare const resize: Api["resize"];
59
+ /**
60
+ * Copy a rectangle out of an image. `undefined` if the rectangle is empty
61
+ * or not entirely inside the image.
62
+ *
63
+ * @throws {RangeError} if the data length does not match the dimensions,
64
+ * or a rectangle field is not a non-negative integer.
65
+ */
66
+ export declare const crop: Api["crop"];
67
+ /**
68
+ * The largest `[width, height]` that fits inside `maxWidth` x `maxHeight`
69
+ * with the same aspect ratio. Never enlarges.
70
+ *
71
+ * @throws {RangeError} if an argument is not an integer of at least 1.
72
+ */
73
+ export declare const fitWithin: Api["fitWithin"];
package/dist/node.mjs ADDED
@@ -0,0 +1,78 @@
1
+ // Node entry point: the wasm is loaded synchronously when this module is
2
+ // imported, so there is nothing to initialize. `init`, `initSync` and the
3
+ // default export mirror the browser build so code shared between the two
4
+ // runs unchanged; their arguments are ignored.
5
+ import * as glue from "../node/smallpeg_wasm.js";
6
+ import { makeApi } from "./core.mjs";
7
+ const api = makeApi(glue);
8
+ /** Does nothing in Node; present so code shared with the browser build can always `await init()`. */
9
+ export async function init(_wasm) { }
10
+ /** Does nothing in Node; present so code shared with the browser build can call `initSync(bytes)`. */
11
+ export function initSync(_module) { }
12
+ export default init;
13
+ /**
14
+ * Encode pixels as a JPEG. 4 channels are RGBA: alpha is flattened onto
15
+ * white.
16
+ *
17
+ * @throws {RangeError} if the data length does not match the dimensions,
18
+ * or `quality` is not an integer from 1 to 100.
19
+ * @throws {TypeError} for arguments of the wrong kind.
20
+ * @throws {Error} if a dimension is above 65535.
21
+ */
22
+ export const encode = api.encode;
23
+ /**
24
+ * Make an existing JPEG smaller without changing a pixel. `undefined` if
25
+ * the file is not one this can re-code. An already optimized file can come
26
+ * out larger; compare lengths.
27
+ */
28
+ export const optimize = api.optimize;
29
+ /**
30
+ * Remove EXIF (including GPS), XMP, comments and other metadata without
31
+ * touching the image data. Keeps the color profile and orientation.
32
+ * `undefined` if the file cannot be parsed.
33
+ */
34
+ export const stripMetadata = api.stripMetadata;
35
+ /**
36
+ * Read a JPEG's frame header without decoding it. `undefined` if the bytes
37
+ * are not a JPEG this library understands.
38
+ */
39
+ export const info = api.info;
40
+ /**
41
+ * Decode a grayscale or color JPEG to 1-channel gray or 3-channel RGB
42
+ * pixels, as stored (see `applyOrientation`). `undefined` for CMYK files,
43
+ * codings this library does not decode, malformed input, or frames over
44
+ * 100 megapixels.
45
+ */
46
+ export const decode = api.decode;
47
+ /**
48
+ * Turn pixels upright for an EXIF orientation (`info(jpeg).orientation`).
49
+ * A number outside 1 to 8 leaves them as they are.
50
+ *
51
+ * @throws {RangeError} if the data length does not match the dimensions.
52
+ * @throws {TypeError} if `orientation` is not a number.
53
+ */
54
+ export const applyOrientation = api.applyOrientation;
55
+ /**
56
+ * Resize with a Lanczos3 filter. 4 channels are filtered independently.
57
+ *
58
+ * @throws {RangeError} if the data length does not match the dimensions,
59
+ * a new size is not an integer of at least 1, or the result would be over
60
+ * 100 megapixels.
61
+ * @throws {Error} if `linear` is set for 4 channels.
62
+ */
63
+ export const resize = api.resize;
64
+ /**
65
+ * Copy a rectangle out of an image. `undefined` if the rectangle is empty
66
+ * or not entirely inside the image.
67
+ *
68
+ * @throws {RangeError} if the data length does not match the dimensions,
69
+ * or a rectangle field is not a non-negative integer.
70
+ */
71
+ export const crop = api.crop;
72
+ /**
73
+ * The largest `[width, height]` that fits inside `maxWidth` x `maxHeight`
74
+ * with the same aspect ratio. Never enlarges.
75
+ *
76
+ * @throws {RangeError} if an argument is not an integer of at least 1.
77
+ */
78
+ export const fitWithin = api.fitWithin;