Untitled
unknown
php
3 years ago
2.3 kB
10
No Index
/*
Heavily modified from a bicubic resampling function by an unknown author here: http://php.net/manual/en/function.imagecopyresampled.php#78049
this will scale down, desaturate and hash an image entirely in memory without the intermediate steps of altering the image resource and
re-reading pixel data, and return a perceptual hash for that image. Doesn't support rotation yet and is not actually as fast as it could be
due to the multiple looping.
*/
function fastPerceptualImageHash($res, $src_w, $src_h, $scale = 8) {
$hash = array();
$rX = $src_w / $scale;
$rY = $src_h / $scale;
$w = 0;
for ($y = 0; $y < $scale; $y++) {
$ow = $w; $w = round(($y + 1) * $rY);
$t = 0;
for ($x = 0; $x < $scale; $x++) {
$r = $g = $b = 0; $a = 0;
$ot = $t; $t = round(($x + 1) * $rX);
for ($u = 0; $u < ($w - $ow); $u++) {
for ($p = 0; $p < ($t - $ot); $p++) {
$rgb = imagecolorat($res, $ot + $p, $ow + $u);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$gs = floor((($r*0.299)+($g*0.587)+($b*0.114)));
$hash[$x][$y] = $gs;
}
}
}
}
// reset all the indexes.
$nhash = array();
$xnormal = 0;
foreach($hash as $xkey => $xval) {
foreach($hash[$xkey] as $ykey => $yval){
unset($hash[$xkey]);
$nhash[$xnormal][] = $yval;
}
$xnormal++;
}
// now hash (I really need to reduce the number of loops here.)
$phash = array();
for ($x = 0; $x < $scale; $x++) {
$avg = floor(array_sum($nhash[$x]) / count(array_filter($nhash[$x])));
for ($y = 0; $y < $scale; $y++) {
$rgb = $nhash[$x][$y];
if ($rgb > $avg) {
$phash[] = 1;
} else {
$phash[] = 0;
}
}
}
return $phash;
}
function HashAsString($hash, $hex = true){
$i = 0;
$bucket = null;
$return = null;
if ($hex == true) {
foreach($hash as $bit) {
$i++;
$bucket .= $bit;
if($i == 4) {
$return .= dechex(bindec($bucket));
$i = 0;
$bucket = null;
}
}
return $return;
}
return implode(null, $hash);
}
/* test -- */
$thumb = imageCreateFromJpeg('14267384s.jpg');
list($thumb_w , $thumb_h) = getImageSize('14267384s.jpg');
$phash = HashAsString( fastPerceptualImageHash($thumb, $thumb_w , $thumb_h) );
echo $phash;
/* -- test */
Editor is loading...