php实现图片对比
PHP实现图片对比的方法
使用GD库进行像素级对比
GD库是PHP内置的图像处理库,可以用于获取图片的像素信息并进行对比。以下是一个简单的实现方式:
function compareImages($imagePath1, $imagePath2) {
$image1 = imagecreatefromstring(file_get_contents($imagePath1));
$image2 = imagecreatefromstring(file_get_contents($imagePath2));
$width1 = imagesx($image1);
$height1 = imagesy($image1);
$width2 = imagesx($image2);
$height2 = imagesy($image2);
if ($width1 != $width2 || $height1 != $height2) {
return false;
}
$diff = 0;
for ($x = 0; $x < $width1; $x++) {
for ($y = 0; $y < $height1; $y++) {
$rgb1 = imagecolorat($image1, $x, $y);
$rgb2 = imagecolorat($image2, $x, $y);
$r1 = ($rgb1 >> 16) & 0xFF;
$g1 = ($rgb1 >> 8) & 0xFF;
$b1 = $rgb1 & 0xFF;
$r2 = ($rgb2 >> 16) & 0xFF;
$g2 = ($rgb2 >> 8) & 0xFF;
$b2 = $rgb2 & 0xFF;
$diff += abs($r1 - $r2) + abs($g1 - $g2) + abs($b1 - $b2);
}
}
$totalPixels = $width1 * $height1 * 3;
$similarity = 100 - (($diff / 255 / $totalPixels) * 100);
return $similarity;
}
使用哈希算法进行快速对比
哈希算法可以生成图片的指纹,适用于快速对比大量图片:
function getImageHash($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));
$pixels = [];
for ($x = 0; $x < $size; $x++) {
for ($y = 0; $y < $size; $y++) {
$rgb = imagecolorat($resized, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$pixels[] = ($r + $g + $b) / 3;
}
}
$avg = array_sum($pixels) / count($pixels);
$hash = '';
foreach ($pixels as $pixel) {
$hash .= ($pixel > $avg) ? '1' : '0';
}
return $hash;
}
function compareHashes($hash1, $hash2) {
$distance = 0;
for ($i = 0; $i < strlen($hash1); $i++) {
if ($hash1[$i] != $hash2[$i]) {
$distance++;
}
}
return (1 - ($distance / strlen($hash1))) * 100;
}
使用第三方库(如Intervention Image)
Intervention Image是一个流行的PHP图像处理库,可以简化图像处理操作:
require 'vendor/autoload.php';
use Intervention\Image\ImageManager;
$manager = new ImageManager(['driver' => 'gd']);
$image1 = $manager->make('image1.jpg')->resize(16, 16)->greyscale();
$image2 = $manager->make('image2.jpg')->resize(16, 16)->greyscale();
$diff = 0;
for ($x = 0; $x < 16; $x++) {
for ($y = 0; $y < 16; $y++) {
$diff += abs(
$image1->pickColor($x, $y, 'array')[0] -
$image2->pickColor($x, $y, 'array')[0]
);
}
}
$similarity = 100 - ($diff / (16 * 16 * 255)) * 100;
使用OpenCV扩展
对于更高级的图像处理需求,可以安装PHP的OpenCV扩展:
$src1 = \CV\imread("image1.jpg", \CV\IMREAD_COLOR);
$src2 = \CV\imread("image2.jpg", \CV\IMREAD_COLOR);
$diff = new \CV\Mat();
\CV\absdiff($src1, $src2, $diff);
$similarity = (1 - (\CV\sum($diff)[0] / (255 * $src1->rows * $src1->cols * 3))) * 100;
以上方法各有优缺点,像素级对比最准确但计算量大,哈希算法速度快但精度稍低,可根据实际需求选择合适的方法。







