引言
图片相似度对比
感知哈希算法
class ImageHash
{
const FILENOTFOUND = '-1';
const FILEEXTNAMEILLEGAL = '-2';
private function __construct()
{
}
public static function run($src1, $src2)
{
static self $instance;
if (!$instance) $instance = new static();
if (!is_file($src1) || !is_file($src2)) exit(self::FILENOTFOUND);
$hash1 = $instance->getHashValue($src1);
$hash2 = $instance->getHashValue($src2);
if (strlen($hash1) != strlen($hash2)) return false;
$count = 0;
$len = strlen($hash1);
for ($i = 0; $i < $len; $i++)
if ($hash1[$i] != $hash2[$i]) $count++;
return $count;
}
private function getHashValue($file)
{
// 这里是获取哈希值的实现,具体代码省略
}
}
结果分析
自动匹配图片网址并下载保存
PHP正则匹配
<?php
header("Content-type:text/html;charset=utf-8");
$str = '<li><a href="https://www.mzitu.com/169017" target="blank"><img src="https://i.meizitu.net/thumbs/2019/02/16901710d01236.jpg" alt="肉感美女刘钰儿性感图片,丰满成熟女人味十足" width="236" height="354" /></a><span><a href="https://www.mzitu.com/169017" target="blank">肉感美女刘钰儿性感图片,丰满成熟女人味十足</a></span><span class="time">2019-02-14</span></li>';
preg_match_all('/<img src="([^"]+)" alt="[^"]+">/', $str, $matches);
foreach ($matches[1] as $match) {
$image_url = $match;
$image_name = basename($image_url);
file_put_contents("images/{$image_name}", file_get_contents($image_url));
}
?>
结果分析
从HTML中提取图片src路径
兼容性正则表达式
<?php
header("Content-type:text/html;charset=utf-8");
$str = '<li><a href="https://www.mzitu.com/169017" target="blank"><img src="https://i.meizitu.net/thumbs/2019/02/16901710d01236.jpg" alt="肉感美女刘钰儿性感图片,丰满成熟女人味十足" width="236" height="354" /></a><span><a href="https://www.mzitu.com/169017" target="blank">肉感美女刘钰儿性感图片,丰满成熟女人味十足</a></span><span class="time">2019-02-14</span></li>';
preg_match_all('/<img\s+[^>]*src="([^"]+)"[^>]*>/i', $str, $matches);
foreach ($matches[1] as $match) {
echo $match . "<br>";
}
?>
结果分析
总结
通过本文的学习,您已经掌握了使用PHP进行图像匹配的几个关键技巧。这些技巧可以帮助您在PHP项目中实现高效的图像识别和处理。在实际应用中,您可以根据具体需求选择合适的算法和工具,从而为您的项目带来更多的可能性。