Skip to content

Instantly share code, notes, and snippets.

@kleisauke
Created September 7, 2017 11:55
Show Gist options
  • Save kleisauke/7c43c2a265780ad6ac08727f52a6ffeb to your computer and use it in GitHub Desktop.
Save kleisauke/7c43c2a265780ad6ac08727f52a6ffeb 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->extract_band(0)->writeToMemory();
// Calculate dHash
$hash = 0;
$bit = 1;
for ($y = 0; $y < 8; $y++) {
for ($x = 0; $x < 8; $x++) {
$left = $dHashImage[($x * 8) + $y];
$right = $dHashImage[($x * 8) + $y + 1];
// Each hash bit is set based on whether the left pixel is brighter than the right pixel
if ($left > $right) {
$hash |= $bit;
}
// Prepare the next loop
$bit <<= 1;
}
}
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