网上一段计算图片 pHash(perceptual hash)的 php 代码,我把它更改了一下:
function phash(file)
{
$resource=imagecreatefromstring(file_get_contents($file));
$size=8;
$width = $size + 1;
$heigth = $size;
$resized = imagecreatetruecolor($width, $heigth);
imagecopyresampled($resized, $resource, 0, 0, 0, 0, $width, $heigth, imagesx($resource), imagesy($resource));
$hash = 0;
$one = 1;
for ($y = 0; $y < $heigth; $y++) {
$rgb = imagecolorsforindex($resized, imagecolorat($resized, 0, $y));
$left = floor(($rgb['red'] + $rgb['green'] + $rgb['blue']) / 3);
for ($x = 1; $x < $width; $x++) {
$rgb = imagecolorsforindex($resized, imagecolorat($resized, $x, $y));
$right = floor(($rgb['red'] + $rgb['green'] + $rgb['blue']) / 3);
if ($left > $right) {
$hash |= $one;
}
$left = $right;
$one = $one << 1;
}
}
imagedestroy($resized);
return dechex($hash);
}
不知道 pHash 的同学可以先 Google 一下概念,上面的代码是我微改后的代码,原理貌似还是很好理解,就是把一张图片压缩成 8x8 的图片并计算 64 个像素灰度平均值,然后遍历每个像素和这个平均值比较,生成一个布尔值最后返回这个值的 16 进制,但是目前在两种环境下测试:
- centos 6.5 32 位 php5.5 的环境下,生成的 pHash 是 8 位,比如:a0e1c3c1
- centos 7.0 64 位 php7.1 的环境下,生成的 pHash 是 16 位,比如:fee6ccf4b133a9e9 这是何解
因为源代码里面有点不懂:
- $hash |= $one;
- $one = $one << 1; 这两行代码什么意思?特别是“|=”这个符号半天都 Google 不到什么意思?求好心 V 友解疑释惑以下,不胜感激