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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308 |
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x45
x46
x46
x46
x45
x46
x46
x46
x45
x46
x46
x46
x46
x46
x45
x46
x46
x46
x45
x46
x46
x45
x46
x46
x82
x82
x119
x119
x119
x119
x119
x119
x460181
x460194
x460194
x460181
x460181
x460192
x460192
x460181
x460181
x460181
x460181
x119
x143
x146
x584
x146
x143
x147
x588
x147
x160
x160
x640
x160
x119
x126
x126
x126
x126
x126
x126
x126
x504
x126
x119
x120
x480
x120
x560
x148
x122
x488
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x820
x82
x492
x119
x119
x119
x119
x119
x119
x119
x119
x119
x119
x82
x82
x45
x45
x69
x534
x109
x109
x109
x112
x112
x112
x112
x112
x109
x89
x89
x69
x45
x312
x59
x67
x67
x67
x67
x59
x52
x52
x52
x52
x52
x342
x62
x62
x62
x62
x57
x57
x52
x45
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x82
x45
x46
x46
x82
x81
x486
x117
x117
x117
x81
x81
x486
x81
x45
x143
x143
x143
x143
x143
x143
x143
x143
x143
x143
x143
x143
x143
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x39
x46
x39
x69
x39
x39
x39
x39
x39
x59
x39
x43
x39
x46
x39
x45
x39
x39 |
I
I
I
|
import { calcCRC } from "@img/internal/apng-png/crc";
import type { PNGOptions } from "@img/internal/apng-png/types";
import {
filter,
guaranteeInvisiblePixel,
passExtraction,
scanlines,
toGrayscale,
toGrayscaleAlpha,
toIndex,
toTruecolor,
} from "@img/internal/apng-png/encode";
import { AbortStream } from "@std/streams/unstable-abort-stream";
/**
* encodePNG is a function that encodes raw image data into the PNG image
* format. The raw image data is expected to be in a sequence of
* `[ r, g, b, a ]` numbers.
*
* @example
* ```ts
* import { encodePNG } from "@img/png";
*
* await Deno.mkdir(".output/", { recursive: true });
*
* const rawData = await new Response(ReadableStream.from(async function* () {
* for (let r = 0; r < 256; ++r) {
* for (let c = 0; c < 256; ++c) {
* yield Uint8Array.from([255 - r, c, r, 255]);
* }
* }
* }())).bytes() as Uint8Array<ArrayBuffer>;
*
* await Deno.writeFile(".output/encode.png", await encodePNG(rawData, {
* width: 256,
* height: 256,
* compression: 0,
* filter: 0,
* interlace: 0,
* }));
* ```
*
* @param input The raw image data.
* @param options The options for the raw image data.
* @param signal The abort signal for the operation.
* @returns An PNG image.
*
* @module
*/
export async function encodePNG(
input: Uint8Array<ArrayBuffer> | Uint8ClampedArray<ArrayBuffer>,
options: PNGOptions,
signal?: AbortSignal,
): Promise<Uint8Array<ArrayBuffer>> {
if (!Number.isInteger(options.width) || options.width < 1) {
throw new RangeError(
`Width (${options.width}) must be an integer value greater than zero`,
);
}
if (!Number.isInteger(options.height) || options.height < 1) {
throw new RangeError(
`Height (${options.height}) must be an integer value greater than zero`,
);
}
if (input.length / 4 !== options.width * options.height) {
throw new RangeError(
`Number of pixels (${
options.width * options.height
}) does not match input length`,
);
}
if (options.compression !== 0) {
throw new TypeError(
`Unsupported Compression Method: ${options.compression}`,
);
}
if (options.filter !== 0) {
throw new TypeError(`Unsupported Filter Method: ${options.filter}`);
}
if (options.interlace !== 0 && options.interlace !== 1) {
throw new TypeError(`Unsupported Interlace Method: ${options.interlace}`);
}
let palette: Uint32Array<ArrayBuffer> | number | undefined;
const [colorType, pixelSize] = function (): [number, number] {
let isOpaque = true;
let isHazy = false;
let isGray = true;
const colors = new Map<number, number>();
const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
for (let i = 0; i < input.length; i += 4) {
if (isGray && (input[i] !== input[i + 1] || input[i] !== input[i + 2])) {
isGray = false;
}
if (isOpaque && input[i + 3] !== 255) isOpaque = false;
if (!isHazy && (input[i + 3] !== 255 && input[i + 3] !== 0)) {
isHazy = true;
}
const x = view.getUint32(i);
colors.set(x, (colors.get(x) ?? 0) + 1);
if (!isGray && !isOpaque && isHazy && colors.size > 256) break;
}
// Grayscale
if (isGray) {
if (isOpaque) {
input = toGrayscale(input);
return [0, 1];
}
if (isHazy) {
input = toGrayscaleAlpha(input);
return [4, 2];
}
palette = guaranteeInvisiblePixel(input, colors, true);
if (palette == undefined) {
input = toGrayscaleAlpha(input);
return [4, 2];
}
input = toGrayscale(input);
return [0, 1];
}
// Index
if (colors.size < 256) {
palette = Uint32Array.from(
colors
.entries()
.toArray()
.sort((x, y) => y[1] - x[1])
.map((x) => x[0]),
);
input = toIndex(input, palette);
return [3, 1];
}
// Truecolor
if (isOpaque) {
input = toTruecolor(input);
return [2, 3];
}
if (isHazy) return [6, 4];
palette = guaranteeInvisiblePixel(input, colors, false);
if (palette == undefined) return [6, 4];
input = toTruecolor(input);
return [2, 3];
}();
const originalSize = input.length;
const maxSize = 8 + // Signature
25 + // IHDR
calcPLTESize(colorType) +
calctRNSSize(colorType) +
calcIDATSize(originalSize, options) +
12; // IEND
if (input.byteOffset) {
const buffer = new Uint8Array(input.buffer);
buffer.set(input);
input = buffer.subarray(0, input.length);
}
// deno-lint-ignore no-explicit-any
const output = new Uint8Array((input.buffer as any).transfer(maxSize));
output.set(output.subarray(0, originalSize), maxSize - originalSize);
const view = new DataView(output.buffer);
output.set([137, 80, 78, 71, 13, 10, 26, 10]);
let offset = 8;
// Add IHDR chunk
offset = addChunk(output, view, offset, [73, 72, 68, 82], (o) => {
view.setUint32(o, options.width);
view.setUint32(o + 4, options.height);
output.set([
8,
colorType,
options.compression,
options.filter,
options.interlace,
], o + 8);
return o + 13;
});
switch (colorType) {
case 0:
case 2:
if (typeof palette === "number") {
// Add tRNS chunk (Optional)
offset = addChunk(output, view, offset, [116, 82, 78, 83], (o) => {
output[o++] = 0;
output[o++] = palette as number >> 24 & 0xFF;
if (colorType === 2) {
output[o++] = 0;
output[o++] = palette as number >> 16 & 0xFF;
output[o++] = 0;
output[o++] = palette as number >> 8 & 0xFF;
}
return o;
});
}
break;
case 3:
// Add PLTE chnk (Optional)
offset = addChunk(output, view, offset, [80, 76, 84, 69], (o) => {
for (const pixel of palette as Uint32Array<ArrayBuffer>) {
output[o++] = pixel >> 24 & 0xFF;
output[o++] = pixel >> 16 & 0xFF;
output[o++] = pixel >> 8 & 0xFF;
}
return o;
});
if (
(palette as Uint32Array<ArrayBuffer>).find((x) => (x & 0xFF) !== 255) !=
undefined
) {
// Add tRNS chunk (Optional)
offset = addChunk(output, view, offset, [116, 82, 78, 83], (o) => {
for (const pixel of palette as Uint32Array<ArrayBuffer>) {
output[o++] = pixel & 0xFF;
}
return o;
});
}
break;
}
// Add IDAT chunks
input = output.subarray(maxSize - originalSize);
let readable = ReadableStream.from([
output.subarray(
filter(
output,
colorType,
pixelSize,
scanlines(
input,
pixelSize,
passExtraction(input, pixelSize, options),
),
),
),
])
.pipeThrough(new CompressionStream("deflate"));
if (signal) {
readable = readable.pipeThrough(new AbortStream(signal));
}
input = await new Response(readable).bytes() as Uint8Array<ArrayBuffer>;
for (let i = 0; i < input.length; i += 2 ** 32 - 1) {
offset = addChunk(output, view, offset, [73, 68, 65, 84], (o) => {
const length = Math.min(input.length - i, 2 ** 31 - 1);
output.set(input.subarray(0, length), o);
return o + length;
});
}
// Add IEND chunk
offset = addChunk(output, view, offset, [73, 69, 78, 68], (o) => o);
return output.subarray(0, offset);
}
function addChunk(
output: Uint8Array<ArrayBuffer>,
view: DataView,
offset: number,
chunkType: ArrayLike<number>,
dataFn: (o: number) => number,
): number {
const lenOffset = offset;
output.set(chunkType, offset + 4); // Chunk Type
offset = dataFn(offset + 8); // Chunk Data
view.setUint32(lenOffset, offset - lenOffset - 8); // Length
view.setUint32(offset, calcCRC(output.subarray(lenOffset + 4, offset))); // CRC
return offset + 4;
}
function calcIDATSize(size: number, options: PNGOptions): number {
size += options.interlace === 1
// (height - admin7Pass.sY + admin7Pass.nY - 1) / admin7Pass.nY
? (options.height + 7) / 8 +
(options.height + 7) / 8 +
(options.height + 3) / 8 +
(options.height + 3) / 4 +
(options.height + 1) / 4 +
(options.height + 1) / 2 +
options.height / 2
: options.height; // Plus Filter Bytes
size += ((size + 32767) / 32768 | 0) * 5 + 12; // Worst Compression Size
size += ((size + 2 ** 31 - 2) / (2 ** 31 - 1) | 0) * 12; // Plus IDAT Overhead
return size;
}
function calcPLTESize(colorType: number): number {
switch (colorType) {
case 3:
return 780;
default:
return 0;
}
}
function calctRNSSize(colorType: number): number {
switch (colorType) {
case 0:
return 14;
case 2:
return 18;
case 3:
return 780;
default:
return 0;
}
}
|