UNPKG

imghash

Version:

Image perceptual hash calculation for node

103 lines (102 loc) 2.54 kB
import fs from "node:fs"; import { getImageData, imageFromBuffer } from "@canvas/image"; import blockhash from "blockhash-core"; import imageType from "image-type"; import jpeg from "jpeg-js"; //#region \0rolldown/runtime.js var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); //#endregion //#region src/index.ts var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => { const JPEG_MAX_MEMORY_USAGE_MB = 1024; const HEX_BINARY_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" }; const BINARY_TO_HEX_LOOKUP = { "0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", 1e3: "8", 1001: "9", 1010: "a", 1011: "b", 1100: "c", 1101: "d", 1110: "e", 1111: "f" }; 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 { imageData = getImageData(await imageFromBuffer(fileData)); } 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) { let ret = ""; for (let i = 0; i < s.length; i++) if (Object.hasOwn(HEX_BINARY_LOOKUP, s[i])) ret += HEX_BINARY_LOOKUP[s[i]]; return ret; } function binaryToHex(s) { let ret = ""; for (let i = 0; i < s.length; i += 4) { const chunk = s.slice(i, i + 4); if (Object.hasOwn(BINARY_TO_HEX_LOOKUP, chunk)) ret += BINARY_TO_HEX_LOOKUP[chunk]; } return ret; } module.exports = { hash, hashRaw, hexToBinary, binaryToHex }; })); //#endregion export default require_src(); export {};