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 |
x2
 
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
 
x43
x44
x44
 
x44
x43
x44
x44
 
x44
x43
x44
x44
x44
x44
 
x44
x43
x44
x44
 
x44
x43
x44
x44
x43
x44
x44
 
x78
x78
x113
x113
x113
x113
x113
x113
x460173
x460186
x460186
x460173
x460173
x460184
x460184
x460173
x460173
x460173
x460173
 
x113
x135
x138
x552
x138
x135
x156
x624
x156
x167
 
 
 
 
x150
x600
x150
 
x113
x120
x120
x120
x120
x120
x120
 
x120
x480
x120
 
x113
x114
x456
x114
x533
x141
 
x116
x464
x78
 
x78
x78
x78
x78
x78
x78
x78
 
 
 
 
 
 
x78
x78
x78
 
x780
x78
 
 
x468
x113
x113
x113
x113
x113
x113
x113
x113
x113
x113
x78
 
x78
x43
x43
x65
 
x498
x101
x101
x101
x104
x104
x104
x104
x104
x101
x83
x83
x65
x43
 
x300
x57
x65
x65
x65
x65
x57
x50
x50
x50
x50
 
x330
x60
x60
x60
x60
x55
x55
x50
x43
 
 
x78
x78
x78
x78
x78
x78
x78
x78
x78
x78
x78
x78
 
 
 
x78
x78
x78
x78
x468
x113
x113
x113
x78
x78
 
 
x468
 
x78
x43
 
x137
x137
x137
x137
x137
x137
 
x137
x137
x137
x137
x137
x137
x137
 
x37
x37
 
x37
x37
x37
x37
x37
x37
x37
x37
x37
x37
x37
x37
 
x37
x37
x37
x44
x37
x65
x37
x37
 
x37
x37
x37
x55
x37
x41
x37
x44
x37
x43
x37
x37 |
I
I
I
|
import { calcCRC } from "../_crc.ts";
import type { PNGOptions } from "../types.ts";
import { filter } from "./_filter.ts";
import { passExtraction } from "./_passExtraction.ts";
import { scanlines } from "./_scanlines.ts";
import {
guaranteeInvisiblePixel,
toGrayscale,
toGrayscaleAlpha,
toIndex,
toTruecolor,
} from "./_to.ts";
/**
* 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();
*
* 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 metadata for the raw image data.
* @returns An PNG image.
*
* @module
*/
export async function encodePNG(
input: Uint8Array | Uint8ClampedArray,
options: PNGOptions,
): Promise<Uint8Array> {
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 | 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) {
output[o++] = pixel >> 24 & 0xFF;
output[o++] = pixel >> 16 & 0xFF;
output[o++] = pixel >> 8 & 0xFF;
}
return o;
});
if (
(palette as Uint32Array).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) {
output[o++] = pixel & 0xFF;
}
return o;
});
}
break;
}
// Add IDAT chunks
input = output.subarray(maxSize - originalSize);
input = await new Response(
ReadableStream.from([
output.subarray(
filter(
output,
colorType,
pixelSize,
scanlines(
input,
pixelSize,
passExtraction(input, pixelSize, options),
),
),
),
])
.pipeThrough(new CompressionStream("deflate")),
).bytes();
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,
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;
}
}
|