Skip to content

Instantly share code, notes, and snippets.

@m8rge
Forked from mncaudill/similar.php
Last active August 29, 2015 14:21
Show Gist options
  • Save m8rge/c65b51420380443e603a to your computer and use it in GitHub Desktop.
Save m8rge/c65b51420380443e603a to your computer and use it in GitHub Desktop.
Image similarity algorithm
<?php
# Algorithm found here: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
class HashBuilder
{
private $buf;
function __construct()
{
$this->buf = imagecreatetruecolor(8, 8);
}
function __destruct()
{
imagedestroy($this->buf);
}
public function hash($imageData)
{
$img = imagecreatefromstring($imageData);
imagecopyresampled($this->buf, $img, 0, 0, 0, 0, 8, 8, imagesx($img), imagesy($img));
imagedestroy($img);
imagefilter($this->buf, IMG_FILTER_GRAYSCALE);
$colors = array();
for ($i = 0; $i < 8; $i++) {
for ($j = 0; $j < 8; $j++) {
$colors[] = imagecolorat($this->buf, $i, $j) & 0xFF;
}
}
$avg = array_sum($colors) / 64;
$bin = '';
foreach ($colors as $color) {
$bin .= $color > $avg ? '1' : '0';
}
return base_convert($bin, 2, 16);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment