/
image.js
53 lines (40 loc) · 1.24 KB
/
image.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
import getPixels from "get-pixels";
import { argv } from "process";
import { writeFileSync } from "fs";
if (argv.length != 4) {
console.log(`Received ${argv.length - 2} arguments. Expected 2\n`);
console.log("Usage: node image.js [input path] [output path]");
process.exit(1);
}
const inputPath = argv[2];
const outputPath = argv[3];
const dataWidth = 1;
getPixels(inputPath, (err, pixels) => {
if (err) {
console.log(`Error loading pixels: ${err}`);
return;
}
const [width, height] = pixels.shape;
let outputBuffer = Buffer.alloc((width * height * dataWidth) / 2);
let word = 0;
let setLow = false;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const red = pixels.get(x, y, 0);
// const green = pixels.get(x, y, 1);
// const blue = pixels.get(x, y, 2);
// const alpha = pixels.get(x, y, 3);
// Use only red channel
// outputBuffer[y * width + x] = red;
if (setLow) {
word |= red / 16;
outputBuffer[Math.floor((y * width + x) / 2)] = word;
} else {
word = (red / 16) << 4;
}
setLow = !setLow;
}
}
writeFileSync(outputPath, outputBuffer, { flag: "w" });
console.log(`Wrote output file ${outputPath}`);
});