Php实现imagehash
实现图片哈希(ImageHash)的 PHP 方法
图片哈希(ImageHash)是一种用于快速比较图片相似度的技术,通常用于去重或相似图片搜索。以下是基于 PHP 实现图片哈希的几种方法:
平均哈希(Average Hash)
平均哈希通过计算图片的灰度平均值生成哈希值:
function averageHash($imagePath, $size = 8) {
$image = imagecreatefromstring(file_get_contents($imagePath));
$resized = imagecreatetruecolor($size, $size);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $size, $size, imagesx($image), imagesy($image));
imagedestroy($image);
$pixels = [];
for ($y = 0; $y < $size; $y++) {
for ($x = 0; $x < $size; $x++) {
$rgb = imagecolorat($resized, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$pixels[] = ($r + $g + $b) / 3;
}
}
imagedestroy($resized);
$avg = array_sum($pixels) / count($pixels);
$hash = '';
foreach ($pixels as $pixel) {
$hash .= ($pixel > $avg) ? '1' : '0';
}
return $hash;
}
说明:
- 将图片缩放到 8x8 尺寸。
- 转换为灰度并计算像素平均值。
- 生成二进制哈希字符串(1 表示高于平均值,0 表示低于平均值)。
感知哈希(Perceptual Hash)
感知哈希(pHash)使用离散余弦变换(DCT)提取低频特征:

function perceptualHash($imagePath, $size = 32, $hashSize = 8) {
$image = imagecreatefromstring(file_get_contents($imagePath));
$resized = imagecreatetruecolor($size, $size);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $size, $size, imagesx($image), imagesy($image));
imagedestroy($image);
$pixels = [];
for ($y = 0; $y < $size; $y++) {
for ($x = 0; $x < $size; $x++) {
$rgb = imagecolorat($resized, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$pixels[$y][$x] = ($r + $g + $b) / 3;
}
}
imagedestroy($resized);
// 计算 DCT(需自定义或使用库)
$dct = customDCT($pixels, $size);
$hash = '';
$avg = array_sum(array_slice($dct, 0, $hashSize * $hashSize)) / ($hashSize * $hashSize);
for ($i = 0; $i < $hashSize; $i++) {
for ($j = 0; $j < $hashSize; $j++) {
$hash .= ($dct[$i][$j] > $avg) ? '1' : '0';
}
}
return $hash;
}
说明:
- 缩放到 32x32 并转换为灰度。
- 应用 DCT 提取低频分量。
- 比较 DCT 矩阵左上部分(8x8)与平均值生成哈希。
差异哈希(Difference Hash)
差异哈希通过比较相邻像素生成哈希:

function differenceHash($imagePath, $size = 9) {
$image = imagecreatefromstring(file_get_contents($imagePath));
$resized = imagecreatetruecolor($size, $size - 1);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $size, $size - 1, imagesx($image), imagesy($image));
imagedestroy($image);
$hash = '';
for ($y = 0; $y < $size - 1; $y++) {
for ($x = 0; $x < $size; $x++) {
$rgb = imagecolorat($resized, $x, $y);
$nextRgb = imagecolorat($resized, $x, $y + 1);
$hash .= ($rgb > $nextRgb) ? '1' : '0';
}
}
imagedestroy($resized);
return $hash;
}
说明:
- 缩放到 9x8 尺寸(横向多一列)。
- 逐行比较相邻像素亮度差异生成哈希。
哈希比较方法
计算汉明距离(Hamming Distance)以比较哈希相似度:
function hammingDistance($hash1, $hash2) {
$distance = 0;
$length = min(strlen($hash1), strlen($hash2));
for ($i = 0; $i < $length; $i++) {
if ($hash1[$i] != $hash2[$i]) {
$distance++;
}
}
return $distance;
}
使用示例:
$hash1 = averageHash('image1.jpg');
$hash2 = averageHash('image2.jpg');
$similarity = hammingDistance($hash1, $hash2);
注意事项
- 依赖 GD 库处理图片,确保 PHP 已安装
gd扩展。 - DCT 实现较复杂,可考虑使用第三方库(如
php-dct)。 - 汉明距离越小,图片越相似(通常阈值 ≤ 5 表示高度相似)。

