-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.js
122 lines (110 loc) · 2.29 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"use strict";
const fs = require("fs");
const blockhash = require("blockhash-core");
const { imageFromBuffer, getImageData } = require("@canvas/image");
const imageType = require("image-type");
const jpeg = require("jpeg-js");
const JPEG_MAX_MEMORY_USAGE_MB = 1024;
async function hash(filepath, bits, format) {
format = format || "hex";
if (format !== "hex" && format !== "binary") {
throw new Error(`Unsupported format: ${format}`);
}
bits = bits || 8;
if (bits % 4 !== 0) {
throw new Error(`Invalid bit-length: ${bits}`);
}
const fileData = await new Promise((resolve, reject) => {
if (Buffer.isBuffer(filepath)) {
return resolve(filepath);
}
fs.readFile(filepath, (err, content) => {
if (err) return reject(err);
resolve(content);
});
});
let imageData;
try {
const image = await imageFromBuffer(fileData);
imageData = getImageData(image);
} catch (error) {
if (imageType(fileData).mime === "image/jpeg") {
imageData = jpeg.decode(fileData, {
maxMemoryUsageInMB: JPEG_MAX_MEMORY_USAGE_MB,
});
} else {
throw error;
}
}
const hexHash = hashRaw(imageData, bits);
if (format === "binary") {
return hexToBinary(hexHash);
}
return hexHash;
}
function hashRaw(data, bits) {
return blockhash.bmvbhash(data, bits);
}
function hexToBinary(s) {
const lookup = {
0: "0000",
1: "0001",
2: "0010",
3: "0011",
4: "0100",
5: "0101",
6: "0110",
7: "0111",
8: "1000",
9: "1001",
a: "1010",
b: "1011",
c: "1100",
d: "1101",
e: "1110",
f: "1111",
A: "1010",
B: "1011",
C: "1100",
D: "1101",
E: "1110",
F: "1111",
};
let ret = "";
for (let i = 0; i < s.length; i++) {
ret += lookup[s[i]];
}
return ret;
}
function binaryToHex(s) {
const lookup = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
1000: "8",
1001: "9",
1010: "a",
1011: "b",
1100: "c",
1101: "d",
1110: "e",
1111: "f",
};
let ret = "";
for (let i = 0; i < s.length; i += 4) {
let chunk = s.slice(i, i + 4);
ret += lookup[chunk];
}
return ret;
}
module.exports = {
hash,
hashRaw,
hexToBinary,
binaryToHex,
};