1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
|
// Baseline TIFF: writer (RGBA 8-bit, uncompressed or PackBits) and a reader for
// common 8-bit files (none / LZW / PackBits / Deflate-less, strips, predictor 2).
export function encodeTIFF(imageData, { compress = true } = {}) {
const { width: w, height: h, data } = imageData;
const rowBytes = w * 4;
const rowsPerStrip = Math.max(1, Math.floor(65536 / rowBytes));
const strips = [];
for (let y = 0; y < h; y += rowsPerStrip) {
const rows = Math.min(rowsPerStrip, h - y);
const raw = data.subarray(y * rowBytes, (y + rows) * rowBytes);
strips.push(compress ? packBits(raw, rowBytes) : new Uint8Array(raw));
}
const entries = [
[256, 4, 1, w], // ImageWidth
[257, 4, 1, h], // ImageLength
[258, 3, 4, null], // BitsPerSample 8,8,8,8
[259, 3, 1, compress ? 32773 : 1], // Compression
[262, 3, 1, 2], // Photometric RGB
[273, 4, strips.length, null], // StripOffsets
[277, 3, 1, 4], // SamplesPerPixel
[278, 4, 1, rowsPerStrip], // RowsPerStrip
[279, 4, strips.length, null], // StripByteCounts
[282, 5, 1, null], // XResolution
[283, 5, 1, null], // YResolution
[284, 3, 1, 1], // PlanarConfig chunky
[296, 3, 1, 2], // ResolutionUnit inch
[338, 3, 1, 2], // ExtraSamples: unassociated alpha
];
const ifdSize = 2 + entries.length * 12 + 4;
const ifdOffset = 8;
let extra = ifdOffset + ifdSize;
const bpsOffset = extra; extra += 8;
const xresOffset = extra; extra += 8;
const yresOffset = extra; extra += 8;
const stripOffsetsOffset = extra; extra += strips.length > 1 ? strips.length * 4 : 0;
const stripCountsOffset = extra; extra += strips.length > 1 ? strips.length * 4 : 0;
let dataOffset = extra;
const stripOffsets = strips.map((s) => { const o = dataOffset; dataOffset += s.length; return o; });
const buf = new ArrayBuffer(dataOffset);
const v = new DataView(buf);
const u8 = new Uint8Array(buf);
v.setUint16(0, 0x4949); // 'II'
v.setUint16(2, 42, true);
v.setUint32(4, ifdOffset, true);
v.setUint16(ifdOffset, entries.length, true);
entries.forEach(([tag, type, count, value], i) => {
const o = ifdOffset + 2 + i * 12;
v.setUint16(o, tag, true);
v.setUint16(o + 2, type, true);
v.setUint32(o + 4, count, true);
if (tag === 258) v.setUint32(o + 8, bpsOffset, true);
else if (tag === 282) v.setUint32(o + 8, xresOffset, true);
else if (tag === 283) v.setUint32(o + 8, yresOffset, true);
else if (tag === 273) v.setUint32(o + 8, strips.length > 1 ? stripOffsetsOffset : stripOffsets[0], true);
else if (tag === 279) v.setUint32(o + 8, strips.length > 1 ? stripCountsOffset : strips[0].length, true);
else if (type === 3) v.setUint16(o + 8, value, true);
else v.setUint32(o + 8, value, true);
});
v.setUint32(ifdOffset + 2 + entries.length * 12, 0, true);
for (let i = 0; i < 4; i++) v.setUint16(bpsOffset + i * 2, 8, true);
v.setUint32(xresOffset, 72, true); v.setUint32(xresOffset + 4, 1, true);
v.setUint32(yresOffset, 72, true); v.setUint32(yresOffset + 4, 1, true);
if (strips.length > 1) {
strips.forEach((s, i) => {
v.setUint32(stripOffsetsOffset + i * 4, stripOffsets[i], true);
v.setUint32(stripCountsOffset + i * 4, s.length, true);
});
}
strips.forEach((s, i) => u8.set(s, stripOffsets[i]));
return new Blob([buf], { type: 'image/tiff' });
}
/** PackBits, row by row (rows must not be merged per the TIFF spec). */
function packBits(raw, rowBytes) {
const out = [];
for (let r = 0; r < raw.length; r += rowBytes) {
const end = r + rowBytes;
let i = r;
while (i < end) {
// run?
let run = 1;
while (i + run < end && run < 128 && raw[i + run] === raw[i]) run++;
if (run >= 3) {
out.push((257 - run) & 0xff, raw[i]);
i += run;
continue;
}
// literal
let lit = 1;
while (i + lit < end && lit < 128) {
if (i + lit + 2 < end && raw[i + lit] === raw[i + lit + 1] && raw[i + lit] === raw[i + lit + 2]) break;
lit++;
}
out.push(lit - 1);
for (let k = 0; k < lit; k++) out.push(raw[i + k]);
i += lit;
}
}
return new Uint8Array(out);
}
// ------------------------------------------------------------------ decoder
export function isTIFF(bytes) {
return bytes.length > 4 && ((bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 42) || (bytes[0] === 0x4d && bytes[1] === 0x4d && bytes[3] === 42));
}
export function decodeTIFF(buffer) {
const v = new DataView(buffer);
const u8 = new Uint8Array(buffer);
const le = v.getUint16(0) === 0x4949;
const u16 = (o) => v.getUint16(o, le);
const u32 = (o) => v.getUint32(o, le);
const ifd = u32(4);
const n = u16(ifd);
const tags = {};
const typeSize = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8 };
for (let i = 0; i < n; i++) {
const o = ifd + 2 + i * 12;
const tag = u16(o), type = u16(o + 2), count = u32(o + 4);
const size = (typeSize[type] || 1) * count;
const at = size <= 4 ? o + 8 : u32(o + 8);
const vals = [];
for (let k = 0; k < Math.min(count, 1 << 16); k++) {
if (type === 3) vals.push(u16(at + k * 2));
else if (type === 4) vals.push(u32(at + k * 4));
else if (type === 1 || type === 7) vals.push(u8[at + k]);
else if (type === 5) vals.push(u32(at + k * 8) / (u32(at + k * 8 + 4) || 1));
}
tags[tag] = vals;
}
const w = tags[256][0], h = tags[257][0];
const bps = tags[258] || [1];
const comp = (tags[259] || [1])[0];
const photometric = (tags[262] || [2])[0];
const spp = (tags[277] || [1])[0];
const rowsPerStrip = (tags[278] || [h])[0];
const offsets = tags[273] || tags[324];
const counts = tags[279] || tags[325];
const predictor = (tags[317] || [1])[0];
const planar = (tags[284] || [1])[0];
const extra = tags[338] || [];
if (bps[0] !== 8) throw new Error(`TIFF: only 8-bit images are supported (got ${bps[0]}-bit)`);
if (planar !== 1) throw new Error('TIFF: planar configuration not supported');
if (tags[322]) throw new Error('TIFF: tiled images are not supported');
if (![1, 5, 32773].includes(comp)) throw new Error(`TIFF: compression ${comp} not supported`);
const rowBytes = w * spp;
const raw = new Uint8Array(rowBytes * h);
let pos = 0;
for (let s = 0; s < offsets.length; s++) {
const chunk = u8.subarray(offsets[s], offsets[s] + counts[s]);
const expected = Math.min(rowsPerStrip, h - s * rowsPerStrip) * rowBytes;
let dec;
if (comp === 1) dec = chunk;
else if (comp === 32773) dec = unpackBits(chunk, expected);
else dec = lzwDecode(chunk, expected);
raw.set(dec.subarray(0, Math.min(expected, raw.length - pos)), pos);
pos += expected;
}
if (predictor === 2) {
for (let y = 0; y < h; y++) {
const r = y * rowBytes;
for (let x = spp; x < rowBytes; x++) raw[r + x] = (raw[r + x] + raw[r + x - spp]) & 0xff;
}
}
const out = new ImageData(w, h);
const d = out.data;
const premultiplied = extra[0] === 1;
for (let p = 0; p < w * h; p++) {
const i = p * spp, o = p * 4;
if (photometric === 2 || photometric === 6) {
d[o] = raw[i]; d[o + 1] = raw[i + 1]; d[o + 2] = raw[i + 2];
d[o + 3] = spp >= 4 ? raw[i + 3] : 255;
} else {
let g = raw[i];
if (photometric === 0) g = 255 - g;
d[o] = d[o + 1] = d[o + 2] = g;
d[o + 3] = spp >= 2 ? raw[i + 1] : 255;
}
if (premultiplied && d[o + 3] && d[o + 3] < 255) {
const k = 255 / d[o + 3];
d[o] *= k; d[o + 1] *= k; d[o + 2] *= k;
}
}
return out;
}
function unpackBits(src, expected) {
const out = new Uint8Array(expected);
let i = 0, o = 0;
while (i < src.length && o < expected) {
const n = (src[i++] << 24) >> 24;
if (n >= 0) { for (let k = 0; k <= n && o < expected; k++) out[o++] = src[i++]; }
else if (n !== -128) { const b = src[i++]; for (let k = 0; k < 1 - n && o < expected; k++) out[o++] = b; }
}
return out;
}
function lzwDecode(src, expected) {
const out = new Uint8Array(expected);
let o = 0;
let bitPos = 0;
const read = (size) => {
let v = 0;
for (let k = 0; k < size; k++) {
const byte = src[(bitPos + k) >> 3];
if (byte === undefined) return 257;
v = (v << 1) | ((byte >> (7 - ((bitPos + k) & 7))) & 1); // MSB-first
}
bitPos += size;
return v;
};
let dict = [];
const reset = () => { dict = []; for (let i = 0; i < 256; i++) dict[i] = [i]; dict[256] = null; dict[257] = null; };
reset();
let codeSize = 9;
let prev = null;
while (o < expected) {
const code = read(codeSize);
if (code === 257) break;
if (code === 256) { reset(); codeSize = 9; prev = null; continue; }
let entry;
if (code < dict.length && dict[code]) entry = dict[code];
else if (prev) entry = [...prev, prev[0]];
else break;
for (const b of entry) { if (o < expected) out[o++] = b; }
if (prev) dict.push([...prev, entry[0]]);
prev = entry;
if (dict.length + 1 >= (1 << codeSize) && codeSize < 12) codeSize++;
}
return out;
}
|