Skip to content

Commit

Permalink
feat: initial commit 🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
ClaudiuCeia committed Aug 26, 2022
0 parents commit a12bdcf
Show file tree
Hide file tree
Showing 12 changed files with 221 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"deno.enable": true,
"deno.unstable": true
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Claudiu Ceia

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# dhash

```
Perceptual hashing is the use of a fingerprinting algorithm that produces a
snippet or fingerprint of various forms of multimedia.
```

A `dhash` implementation for Deno.

Based on the
["Kind of Like That"](https://www.hackerfactor.com/blog/?/archives/529-Kind-of-Like-That.html)
article by [Dr. Neal Krawetz](https://www.hackerfactor.com/about.php).

## Usage

You can compare dhash values by simply computing the Hamming distance between
them:

- A distance of 0 represents an identical, or very similar image
- A distance greater than 10 means that you're most likely dealing with a
different image
- A distance between 1 and 10 may indicate that you're dealing with variations
of the same base image

```ts
const [hash1, hash2] = await Promise.all([
dhash("./tests/dalle.png"),
dhash("./tests/dalle-copyright.png"),
]);

console.log(compare(hash1, hash2));
```

There are also two functions that you may use to display the fingerprint in a
non-hash form:

```ts
/**
* toAscii will return the fingerprint represented as a matrix of
* black/white pixels, represented by default through unicode low density
* and full blocks, ie:
*
* ██░░██████░░░░░░
* ░░██░░░░░░░░░░██
* ██░░░░░░████░░██
* ░░████░░████░░██
* ░░░░░░░░░░░░░░██
* ████████░░░░░░░░
* ░░░░░░██░░░░░░░░
* ░░░░░░░░░░░░░░░░
* /
toAscii(hash: string, chars: [string, string]): string
/**
* save will render the fingerprint as an 8x8px PNG file with black and
* white pixels, at the specified path.
*
* async save(hash: string, file: string): Promise<void>
*/
```

## License

MIT © [Claudiu Ceia](https://github.com/ClaudiuCeia)
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./src/dhash.ts";
93 changes: 93 additions & 0 deletions src/dhash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {
decode,
GIF,
Image,
} from "https://deno.land/x/[email protected]/mod.ts";
import { normalize, join } from "https://deno.land/[email protected]/path/mod.ts";

export const dhash = async (path: string) => {
const resolvedPath = join(Deno.cwd(), normalize(path));

let file;
try {
file = await Deno.readFile(resolvedPath);
} catch {
throw new Error(`Failed to open "${resolvedPath}"`);
}

const image = await decode(file);
if (image instanceof GIF) {
throw new Error("GIF not supported");
}

const grayscale = image.saturation(0);
const resized = grayscale.resize(9, 8);

const out = [];
for (let x = 1; x <= resized.height; x++) {
for (let y = 1; y <= resized.height; y++) {
const left = resized.getPixelAt(x, y);
const right = resized.getPixelAt(x + 1, y);
out.push(left < right ? 1 : 0);
}
}

return parseInt(out.join(""), 2).toString(16);
};

export const compare = (hash1: string, hash2: string) => {
if (hash1.length !== hash2.length) {
throw new Error(`
Hashes should be of the same length.
Got ${hash1} of ${hash1.length} and ${hash2} of ${hash2.length}
`);
}

let counter = 0;
for (const [idx, c] of hash1.split("").entries()) {
if (c !== hash2[idx]) {
counter++;
}
}

return counter;
};

export const toAscii = (hash: string, chars = ["░░", "██"]) => {
const bin = parseInt(hash, 16).toString(2).split("");
let counter = 0;
let row = "";
for (const bit of bin) {
row += bit === "0" ? chars[0] : chars[1];
counter++;
if (counter === 8) {
row += "\n";
counter = 0;
}
}
return row + chars[0];
};

export const save = async (hash: string, file: string) => {
const bin = parseInt(hash, 16).toString(2).split("");
const out = new Image(8, 8);

const white = Image.rgbToColor(255, 255, 255);
const black = Image.rgbToColor(0, 0, 0);

let column = 1;
let row = 1;
for (const bit of bin) {
console.log(column, row);
out.setPixelAt(column, row, parseInt(bit) === 1 ? black : white);
row++;
if (row === 9) {
column++;
row = 1;
}
}

out.setPixelAt(8, 8, white);
const enc = await out.encode();
await Deno.writeFile(`${file}.png`, enc);
};
Binary file added tests/dalle-bolder-copyright.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/dalle-copyright.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/dalle-crop.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/dalle-edited.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/dalle-stickers.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/dalle.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions tests/dhash.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import { compare, dhash, toAscii } from "../src/dhash.ts";

Deno.test("sample", async () => {
assertEquals(await dhash("./tests/dalle.png"), "5c20c6b680f80800");
});

Deno.test("comparison", async () => {
const res = await Promise.all([
dhash("./tests/dalle.png"),
dhash("./tests/dalle-copyright.png"),
dhash("./tests/dalle-bolder-copyright.jpeg"),
dhash("./tests/dalle-crop.jpeg"),
dhash("./tests/dalle-edited.jpeg"),
dhash("./tests/dalle-stickers.jpeg"),
]);

assertEquals(compare(res[0], res[1]), 0);
assertEquals(compare(res[0], res[2]), 5);
assertEquals(compare(res[0], res[3]), 14);
assertEquals(compare(res[0], res[4]), 7);
assertEquals(compare(res[0], res[5]), 6);
});

Deno.test("print", async () => {
const hash = await dhash("./tests/dalle.png");
assertEquals(
toAscii(hash),
`██░░██████░░░░░░
░░██░░░░░░░░░░██
██░░░░░░████░░██
░░████░░████░░██
░░░░░░░░░░░░░░██
████████░░░░░░░░
░░░░░░██░░░░░░░░
░░░░░░░░░░░░░░░░`.replaceAll(" ", "")
);
});

0 comments on commit a12bdcf

Please sign in to comment.