4 stable releases

new 1.2.0 Apr 26, 2024
1.1.1 Apr 10, 2024
1.1.0 Apr 7, 2024
1.0.0 Apr 1, 2024

#149 in Images

Download history 209/week @ 2024-04-01 163/week @ 2024-04-08 1/week @ 2024-04-15 163/week @ 2024-04-22

536 downloads per month

Custom license

800KB
950 lines

imghash - Image Hashing for Rust

Crates.io Version Main

imghash is a crate that allows you to generate different hashes for images. The following hashes can be generated using this crate:

Usage

There are multiple ways how to utilize imghash depending on your use case.

Quickstart

The easy way to use imghash is by using the provided utility functions which assume reasonable defaults.

use imghash::{average_hash, difference_hash, perceptual_hash};

let path = Path::new("path/to/my/image");

let average = average_hash(path);
let difference = difference_hash(path);
let perceptual = perceptual_hash(path);

Each of these functions return a Result<ImageHash, String>-type. The ImageHash object is essentially a container for the encoded bit matrix of the image (learn more here). The ImageHash can be encoded into hexadecimal string by calling the encode method:

let res: String = hash.encode();

Custom Hashers

If you need more flexibility, for example getting a larger bit matrix, you can use a custom Hasher instance.

For each hash type the crate provides a custom hasher, here for the example we will use the AverageHasher:

use imghash::{average::AverageHasher};

let path = Path::new("path/to/my/image");

let hasher = AverageHasher {
  width: 10,
  height: 10,
};

let hash = hasher.hash_from_path(path);

Hasher instances also allow you to create hashes for already loaded images:

let img = ImageReader::open(...);

let hasher = AverageHasher { ..Default::default() };

let hash = hasher.hash_from_img(&img);

Each hasher also implements the Default-trait, allowing you to create them with their default values:

let hasher = AverageHasher { ..Default::default() };

Python Compatability

One of the major factors that drove development of this crate was the need to have a hasher implementation that matches the imagehash-package for Python.

A future Python-wrapper for this crate is already on the roadmap, to allow a replacement of the imagehash-package.

As of Version 1.2.0 all hashes generated by this crate should match hashes generated by imagehash - however it is not guaranteed for any other package or crate. Previous version of this crate (<1.2.0) were not generated the same hashes. To make sure you are generating the same hashes, set the color space of the hasher to REC601, as this will make sure the same grayscaling as Pillow is used - this is configured as the default.

Dependencies

~14MB
~85K SLoC