-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (86 loc) · 2.24 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
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
const fs = require("fs");
const bmp = require("bmp-js");
const sharp = require("sharp");
function scan(bitmap, f) {
const w = Math.round(bitmap.width);
const h = Math.round(bitmap.height);
for (let _y = 0; _y < h; _y++) {
for (let _x = 0; _x < w; _x++) {
const index = (bitmap.width * _y + _x) << 2;
f.call(bitmap, index);
}
}
return bitmap;
}
function fromAGBR(bitmap) {
return scan(bitmap, (index) => {
const alpha = bitmap.data[index + 0];
const blue = bitmap.data[index + 1];
const green = bitmap.data[index + 2];
const red = bitmap.data[index + 3];
bitmap.data[index + 0] = red;
bitmap.data[index + 1] = green;
bitmap.data[index + 2] = blue;
bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff;
});
}
function toAGBR(bitmap) {
return scan(bitmap, (index) => {
const red = bitmap.data[index + 0];
const green = bitmap.data[index + 1];
const blue = bitmap.data[index + 2];
const alpha = bitmap.data[index + 3];
bitmap.data[index + 0] = alpha;
bitmap.data[index + 1] = blue;
bitmap.data[index + 2] = green;
bitmap.data[index + 3] = red;
});
}
function decode(buffer) {
return fromAGBR(bmp.decode(buffer));
}
function encode(bitmap) {
return bmp.encode(toAGBR(bitmap));
}
function sharpFromBmp(input, options, resolveWithObject = false) {
const buffer = typeof input === "string" ? fs.readFileSync(input) : input;
const bitmap = decode(buffer);
const image = sharp(bitmap.data, {
...options,
raw: {
width: bitmap.width,
height: bitmap.height,
channels: 4,
},
});
return resolveWithObject ? Object.assign(bitmap, { image }) : image;
}
async function sharpToBmp(image, fileOut) {
const { data, info } = await image
.flatten({ background: "#ffffff" })
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const bitmap = {
data,
width: info.width,
height: info.height,
};
const rawData = encode(bitmap);
try {
fs.writeFileSync(fileOut, rawData.data);
return {
width: info.width,
height: info.height,
size: rawData.data.length,
};
} catch (err) {
return Promise.reject(err);
}
}
module.exports = {
encode,
decode,
sharpFromBmp,
sharpToBmp,
};