Php实现imagehash

PHP 实现 ImageHash
ImageHash 是一种图像指纹算法,用于快速比较图像的相似性。PHP 可以通过 GD 库或 Imagick 扩展实现该功能。以下是两种实现方式:
使用 GD 库实现
function imageHash($imagePath, $size = 8) {
// 读取图像
$image = imagecreatefromstring(file_get_contents($imagePath));
if (!$image) {
return false;
}
// 调整图像大小为 8x8
$resized = imagecreatetruecolor($size, $size);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $size, $size, imagesx($image), imagesy($image));
imagedestroy($image);
// 转换为灰度图
$grayscale = array();
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;
$grayscale[$y][$x] = ($r + $g + $b) / 3;
}
}
imagedestroy($resized);
// 计算平均灰度值
$total = 0;
foreach ($grayscale as $row) {
foreach ($row as $value) {
$total += $value;
}
}
$average = $total / ($size * $size);
// 生成哈希值
$hash = '';
foreach ($grayscale as $row) {
foreach ($row as $value) {
$hash .= ($value > $average) ? '1' : '0';
}
}
return $hash;
}
使用 Imagick 扩展实现
function imageHashImagick($imagePath, $size = 8) {
$imagick = new Imagick($imagePath);
if (!$imagick) {
return false;
}
// 调整图像大小并转换为灰度图
$imagick->resizeImage($size, $size, Imagick::FILTER_LANCZOS, 1);
$imagick->transformImageColorspace(Imagick::COLORSPACE_GRAY);
// 获取像素数据
$pixels = $imagick->exportImagePixels(0, 0, $size, $size, "RGB", Imagick::PIXEL_CHAR);
$grayscale = array();
for ($i = 0; $i < count($pixels); $i += 3) {
$r = $pixels[$i];
$g = $pixels[$i + 1];
$b = $pixels[$i + 2];
$grayscale[] = ($r + $g + $b) / 3;
}
// 计算平均灰度值
$average = array_sum($grayscale) / count($grayscale);
// 生成哈希值
$hash = '';
foreach ($grayscale as $value) {
$hash .= ($value > $average) ? '1' : '0';
}
return $hash;
}
比较哈希值
生成哈希值后,可以通过汉明距离(Hamming Distance)比较两个图像的相似性:
function hammingDistance($hash1, $hash2) {
if (strlen($hash1) !== strlen($hash2)) {
return false;
}
$distance = 0;
for ($i = 0; $i < strlen($hash1); $i++) {
if ($hash1[$i] !== $hash2[$i]) {
$distance++;
}
}
return $distance;
}
使用示例
$hash1 = imageHash('image1.jpg');
$hash2 = imageHash('image2.jpg');
$distance = hammingDistance($hash1, $hash2);
echo "Hash 1: $hash1\n";
echo "Hash 2: $hash2\n";
echo "Hamming Distance: $distance\n";
注意事项
- 哈希值长度通常为 64 位(8x8 图像),可以根据需求调整大小。
- 汉明距离越小,图像越相似。通常距离小于 5 表示图像非常相似。
- 确保服务器安装了 GD 库或 Imagick 扩展。


