Last active
March 14, 2016 00:24
-
-
Save jamiebicknell/9964033 to your computer and use it in GitHub Desktop.
dHash implementation in PHP based on http://blog.iconfinder.com/detecting-duplicate-images-using-python/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function dHash($file, $size = 8) | |
{ | |
$hash = ''; | |
list($w, $h, $t) = getimagesize($file); | |
$im = imagecreatetruecolor($size + 1, $size); | |
imagefilter($im, IMG_FILTER_GRAYSCALE); | |
switch($t) { | |
case 1: | |
$oi = imagecreatefromgif($file); | |
break; | |
case 2: | |
$oi = imagecreatefromjpeg($file); | |
break; | |
case 3: | |
$oi = imagecreatefrompng($file); | |
break; | |
} | |
imagecopyresampled($im, $oi, 0, 0, 0, 0, $size + 1, $size, $w, $h); | |
imagedestroy($oi); | |
for ($y = 0; $y < $size; $y++) { | |
$val = 0; | |
for ($x = 0; $x < $size; $x++) { | |
$curr = imagecolorat($im, $x, $y); | |
$next = imagecolorat($im, $x + 1, $y); | |
$val += ($curr > $next) ? pow(2, ($x + ($y * $size)) % 8) : 0; | |
} | |
$hash .= str_pad(dechex($val), 2, 0, STR_PAD_LEFT); | |
} | |
imagedestroy($im); | |
return $hash; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function dHashAlt($file) | |
{ | |
$hash = ''; | |
$size = 8; | |
list($w, $h, $t) = getimagesize($file); | |
$im = imagecreatetruecolor($size + 1, $size); | |
imagefilter($im, IMG_FILTER_GRAYSCALE); | |
switch($t) { | |
case 1: | |
$oi = imagecreatefromgif($file); | |
break; | |
case 2: | |
$oi = imagecreatefromjpeg($file); | |
break; | |
case 3: | |
$oi = imagecreatefrompng($file); | |
break; | |
} | |
imagecopyresampled($im, $oi, 0, 0, 0, 0, $size + 1, $size, $w, $h); | |
imagedestroy($oi); | |
for ($y = 0; $y < $size; $y++) { | |
$val = ''; | |
for ($x = 0; $x < $size; $x++) { | |
$curr = imagecolorat($im, $x, $y); | |
$next = imagecolorat($im, $x + 1, $y); | |
$val .= ($curr > $next) ? 1 : 0; | |
} | |
$hash .= str_pad(dechex(bindec($val)), 2, 0, STR_PAD_LEFT); | |
} | |
imagedestroy($im); | |
return $hash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment