Skip to content

Instantly share code, notes, and snippets.

@daif
Last active September 30, 2017 09:59
Show Gist options
  • Save daif/bcc49e829b5d41ebedf07b01cdee06aa to your computer and use it in GitHub Desktop.
Save daif/bcc49e829b5d41ebedf07b01cdee06aa to your computer and use it in GitHub Desktop.
a simple image hashing algorithm
<?php
function imageHash($image_file) {
// check if the file is existed and is readable
if(file_exists($image_file) && is_readable($image_file)) {
return false;
}
// get image dimensions
list($width, $height) = getimagesize($image_file);
// new dimensions
$newwidth = 100;
$newheight = 100;
$img = imagecreatefromjpeg($image_file);
$dst = imagecreatetruecolor($newwidth, $newheight);
// resize image to 100x100
imagecopyresampled($dst, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// converts the image into grayscale
imagefilter($dst, IMG_FILTER_GRAYSCALE);
$color_arr = [];
// scan image from min x-coordinate and min y-coordinate to max x-coordinate and y-coordinate
for ($width=5;$width<=imagesx($dst)-5;$width++) {
for ($height=5;$height<=imagesy($dst)-5;$height++) {
// get RGB color index
$rgb = imagecolorat($dst, $width, $height);
// convert value to integer
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// get the value of RGB color for all pixels and round the value to get the color index average.
$rounded = round((($r+$g+$b)/3) / 10) * 10;
// increase the rounded index by one each time
$color_arr[$rounded] +=1;
}
}
// try to ignore abnormal values
foreach ($color_arr as $color => $count) {
$count = round($count / 30) * 30;
// ignore color index that count less than 40 or big than 1000
if($count>40 && $count<1000) {
$color_arr[$color]=$count;
} else {
unset($color_arr[$color]);
}
}
// use md5 to create hash from the array
$hash = md5(implode('', array_keys($color_arr)).implode('', array_values($color_arr)));
return $hash;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment