-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathencode_node.js
61 lines (49 loc) · 1.64 KB
/
encode_node.js
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
import * as path from "path";
import { promisify } from "util";
import { writeFile } from "fs/promises";
import getPixelsCb from "get-pixels";
import { GIFEncoder, quantize, applyPalette } from "../src/index.js";
const getPixels = promisify(getPixelsCb);
const __dirname = import.meta.dirname;
encode();
async function encode() {
// Load width/height + RGBA uint8 array data
const { data, width, height } = await readImage(
path.resolve(__dirname, "fixtures/baboon.png"),
);
// Choose a pixel format: rgba4444, rgb444, rgb565
const format = "rgb444";
// If necessary, quantize your colors to a reduced palette
const palette = quantize(data, 256, { format });
// Apply palette to RGBA data to get an indexed bitmap
const index = applyPalette(data, palette, format);
// Now let's encode it into a GIF
const gif = GIFEncoder();
// Write a single frame into the encoder
gif.writeFrame(index, width, height, { palette });
// Finish encoding (write end-of-file character)
gif.finish();
// Get a uint8array buffer with our bytes
const bytes = gif.bytes();
// Write the uint8 array data to file
await writeFile(
path.resolve(__dirname, "output/test.gif"),
Buffer.from(bytes),
);
}
async function readImage(file) {
const { data, shape } = await getPixels(file);
let width, height;
if (shape.length === 3) {
// PNG,JPG,etc...
width = shape[0];
height = shape[1];
} else if (shape.length === 4) {
// still GIFs might appear in frames, so [N,w,h]
width = shape[1];
height = shape[2];
} else {
throw new Error("Invalid shape " + shape.join(", "));
}
return { data, width, height };
}