hash()
Compute a perceptual hash of the image as a string in any base.
From @jimp/plugin-hash
hash returns the image’s perceptual hash, the same bits as pHash, written in a more compact base.
The default, base 64, turns the 64-bit hash into an 11-character string that’s easy to store and to use as a lookup key.
Signature
image.hash( base?: number, options?: { size?: number; smallerSize?: number },): stringhash doesn’t change the image. It returns a string, padded with leading 0s so every hash in a given base and size has the same length.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
base |
number |
64 |
The base to write the hash in, from 2 to 64. 2 is binary, 16 is hexadecimal. |
options |
object |
{} |
size and smallerSize, as for pHash. They set how many bits the hash has. |
Example
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
image.hash(); // "bUvO$3wo1Wi" (base 64)image.hash(16); // "be1fcbe0e0601e92"image.hash(2); // the same 64 bits as image.pHash()Find exact duplicates
Images with the same hash look the same to the algorithm, so you can group them with a Map:
import { Jimp } from "jimp";
const files = ["a.jpg", "b.jpg", "a-copy.png"];const groups = new Map<string, string[]>();
for (const file of files) { const image = await Jimp.read(file); const key = image.hash();
groups.set(key, [...(groups.get(key) ?? []), file]);}For “close enough” matches rather than identical hashes, compare the hashes with compareHashes. It decodes them back to bits, so compareHashes(a.hash(), b.hash()) gives the same result as comparing their pHash() strings.
A longer hash
options work as they do for pHash. With smallerSize: 16 the hash has 256 bits, which is 64 characters in base 16:
image.hash(16, { smallerSize: 16 }); // 64 hex digitsNotes
- Digits. Bases above 10 use
0-9, thena-z, thenA-Z, then$and_. Base 64 output is therefore not the standard Base64 encoding. - Comparing hashes.
compareHashesassumes base 64 for strings that aren’t binary. For other bases, pass the base:compareHashes(a.hash(16), b.hash(16), 16). - Invalid bases. A
basebelow2or above64throwsbase must be a number between 2 and 64. - Invalid options.
optionsare validated likepHash’s; see its notes. - Added in 2.0: the
optionsargument. - Changed in 2.0: the hash is computed differently (see
pHash), so hashes stored with 1.x don’t match hashes from 2.0. Hash the images again.