Skip to content

Novis\Image\Image::HashKind

The kind of hash Image::hash returns.

Image::HashKind is declared in the class Novis\Image\Image.

A hash is a short fingerprint of what an image looks like. Two images that look the same have the same hash, or one with only a few different bits, even when their size or file format is different. Image::hashDistance counts the bits that differ between two hashes of the same kind.

  • Perceptual is 8 bytes. It looks at the large shapes of the image.
  • Difference is 16 bytes. It looks at where the image gets brighter or darker.
  • Average is 32 bytes. It looks at which parts are brighter than the image as a whole.

Each kind has its own length. hashDistance throws a LogicError when you compare two hashes of different kinds.

Examples

Find a changed copy

<?nvs
// Shows the length of each `Image::HashKind`, and how a hash finds a smaller copy of an image.
use Novis\Image\Image;
// A pattern of 4 by 4 grey pixels, made 64 by 64 pixels wide.
Image $photo = Image::fromRaw({
width: 4,
height: 4,
pixels: Core\Encoding::fromHex(
'202020ffe0e0e0ff606060ffa0a0a0ff'
. '909090ff303030ffd0d0d0ff505050ff'
. 'f0f0f0ff707070ff101010ffc0c0c0ff'
. '404040ffb0b0b0ff808080ff000000ff',
),
})->resized({ width: 64, height: 64 });
// The copy is the same image at 40 by 40 pixels. The other image is the photo mirrored.
tainted bytes $original = $photo->encode();
tainted bytes $copy = $photo->resized({ width: 40, height: 40 })->encode();
tainted bytes $other = $photo->flipped(Image::Axis::Horizontal)->encode();
array<Image::HashKind> $kinds = [Image::HashKind::Perceptual, Image::HashKind::Difference, Image::HashKind::Average];
// `hashDistance` counts the bits that differ. It is 0 for the copy with every kind.
foreach ($kinds as Image::HashKind $kind) {
bytes $hash = Image::hash($original, $kind);
uint $nearCopy = Image::hashDistance($hash, Image::hash($copy, $kind));
uint $notCopy = Image::hashDistance($hash, Image::hash($other, $kind));
echo Core\Bytes::length($hash), ' bytes, copy ', $nearCopy, ', other image ', $notCopy, "\n";
}
Output
8 bytes, copy 0, other image 34
16 bytes, copy 0, other image 28
32 bytes, copy 0, other image 128