-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
51 lines (41 loc) · 1.21 KB
/
index.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
import {PNG} from 'pngjs';
import Datauri from 'datauri';
const datauri = new Datauri();
export const convert = (rgbaInput, width, height) => {
// (performance)
// eslint-disable-next-line no-var
var idx = 0;
// TODO: validate input
// TODO: add promises, don't do this all on sync
const SIZE = width * height * 4;
let data;
if (Buffer.isBuffer(rgbaInput)) {
// input is flattened buffer
if (rgbaInput.length !== SIZE) {
throw new Error(`Invalid input buffer length, must be ${SIZE} bytes`);
}
data = rgbaInput;
} else {
// input is array of quadruplets
const quadrupletLength = width * height;
if (rgbaInput.length !== quadrupletLength) {
throw new Error(`Invalid length of quadruplet array input, must be ${quadrupletLength}`);
}
data = Buffer.alloc(SIZE);
while (idx < SIZE) {
idx = data.writeUInt8(
rgbaInput[Math.floor(idx / 4)][idx % 4],
idx
);
}
}
// Create png instance with metadata
const png = new PNG();
png.width = width;
png.height = height;
png.data = data;
// Write image into buffer
const buffer = PNG.sync.write(png);
const uri = datauri.format('.png', buffer);
return uri.content;
};