tiff-wasm 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mustafa Arif Şişman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # tiff-wasm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read, write, merge and split TIFF files in the browser, in Web Workers and in Node.js. The core is Rust compiled to
4
+ WebAssembly. It is made for scanned documents: CCITT G3/G4 fax, LZW, Deflate, PackBits, JPEG, palette, and
5
+ multi-page files.
6
+
7
+ - **Decode** any page to RGBA, ready for `ImageData`, canvas, `ImageBitmap` or a `Blob`. Pages render the way
8
+ LibTIFF's RGBA interface does: every fixture in the test suite matches LibTIFF's output pixel for pixel (JPEG within
9
+ rounding).
10
+ - **Raw samples** (`readRaster`) for image processing: 1 to 64-bit, integer and float, palette indices.
11
+ - **Tags** of every page, with Exif and GPS, without decoding pixels.
12
+ - **Merge, split, reorder** pages without re-encoding them: a G4 page stays the same G4 bytes.
13
+ - **Encode** images as TIFF pages: CCITT G4 for black and white, gray, RGB or RGBA with LZW, Deflate or PackBits.
14
+ - **Small and isolated**: 176 KB gzipped in total. Every reader and writer owns its memory and frees it on `close()`.
15
+ There is no global module state, no virtual file system, and nothing to tune up front.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install tiff-wasm
21
+ ```
22
+
23
+ ## Use
24
+
25
+ ```js
26
+ import init, { openTiff } from 'tiff-wasm';
27
+
28
+ await init(); // loads tiff_wasm_bg.wasm once (Node: not needed)
29
+
30
+ const reader = openTiff(await file.arrayBuffer());
31
+ for (const page of reader) {
32
+ console.log(page.index, page.width, page.height, page.info.compression); // 'ccitt-g4', 'jpeg', ...
33
+ const image = page.decode(); // { width, height, data: Uint8ClampedArray (RGBA) }
34
+ context.putImageData(new ImageData(image.data, image.width, image.height), 0, 0);
35
+ }
36
+ reader.close();
37
+ ```
38
+
39
+ ### In a Web Worker
40
+
41
+ ```js
42
+ // worker.js (module worker)
43
+ import init, { openTiff } from 'tiff-wasm';
44
+ const ready = init();
45
+
46
+ onmessage = async ({ data: { bytes, page } }) => {
47
+ await ready;
48
+ const reader = openTiff(bytes);
49
+ try {
50
+ const bitmap = await reader.page(page).toImageBitmap();
51
+ postMessage(bitmap, [bitmap]); // transferred, not copied
52
+ } finally {
53
+ reader.close();
54
+ }
55
+ };
56
+ ```
57
+
58
+ ### Merge, split, encode
59
+
60
+ ```js
61
+ import { mergeTiffs, extractPages, splitTiff, encodeTiff, TiffWriter } from 'tiff-wasm';
62
+
63
+ const merged = mergeTiffs([fileA, fileB, { data: fileC, pages: [0, 2] }]); // Uint8Array
64
+ const firstTwo = extractPages(merged, [0, 1]);
65
+ const singlePages = splitTiff(merged);
66
+
67
+ // Scanned pages from a canvas: black and white as CCITT G4 at 300 dpi.
68
+ const tiff = encodeTiff(canvas, { mode: 'bilevel', dpi: 300 });
69
+
70
+ // Or build a file step by step.
71
+ const writer = new TiffWriter();
72
+ writer.addPages(existingTiff).addImage(imageData, { mode: 'gray', compression: 'deflate' });
73
+ const blob = writer.toBlob(); // image/tiff
74
+ writer.close();
75
+ ```
76
+
77
+ ### Loading the WebAssembly file
78
+
79
+ `init()` fetches `tiff_wasm_bg.wasm` from next to the package's JS (`new URL('tiff_wasm_bg.wasm', import.meta.url)`).
80
+ Vite, webpack 5, Rollup and Parcel bundle it that way. If your bundler leaves the file out (some esbuild setups,
81
+ including Angular's), copy `node_modules/tiff-wasm/pkg/tiff_wasm_bg.wasm` to your assets and pass its URL:
82
+
83
+ ```js
84
+ await init('/assets/tiff_wasm_bg.wasm');
85
+ ```
86
+
87
+ `initSync(bytesOrModule)` loads it synchronously. In Node.js, `import ... from 'tiff-wasm'` loads it from disk at import
88
+ time.
89
+
90
+ ## API
91
+
92
+ | | |
93
+ |---|---|
94
+ | `init(input?)`, `initSync(module)`, `isReady()` | Load the WebAssembly module (once). |
95
+ | `openTiff(data)` / `new TiffReader(data)` | Open a file: `pageCount`, `page(i)`, `pages()`, iteration, `close()`, `Symbol.dispose`. |
96
+ | `page.width`, `page.height`, `page.info`, `page.tags` | From the directory, no decoding. `info`: compression, photometric, bits, samples, alpha, resolution, orientation, page number, texts. |
97
+ | `page.decode()` | RGBA `{ width, height, data }`. |
98
+ | `page.toImageData()`, `toImageBitmap()`, `toCanvas()`, `toBlob(type?, q?)`, `toDataURL(type?, q?)` | Display helpers (canvas is `OffscreenCanvas` in workers). |
99
+ | `page.readRaster()` | Samples for processing: `{ width, height, samplesPerPixel, bitsPerSample, photometric, data, palette }`. |
100
+ | `decodeTiff(data, { pages? })` | RGBA of all (or some) pages in one call. |
101
+ | `readTiffInfo(data)`, `countPages(data)` | Info and tags of every page. Pure JS, works without `init()`. |
102
+ | `new TiffWriter()` | `addPages(source, pages?)`, `addImage(image, options)`, `finish()`, `toBlob()`, `close()`. |
103
+ | `mergeTiffs(sources)`, `extractPages(data, pages)`, `splitTiff(data)`, `encodeTiff(images, options)` | One-call writing. |
104
+ | `Tags` | `get(numberOrName)`, `has()`, `nameOf()`, iteration, `toJSON()`, `exif`, `gps`. |
105
+ | `TiffError` | Thrown for unreadable input, closed objects and wrong arguments. |
106
+
107
+ Encode options: `mode` (`'auto'` picks bilevel, gray, RGB or RGBA, whichever holds the pixels exactly; or one of
108
+ those), `compression` (`'auto'` = G4 for bilevel, otherwise LZW; `'none'`, `'ccitt-g4'`, `'lzw'`, `'deflate'`,
109
+ `'packbits'`), `threshold` (bilevel cut-off, default 128), `dpi`.
110
+
111
+ Full types: [`js/index.d.ts`](js/index.d.ts) (TypeScript 5.7+).
112
+
113
+ ## What it reads
114
+
115
+ | | |
116
+ |---|---|
117
+ | Compression | none, CCITT RLE (Modified Huffman), CCITT G3 1D/2D, CCITT G4, LZW, Deflate (both codes), PackBits, JPEG (new style, code 7) |
118
+ | Pixels | bilevel, gray 1/2/4/8/16/32-bit and float, palette 1/2/4/8-bit, RGB/RGBA 8/16-bit, CMYK, YCbCr (JPEG) |
119
+ | Layout | strips and tiles, chunky and planar, predictor 2, FillOrder 2, all orientations (rendered as LibTIFF does), multi-page, BigTIFF |
120
+
121
+ Not supported: old-style JPEG (compression 6), CCITT uncompressed mode, subsampled YCbCr without JPEG, LogLuv/CIELab.
122
+ Writing produces classic (not Big) TIFF up to 4 GiB and does not encode JPEG.
123
+
124
+ ## Performance
125
+
126
+ Node 22 on an Apple M1 Pro. tiff.js 1.0.0 (LibTIFF compiled with Emscripten) is the comparison. Each
127
+ library runs in a fresh process; "page" is the median warm decode of one page to RGBA.
128
+
129
+ | file | tiff.js page | tiff-wasm page | tiff.js module memory | tiff-wasm module memory |
130
+ |---|---:|---:|---:|---:|
131
+ | fax G4, A4 300 dpi, 10 pages | 21.1 ms | 17.2 ms | 64 MB | 36 MB |
132
+ | colour JPEG, A4 200 dpi | 105 ms | 56 ms | 32 MB | 28 MB |
133
+ | gray JPEG, A4 200 dpi | 48 ms | 12 ms | 32 MB | 20 MB |
134
+ | gray LZW, A4 200 dpi | 38 ms | 12 ms | 32 MB | 20 MB |
135
+ | colour LZW, A4 200 dpi | 65 ms | 39 ms | 32 MB | 28 MB |
136
+
137
+ Module load: 4 ms against 40 ms. Download: 487 KB raw / 176 KB gzip / 143 KB brotli, against tiff.js's 1.5 MB / 394 KB /
138
+ 303 KB. Run it yourself with `node bench/make-samples.mjs && npm run bench`.
139
+
140
+ ## Build from source
141
+
142
+ Needs Rust with the `wasm32-unknown-unknown` target, [wasm-pack](https://rustwasm.github.io/wasm-pack/) and binaryen's
143
+ `wasm-opt`.
144
+
145
+ ```sh
146
+ npm run build # Rust -> pkg/
147
+ npm test # Rust tests, JS tests, type check
148
+ npm run fixtures # regenerate tests/fixtures (needs LibTIFF's tools: tiffcp, tiff2rgba)
149
+ ```
150
+
151
+ Cargo features: `jpeg` (JPEG decoding, about 49 KB gzipped) and `encode` (writing, about 29 KB) are on by default.
152
+ `--no-default-features` builds a decoder of about 87 KB gzipped.
153
+
154
+ The tests check decoding against LibTIFF (`tiff2rgba`, and tiff.js in the JS tests) and against an independent
155
+ pure-JS decoder for raw samples and tag values. Every written file is checked with LibTIFF's `tiffinfo -D` and
156
+ `tiff2rgba`.
157
+
158
+ ## License
159
+
160
+ MIT
@@ -0,0 +1,233 @@
1
+ // Reads the TIFF structure (header and directories) in JS: tags of every page without touching pixel data.
2
+ // Classic TIFF and BigTIFF, either byte order. Pixel data is decoded in Rust/WebAssembly.
3
+ import { COMPRESSION, PHOTOMETRIC, TAG_IDS, TAG_NAMES } from './tags.js';
4
+
5
+ /** Thrown for unreadable, unsupported or wrongly used input. */
6
+ export class TiffError extends Error {
7
+ constructor(message, options) {
8
+ super(message, options);
9
+ this.name = 'TiffError';
10
+ }
11
+ }
12
+
13
+ /**
14
+ * The tags of a directory. Values: a number for one value, a typed array (or an array for rationals and 64-bit
15
+ * values) for several, a string for ASCII (an array of strings when it holds several). Rationals are numbers.
16
+ */
17
+ export class Tags {
18
+ /** @param {'tiff' | 'exif' | 'gps'} kind */
19
+ constructor(kind, fields = new Map()) {
20
+ this.kind = kind;
21
+ /** @type {Map<number, any>} */
22
+ this.fields = fields;
23
+ /** @type {Tags | undefined} */
24
+ this.exif = undefined;
25
+ /** @type {Tags | undefined} */
26
+ this.gps = undefined;
27
+ }
28
+
29
+ /** Value of a tag by number or name ('ImageWidth'), or undefined. */
30
+ get(tag) {
31
+ return this.fields.get(typeof tag === 'number' ? tag : TAG_IDS[this.kind][tag]);
32
+ }
33
+
34
+ has(tag) {
35
+ return this.get(tag) !== undefined;
36
+ }
37
+
38
+ /** Name of a tag number in this directory kind, or undefined when unknown. */
39
+ nameOf(tag) {
40
+ return TAG_NAMES[this.kind][tag];
41
+ }
42
+
43
+ /** [tag number, value] pairs. */
44
+ [Symbol.iterator]() {
45
+ return this.fields[Symbol.iterator]();
46
+ }
47
+
48
+ /** Plain object of the tags by name (unknown tags by number), with `exif` and `gps` nested. */
49
+ toJSON() {
50
+ const out = {};
51
+ for (const [tag, value] of this.fields) {
52
+ out[this.nameOf(tag) ?? String(tag)] = ArrayBuffer.isView(value) ? Array.from(value) : value;
53
+ }
54
+ if (this.exif) out.Exif = this.exif.toJSON();
55
+ if (this.gps) out.GPS = this.gps.toJSON();
56
+ return out;
57
+ }
58
+ }
59
+
60
+ const first = value => (value === undefined ? undefined : typeof value === 'number' || typeof value === 'string' ? value : value[0]);
61
+ const list = value => (value === undefined ? [] : typeof value === 'number' ? [value] : Array.from(value));
62
+
63
+ /**
64
+ * What a page is, read from its tags (no decoding).
65
+ * @param {Tags} tags
66
+ */
67
+ export function pageInfo(tags) {
68
+ const width = first(tags.get(256)) ?? 0;
69
+ const height = first(tags.get(257)) ?? 0;
70
+ const compressionCode = first(tags.get(259)) ?? 1;
71
+ const photometricCode = first(tags.get(262));
72
+ const bits = list(tags.get(258));
73
+ const unit = first(tags.get(296)) ?? 2;
74
+ const x = first(tags.get(282));
75
+ const y = first(tags.get(283));
76
+ const pageNumber = tags.get(297);
77
+ const extra = list(tags.get(338));
78
+ return {
79
+ width,
80
+ height,
81
+ compression: COMPRESSION[compressionCode] ?? `unknown-${compressionCode}`,
82
+ compressionCode,
83
+ photometric: photometricCode === undefined ? undefined : PHOTOMETRIC[photometricCode] ?? `unknown-${photometricCode}`,
84
+ photometricCode,
85
+ bitsPerSample: bits.length ? bits[0] : 1,
86
+ samplesPerPixel: first(tags.get(277)) ?? 1,
87
+ sampleFormat: ({ 1: 'uint', 2: 'int', 3: 'float' })[first(tags.get(339)) ?? 1] ?? 'unknown',
88
+ alpha: extra.length === 0 ? 'none' : extra[0] === 1 ? 'premultiplied' : extra[0] === 2 ? 'straight' : 'none',
89
+ planar: (first(tags.get(284)) ?? 1) === 2,
90
+ tiled: tags.has(322) && tags.has(324),
91
+ orientation: first(tags.get(274)) ?? 1,
92
+ fillOrder: first(tags.get(266)) ?? 1,
93
+ predictor: first(tags.get(317)) ?? 1,
94
+ resolution: x === undefined ? undefined : { x, y: y ?? x, unit: unit === 3 ? 'cm' : unit === 1 ? 'none' : 'inch' },
95
+ pageNumber: pageNumber === undefined ? undefined : { index: list(pageNumber)[0], total: list(pageNumber)[1] },
96
+ subfileType: first(tags.get(254)) ?? 0,
97
+ description: first(tags.get(270)),
98
+ documentName: first(tags.get(269)),
99
+ pageName: first(tags.get(285)),
100
+ software: first(tags.get(305)),
101
+ dateTime: first(tags.get(306)),
102
+ artist: first(tags.get(315)),
103
+ make: first(tags.get(271)),
104
+ model: first(tags.get(272)),
105
+ copyright: first(tags.get(33432)),
106
+ };
107
+ }
108
+
109
+ /** Any binary input (ArrayBuffer, typed array, DataView, Node Buffer) as a Uint8Array view, without copying. */
110
+ export function toBytes(data) {
111
+ if (data instanceof Uint8Array) return data;
112
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
113
+ if (data instanceof ArrayBuffer || (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)) return new Uint8Array(data);
114
+ throw new TiffError('expected an ArrayBuffer, a typed array, a DataView or a Buffer');
115
+ }
116
+
117
+ // type: [bytes per value, reader of `count` values at `offset`]
118
+ const bytesOf = (v, o, n) => (n === 1 ? v.getUint8(o) : new Uint8Array(v.buffer.slice(v.byteOffset + o, v.byteOffset + o + n)));
119
+ const TYPES = {
120
+ 1: [1, bytesOf], // BYTE
121
+ 2: [1, readAscii], // ASCII
122
+ 3: [2, (v, o, n, le) => many(n, Uint16Array, i => v.getUint16(o + 2 * i, le))], // SHORT
123
+ 4: [4, (v, o, n, le) => many(n, Uint32Array, i => v.getUint32(o + 4 * i, le))], // LONG
124
+ 5: [8, (v, o, n, le) => many(n, Array, i => v.getUint32(o + 8 * i, le) / v.getUint32(o + 8 * i + 4, le))], // RATIONAL
125
+ 6: [1, (v, o, n) => many(n, Int8Array, i => v.getInt8(o + i))], // SBYTE
126
+ 7: [1, bytesOf], // UNDEFINED
127
+ 8: [2, (v, o, n, le) => many(n, Int16Array, i => v.getInt16(o + 2 * i, le))], // SSHORT
128
+ 9: [4, (v, o, n, le) => many(n, Int32Array, i => v.getInt32(o + 4 * i, le))], // SLONG
129
+ 10: [8, (v, o, n, le) => many(n, Array, i => v.getInt32(o + 8 * i, le) / v.getInt32(o + 8 * i + 4, le))], // SRATIONAL
130
+ 11: [4, (v, o, n, le) => many(n, Float32Array, i => v.getFloat32(o + 4 * i, le))], // FLOAT
131
+ 12: [8, (v, o, n, le) => many(n, Float64Array, i => v.getFloat64(o + 8 * i, le))], // DOUBLE
132
+ 13: [4, (v, o, n, le) => many(n, Uint32Array, i => v.getUint32(o + 4 * i, le))], // IFD
133
+ 16: [8, (v, o, n, le) => many(n, Array, i => Number(v.getBigUint64(o + 8 * i, le)))], // LONG8
134
+ 17: [8, (v, o, n, le) => many(n, Array, i => Number(v.getBigInt64(o + 8 * i, le)))], // SLONG8
135
+ 18: [8, (v, o, n, le) => many(n, Array, i => Number(v.getBigUint64(o + 8 * i, le)))], // IFD8
136
+ };
137
+
138
+ function many(count, ArrayType, read) {
139
+ if (count === 1) return read(0);
140
+ const out = new ArrayType(count);
141
+ for (let i = 0; i < count; i++) out[i] = read(i);
142
+ return out;
143
+ }
144
+
145
+ function readAscii(view, offset, count) {
146
+ const strings = [];
147
+ let current = '';
148
+ for (let i = 0; i < count; i++) {
149
+ const code = view.getUint8(offset + i);
150
+ if (code === 0) {
151
+ strings.push(current);
152
+ current = '';
153
+ } else {
154
+ current += String.fromCharCode(code);
155
+ }
156
+ }
157
+ if (current) strings.push(current); // a value without its terminating NUL
158
+ return strings.length === 1 ? strings[0] : strings;
159
+ }
160
+
161
+ function readHeader(bytes) {
162
+ if (bytes.byteLength < 8) throw new TiffError('not a TIFF file');
163
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
164
+ const order = view.getUint16(0);
165
+ if (order !== 0x4949 && order !== 0x4d4d) throw new TiffError('not a TIFF file');
166
+ const little = order === 0x4949;
167
+ const magic = view.getUint16(2, little);
168
+ if (magic === 42) return { view, little, big: false, first: view.getUint32(4, little) };
169
+ if (magic === 43 && bytes.byteLength >= 16) return { view, little, big: true, first: Number(view.getBigUint64(8, little)) };
170
+ throw new TiffError('not a TIFF file');
171
+ }
172
+
173
+ function readDirectory(header, offset, tags, seen) {
174
+ const { view, little, big } = header;
175
+ const entrySize = big ? 20 : 12;
176
+ const inline = big ? 8 : 4;
177
+ if (offset + (big ? 8 : 2) > view.byteLength) throw new TiffError(`directory at ${offset} is outside the file`);
178
+ const count = big ? Number(view.getBigUint64(offset, little)) : view.getUint16(offset, little);
179
+ const start = offset + (big ? 8 : 2);
180
+ if (start + count * entrySize + inline > view.byteLength) throw new TiffError(`directory at ${offset} is outside the file`);
181
+ for (let i = 0; i < count; i++) {
182
+ const entry = start + i * entrySize;
183
+ const tag = view.getUint16(entry, little);
184
+ const type = view.getUint16(entry + 2, little);
185
+ const n = big ? Number(view.getBigUint64(entry + 4, little)) : view.getUint32(entry + 4, little);
186
+ const spec = TYPES[type];
187
+ if (!spec || n === 0) continue; // unknown type
188
+ const byteLength = spec[0] * n;
189
+ const field = entry + (big ? 12 : 8);
190
+ const at = byteLength > inline ? (big ? Number(view.getBigUint64(field, little)) : view.getUint32(field, little)) : field;
191
+ if (at + byteLength > view.byteLength) continue; // value outside the file
192
+ const value = spec[1](view, at, n, little);
193
+ tags.fields.set(tag, value);
194
+ if ((tag === 34665 || tag === 34853) && typeof value === 'number' && !seen.has(value)) {
195
+ seen.add(value);
196
+ const kind = tag === 34665 ? 'exif' : 'gps';
197
+ try {
198
+ tags[kind] = readDirectory(header, value, new Tags(kind), seen).tags;
199
+ } catch {
200
+ // A broken Exif / GPS directory leaves the page readable.
201
+ }
202
+ }
203
+ }
204
+ const nextField = start + count * entrySize;
205
+ const next = big ? Number(view.getBigUint64(nextField, little)) : view.getUint32(nextField, little);
206
+ return { tags, next };
207
+ }
208
+
209
+ /**
210
+ * Tags of every page (or of the first `limit`), in file order. A loop in the chain ends it; a broken directory
211
+ * after the first ends the list (as libtiff does).
212
+ * @returns {Tags[]}
213
+ */
214
+ export function readDirectories(bytes, limit = Infinity) {
215
+ const header = readHeader(bytes);
216
+ const pages = [];
217
+ const seen = new Set();
218
+ let offset = header.first;
219
+ while (offset && pages.length < limit && !seen.has(offset)) {
220
+ seen.add(offset);
221
+ let result;
222
+ try {
223
+ result = readDirectory(header, offset, new Tags('tiff'), seen);
224
+ } catch (error) {
225
+ if (pages.length === 0) throw error;
226
+ break;
227
+ }
228
+ pages.push(result.tags);
229
+ offset = result.next;
230
+ }
231
+ if (pages.length === 0) throw new TiffError('the TIFF file has no pages');
232
+ return pages;
233
+ }
package/js/index.d.ts ADDED
@@ -0,0 +1,203 @@
1
+ // Typed arrays use TypeScript 5.7+ generics (Uint8Array<ArrayBuffer>).
2
+
3
+ /** Binary input: copied into WebAssembly memory where needed, never modified. */
4
+ export type BinaryInput = ArrayBuffer | SharedArrayBuffer | ArrayBufferView;
5
+
6
+ /** What `init()` accepts: the URL of tiff_wasm_bg.wasm, its bytes, a Response or a compiled module. */
7
+ export type WasmInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
8
+
9
+ /**
10
+ * Loads the WebAssembly module once (later calls wait for the first). Without `input`, tiff_wasm_bg.wasm next to
11
+ * this script is fetched. Not needed with the Node entry, which loads it synchronously.
12
+ */
13
+ export default function init(input?: WasmInput | Promise<WasmInput>): Promise<void>;
14
+ export function init(input?: WasmInput | Promise<WasmInput>): Promise<void>;
15
+ /** Loads the WebAssembly module synchronously from its bytes or a compiled module. */
16
+ export function initSync(module: BufferSource | WebAssembly.Module): void;
17
+ /** True once the WebAssembly module is loaded. */
18
+ export function isReady(): boolean;
19
+
20
+ /** Thrown for unreadable or unsupported input, closed objects and wrong arguments. */
21
+ export class TiffError extends Error {
22
+ name: 'TiffError';
23
+ }
24
+
25
+ /**
26
+ * A tag value: a number for one value, a typed array (or a number array for rationals and 64-bit values) for
27
+ * several, a string for ASCII (a string array when it holds several). Rationals are numbers.
28
+ */
29
+ export type TagValue = number | string | string[] | number[] | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array;
30
+
31
+ /** The tags of a directory (a page, or its Exif / GPS directory). */
32
+ export class Tags implements Iterable<[number, TagValue]> {
33
+ readonly kind: 'tiff' | 'exif' | 'gps';
34
+ readonly fields: Map<number, TagValue>;
35
+ readonly exif: Tags | undefined;
36
+ readonly gps: Tags | undefined;
37
+ /** Value by tag number or name ('ImageWidth', 'DateTimeOriginal', 'GPSLatitude'...). */
38
+ get(tag: number | string): TagValue | undefined;
39
+ has(tag: number | string): boolean;
40
+ nameOf(tag: number): string | undefined;
41
+ [Symbol.iterator](): Iterator<[number, TagValue]>;
42
+ /** Tags by name (unknown ones by number), Exif and GPS nested. */
43
+ toJSON(): Record<string, unknown>;
44
+ }
45
+
46
+ /** Tag numbers by name, per directory kind. */
47
+ export const TAG_IDS: { tiff: Record<string, number>; exif: Record<string, number>; gps: Record<string, number> };
48
+ /** Tag names by number, per directory kind. */
49
+ export const TAG_NAMES: { tiff: Record<number, string>; exif: Record<number, string>; gps: Record<number, string> };
50
+
51
+ export type Compression =
52
+ | 'none' | 'ccitt-rle' | 'ccitt-g3' | 'ccitt-g4' | 'lzw' | 'ojpeg' | 'jpeg' | 'deflate' | 'packbits'
53
+ | 'lerc' | 'lzma' | 'zstd' | 'webp' | 'jpegxl' | `unknown-${number}`;
54
+
55
+ export type Photometric =
56
+ | 'min-is-white' | 'min-is-black' | 'rgb' | 'palette' | 'mask' | 'separated' | 'ycbcr' | 'cielab' | 'icclab'
57
+ | 'itulab' | 'logl' | 'logluv' | `unknown-${number}`;
58
+
59
+ /** A page described from its directory (nothing decoded). */
60
+ export interface PageInfo {
61
+ width: number;
62
+ height: number;
63
+ compression: Compression;
64
+ compressionCode: number;
65
+ /** Undefined when the tag is missing (fax pages are then read as min-is-white). */
66
+ photometric: Photometric | undefined;
67
+ photometricCode: number | undefined;
68
+ bitsPerSample: number;
69
+ samplesPerPixel: number;
70
+ sampleFormat: 'uint' | 'int' | 'float' | 'unknown';
71
+ alpha: 'none' | 'premultiplied' | 'straight';
72
+ planar: boolean;
73
+ tiled: boolean;
74
+ /** TIFF Orientation, 1 (top-left) to 8. */
75
+ orientation: number;
76
+ fillOrder: number;
77
+ predictor: number;
78
+ resolution: { x: number; y: number; unit: 'inch' | 'cm' | 'none' } | undefined;
79
+ pageNumber: { index: number; total: number } | undefined;
80
+ subfileType: number;
81
+ description: string | undefined;
82
+ documentName: string | undefined;
83
+ pageName: string | undefined;
84
+ software: string | undefined;
85
+ dateTime: string | undefined;
86
+ artist: string | undefined;
87
+ make: string | undefined;
88
+ model: string | undefined;
89
+ copyright: string | undefined;
90
+ }
91
+
92
+ /** 8-bit RGBA pixels, top row first, straight alpha; `new ImageData(data, width, height)` takes it as is. */
93
+ export interface RgbaImage {
94
+ width: number;
95
+ height: number;
96
+ data: Uint8ClampedArray<ArrayBuffer>;
97
+ }
98
+
99
+ export type SampleArray =
100
+ | Uint8Array<ArrayBuffer> | Uint16Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Int8Array<ArrayBuffer>
101
+ | Int16Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Float64Array<ArrayBuffer>;
102
+
103
+ /**
104
+ * Samples for processing: chunky, one element per sample, stored row order (Orientation not applied).
105
+ * 1, 2 and 4-bit samples get a byte each. Normalised: 0 is black (min-is-white is inverted), alpha is straight,
106
+ * JPEG YCbCr is RGB. Palette pages give indices into `palette`.
107
+ */
108
+ export interface Raster {
109
+ width: number;
110
+ height: number;
111
+ samplesPerPixel: number;
112
+ /** Bits per sample as stored in the file. */
113
+ bitsPerSample: number;
114
+ photometric: Photometric;
115
+ data: SampleArray;
116
+ /** Palette pages: 8-bit RGB triplets (3 bytes per entry). */
117
+ palette: Uint8Array<ArrayBuffer> | undefined;
118
+ }
119
+
120
+ /** One page of an open TIFF. Size, info and tags need no decoding; every decode*()/to*() call decodes. */
121
+ export class TiffPage {
122
+ readonly reader: TiffReader;
123
+ /** 0 based. */
124
+ readonly index: number;
125
+ readonly width: number;
126
+ readonly height: number;
127
+ readonly tags: Tags;
128
+ readonly info: PageInfo;
129
+ /** RGBA rendering (as LibTIFF's RGBA interface renders it: fax, gray, palette, CMYK, 16-bit... all become RGBA). */
130
+ decode(): RgbaImage;
131
+ toImageData(): ImageData;
132
+ /** Cheap to draw and transferable from a worker to the page. */
133
+ toImageBitmap(): Promise<ImageBitmap>;
134
+ /** OffscreenCanvas in a worker, HTMLCanvasElement in a page. */
135
+ toCanvas(): HTMLCanvasElement | OffscreenCanvas;
136
+ toBlob(type?: string, quality?: number): Promise<Blob>;
137
+ /** Needs a DOM canvas; in a worker use toBlob(). */
138
+ toDataURL(type?: string, quality?: number): string;
139
+ readRaster(): Raster;
140
+ }
141
+
142
+ /** An open TIFF file. The bytes are copied; close() frees everything (also `using`). */
143
+ export class TiffReader implements Iterable<TiffPage> {
144
+ constructor(data: BinaryInput);
145
+ readonly pageCount: number;
146
+ page(index: number): TiffPage;
147
+ pages(): TiffPage[];
148
+ [Symbol.iterator](): Iterator<TiffPage>;
149
+ close(): void;
150
+ [Symbol.dispose](): void;
151
+ }
152
+
153
+ export function openTiff(data: BinaryInput): TiffReader;
154
+ /** Decodes all pages, or the given 0 based indices, to RGBA. */
155
+ export function decodeTiff(data: BinaryInput, options?: { pages?: number[] }): RgbaImage[];
156
+ /** Info and tags of every page; no pixels decoded, no WebAssembly needed. */
157
+ export function readTiffInfo(data: BinaryInput): Array<PageInfo & { index: number; tags: Tags }>;
158
+ /** Number of pages; no WebAssembly needed. */
159
+ export function countPages(data: BinaryInput): number;
160
+
161
+ /** Anything with pixels: ImageData, `{ width, height, data }` (RGBA), a canvas, an ImageBitmap or an image. */
162
+ export type ImageInput =
163
+ | { width: number; height: number; data: Uint8Array | Uint8ClampedArray }
164
+ | ImageData
165
+ | HTMLCanvasElement
166
+ | OffscreenCanvas
167
+ | ImageBitmap
168
+ | HTMLImageElement;
169
+
170
+ export interface EncodeOptions {
171
+ /** 'auto' (default) picks bilevel, gray, rgb or rgba, whichever holds the pixels exactly. */
172
+ mode?: 'auto' | 'bilevel' | 'gray' | 'rgb' | 'rgba';
173
+ /** 'auto' (default): 'ccitt-g4' for bilevel pages, 'lzw' otherwise. LZW and Deflate use the predictor. */
174
+ compression?: 'auto' | 'none' | 'ccitt-g4' | 'lzw' | 'deflate' | 'packbits';
175
+ /** Bilevel: luminance below this is black. Default 128. */
176
+ threshold?: number;
177
+ /** Resolution to record, e.g. 200 or 300 for scans. Left out by default. */
178
+ dpi?: number;
179
+ }
180
+
181
+ /** Builds a multi-page TIFF from copied pages (lossless) and encoded images, in the order added. */
182
+ export class TiffWriter {
183
+ constructor();
184
+ readonly pageCount: number;
185
+ /** Copies pages without re-encoding: all, or the given 0 based indices in that order (repeats allowed). */
186
+ addPages(source: BinaryInput | TiffReader, pages?: number[]): this;
187
+ addImage(image: ImageInput, options?: EncodeOptions): this;
188
+ /** The file; the writer is empty afterwards. */
189
+ finish(): Uint8Array<ArrayBuffer>;
190
+ /** The file as an image/tiff Blob. */
191
+ toBlob(): Blob;
192
+ close(): void;
193
+ [Symbol.dispose](): void;
194
+ }
195
+
196
+ /** Merges files (or picked pages of them) into one, pages untouched. */
197
+ export function mergeTiffs(sources: Array<BinaryInput | { data: BinaryInput; pages?: number[] }>): Uint8Array<ArrayBuffer>;
198
+ /** A new file with the given pages (in that order), untouched. */
199
+ export function extractPages(data: BinaryInput, pages: number[]): Uint8Array<ArrayBuffer>;
200
+ /** One single-page file per page, untouched. */
201
+ export function splitTiff(data: BinaryInput): Array<Uint8Array<ArrayBuffer>>;
202
+ /** Encodes one or more images as a (multi-page) TIFF. */
203
+ export function encodeTiff(images: ImageInput | ImageInput[], options?: EncodeOptions): Uint8Array<ArrayBuffer>;