Skip to content

Instantly share code, notes, and snippets.

@kleisauke
Created September 7, 2017 11:54
Show Gist options
  • Save kleisauke/ccdeb238af6c155aa42048de0132679d to your computer and use it in GitHub Desktop.
Save kleisauke/ccdeb238af6c155aa42048de0132679d to your computer and use it in GitHub Desktop.
Calculate a perceptual hash of an image
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips\Access;
use Jcupitt\Vips\Image;
use Jcupitt\Vips\Interpretation;
/**
* Calculate a perceptual hash of an image.
* Based on the dHash gradient method - see http://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html
*
* @param Image $image
*
* @return string
*/
function dHash(Image $image): string
{
/** @var Image $thumbnailImage */
$thumbnailImage = $image->thumbnail_image(9, [
'height' => 8,
'size' => 'force',
'auto_rotate' => false,
'linear' => false
])->colourspace(Interpretation::B_W);
$dHashImage = $thumbnailImage->copyMemory()->extract_band(0);
// Calculate dHash
$hash = 0;
$bit = 1;
for ($y = 0; $y < 8; $y++) {
// Get the pixel value for the leftmost pixel
$previous = $dHashImage->getpoint(0, $y)[0];
for ($x = 1; $x < 9; $x++) {
$current = $dHashImage->getpoint($x, $y)[0];
// Each hash bit is set based on whether the left pixel is brighter than the right pixel
if ($previous > $current) {
$hash |= $bit;
}
// Prepare the next loop
$bit <<= 1;
$previous = $current;
}
}
return sprintf('%016x', $hash);
}
$image = Image::newFromFile('img_0076.jpg', ['access' => Access::SEQUENTIAL]);
// 446a3af634aecaec
echo dHash($image).PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment