-
Notifications
You must be signed in to change notification settings - Fork 17
/
PNGEncoder.ts
202 lines (177 loc) · 5.02 KB
/
PNGEncoder.ts
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
import { IOBuffer } from 'iobuffer';
import { deflate } from 'pako';
import { pngSignature, crc } from './common';
import {
DeflateFunctionOptions,
IPNGEncoderOptions,
IImageData,
IDecodedPNG,
PNGDataArray,
BitDepth,
} from './types';
import {
ColorType,
CompressionMethod,
FilterMethod,
InterlaceMethod,
} from './internalTypes';
const defaultZlibOptions: DeflateFunctionOptions = {
level: 3,
};
export default class PNGEncoder extends IOBuffer {
private _png: IDecodedPNG;
private _zlibOptions: DeflateFunctionOptions;
private _colorType: ColorType;
public constructor(data: IImageData, options: IPNGEncoderOptions = {}) {
super();
this._colorType = ColorType.UNKNOWN;
this._zlibOptions = Object.assign({}, defaultZlibOptions, options.zlib);
this._png = this._checkData(data);
this.setBigEndian();
}
public encode(): Uint8Array {
this.encodeSignature();
this.encodeIHDR();
this.encodeData();
this.encodeIEND();
return this.toArray();
}
// https://www.w3.org/TR/PNG/#5PNG-file-signature
private encodeSignature(): void {
this.writeBytes(pngSignature);
}
// https://www.w3.org/TR/PNG/#11IHDR
private encodeIHDR(): void {
this.writeUint32(13);
this.writeChars('IHDR');
this.writeUint32(this._png.width);
this.writeUint32(this._png.height);
this.writeByte(this._png.depth);
this.writeByte(this._colorType);
this.writeByte(CompressionMethod.DEFLATE);
this.writeByte(FilterMethod.ADAPTIVE);
this.writeByte(InterlaceMethod.NO_INTERLACE);
this.writeCrc(17);
}
// https://www.w3.org/TR/PNG/#11IEND
private encodeIEND(): void {
this.writeUint32(0);
this.writeChars('IEND');
this.writeCrc(4);
}
// https://www.w3.org/TR/PNG/#11IDAT
private encodeIDAT(data: PNGDataArray): void {
this.writeUint32(data.length);
this.writeChars('IDAT');
this.writeBytes(data);
this.writeCrc(data.length + 4);
}
private encodeData(): void {
const { width, height, channels, depth, data } = this._png;
const slotsPerLine = channels * width;
const newData = new IOBuffer().setBigEndian();
let offset = 0;
for (let i = 0; i < height; i++) {
newData.writeByte(0); // no filter
/* istanbul ignore else */
if (depth === 8) {
offset = writeDataBytes(data, newData, slotsPerLine, offset);
} else if (depth === 16) {
offset = writeDataUint16(data, newData, slotsPerLine, offset);
} else {
throw new Error('unreachable');
}
}
const buffer = newData.toArray();
const compressed = deflate(buffer, this._zlibOptions);
this.encodeIDAT(compressed);
}
private _checkData(data: IImageData): IDecodedPNG {
const { colorType, channels, depth } = getColorType(data);
const png: IDecodedPNG = {
width: checkInteger(data.width, 'width'),
height: checkInteger(data.height, 'height'),
channels: channels,
data: data.data,
depth: depth,
text: {},
};
this._colorType = colorType;
const expectedSize = png.width * png.height * channels;
if (png.data.length !== expectedSize) {
throw new RangeError(
`wrong data size. Found ${png.data.length}, expected ${expectedSize}`,
);
}
return png;
}
private writeCrc(length: number): void {
this.writeUint32(
crc(
new Uint8Array(
this.buffer,
this.byteOffset + this.offset - length,
length,
),
length,
),
);
}
}
function checkInteger(value: number, name: string): number {
if (Number.isInteger(value) && value > 0) {
return value;
}
throw new TypeError(`${name} must be a positive integer`);
}
function getColorType(
data: IImageData,
): { channels: number; depth: BitDepth; colorType: ColorType } {
const { channels = 4, depth = 8 } = data;
if (channels !== 4 && channels !== 3 && channels !== 2 && channels !== 1) {
throw new RangeError(`unsupported number of channels: ${channels}`);
}
if (depth !== 8 && depth !== 16) {
throw new RangeError(`unsupported bit depth: ${depth}`);
}
const returnValue = { channels, depth, colorType: ColorType.UNKNOWN };
switch (channels) {
case 4:
returnValue.colorType = ColorType.TRUECOLOUR_ALPHA;
break;
case 3:
returnValue.colorType = ColorType.TRUECOLOUR;
break;
case 1:
returnValue.colorType = ColorType.GREYSCALE;
break;
case 2:
returnValue.colorType = ColorType.GREYSCALE_ALPHA;
break;
default:
throw new Error(`unsupported number of channels: ${channels}`);
}
return returnValue;
}
function writeDataBytes(
data: PNGDataArray,
newData: IOBuffer,
slotsPerLine: number,
offset: number,
): number {
for (let j = 0; j < slotsPerLine; j++) {
newData.writeByte(data[offset++]);
}
return offset;
}
function writeDataUint16(
data: PNGDataArray,
newData: IOBuffer,
slotsPerLine: number,
offset: number,
): number {
for (let j = 0; j < slotsPerLine; j++) {
newData.writeUint16(data[offset++]);
}
return offset;
}