-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
105 lines (88 loc) · 2.5 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import Gifsicle from './gifsicle';
import { EncodeOptions } from './types';
import { defaultEncodeOptions } from './options';
import { stdout, stderr, flush } from './io';
const queue: Array<() => void> = [];
/**
* Initialize the gifsicle module
*/
const initModule = (): Promise<void> => {
return new Promise((resolve) => {
// add a new job to the queue
queue.push(resolve);
// start it if there is no queue
if (queue.length === 1) {
queue[0]();
}
});
};
/**
* Reset the gifsicle module
*/
const resetModule = (): void => {
if (queue.length > 0) {
// remove finished job
queue.shift();
// trigger next job
if (queue.length > 0) {
queue[0]();
}
}
};
/**
* Encode an input image using Gifsicle
*
* @async
* @param {Buffer} image Image input buffer
* @param {EncodeOptions} encodeOptions Encoding options passed to Gifsicle
* @returns {Buffer} Processed image buffer
*/
const encode = async (image: Buffer, encodeOptions: EncodeOptions = {}): Promise<Buffer> => {
await initModule();
return new Promise((resolve, reject) => {
// merge default options
const filledEncodeOptions = { ...defaultEncodeOptions, ...encodeOptions };
// build arguments
const gifsicleArguments = [
// ignore gifsicle warnings
'--no-warnings',
// remove application extensions from the input image
'--no-app-extensions',
// set optimization level
`--optimize=${filledEncodeOptions.optimizationLevel}`,
// turn on interlacing
filledEncodeOptions.interlaced === true ? '--interlace' : false,
// set number of colors
typeof filledEncodeOptions.colors === 'number' ? `--colors=${filledEncodeOptions.colors}` : false,
// resize image
filledEncodeOptions.width || filledEncodeOptions.height
? `--resize ${filledEncodeOptions.width || '_'}x${filledEncodeOptions.height || '_'}`
: false,
// set input & output file names
'-i',
'/input.gif',
'-o',
'/output.gif',
].filter(Boolean);
let resolved = false;
Gifsicle({
stdout,
stderr,
arguments: gifsicleArguments as string[],
input: new Uint8Array(image.buffer),
output: (res: Uint8Array) => {
resolve(Buffer.from(res));
resolved = true;
},
}).then(() => {
flush();
if (!resolved) {
reject();
}
resetModule();
});
});
};
export default encode;
export type { EncodeOptions } from './types';
module.exports = encode;