-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
82 lines (72 loc) · 2.04 KB
/
index.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
/**
* @File : index.ts
* @Author : dtysky ([email protected])
* @Date : 11/18/2019, 3:54:07 PM
* @Description:
*/
import * as PNG from 'upng-js';
function debug(msg: string) {
if (process.env.SEINJS_LOADER_DEBUG) {
console.log('seinjs-png-compress-processor', msg);
}
}
export = class SeinJSPNGCompressProcessor {
public test: RegExp | ((filePath: string) => boolean);
private _psize: number = 256;
private _custom: (filePath: string, data: Buffer) => {
psize?: number;
};
constructor(options: {
/**
* Which files will be processed.
*
* @default /\.png/g
*/
test: RegExp | ((filePath: string) => boolean);
/**
* Palette size(how many colors you want to have) if `quantized` is true.
*
* @default 256
*/
psize?: number;
/**
* You can overwrite settings for each file.
*/
custom?(filePath: string): {
psize?: number;
skip?: boolean;
}
}) {
if (options) {
this.test = options.test || /\.png/g;
this._psize = options.psize || 256;
this._custom = options.custom || null;
}
}
process(options: {data: Buffer, filePath: string}): Promise<Buffer> {
return new Promise((resolve) => {
let {data, filePath} = options;
if (!(data instanceof Buffer)) {
data = new Buffer(data);
}
const cpOptions = {psize: this._psize, skip: false};
if (this._custom) {
Object.assign(cpOptions, this._custom(filePath, data) || {});
}
debug(`${filePath}, ${JSON.stringify(cpOptions)}`);
if (cpOptions.skip) {
console.log(`PNG Compress skip: ${filePath}`);
} else {
try {
const png = PNG.decode(data);
const res = PNG.encode([PNG.toRGBA8(png)[0]], png.width, png.height, cpOptions.psize);
data = Buffer.from(res);
console.log(`PNG Compress success: ${filePath}`);
} catch(error) {
console.error(`PNG Compress error: file ${filePath}, ${error.message}`);
}
}
resolve(data);
});
}
}