Skip to content

Instantly share code, notes, and snippets.

@jamiebicknell
Last active March 14, 2016 00:24
Show Gist options
  • Save jamiebicknell/9964033 to your computer and use it in GitHub Desktop.
Save jamiebicknell/9964033 to your computer and use it in GitHub Desktop.
<?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;
}
<?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