php判断两张图片是否相同

AndyYang| 阅读:4480 发表时间:2017-07-08 12:05:38 php
摘要:随着上传图片的增多,有的时候需要判断是否是相同的图片,然后进行删除。那么如何实现这个过程呢?

随着上传图片的增多,有的时候需要判断是否是相同的图片,然后进行删除。那么如何实现这个过程呢?

方法一:

sha1_file() 或者 md5_file()方法。

$file = "./img/1.jpg";
$file2 = "./img/2.jpg";
$gg = sha1_file($file);
$aa = sha1_file($file2);
if($aa == $gg) echo 'equation';

这两个方法只能判断两张完全相同的图片,包括文件的大小,尺寸,另外这个方法还可以用来判断文件。

方法二:

$filename = '1.jpg';
list($width, $height) = getimagesize($filename);
$img = imagecreatefromjpeg($filename);
$new_img = imagecreatetruecolor(8, 8);
imagecopyresampled($new_img, $img, 0, 0, 0, 0, 8, 8, $width, $height);
imagefilter($new_img, IMG_FILTER_GRAYSCALE);
$colors = array();
$sum = 0;

for ($i = 0; $i < 8; $i++) {
    for ($j = 0; $j < 8; $j++) {
        $color = imagecolorat($new_img, $i, $j) & 0xff;
        $sum += $color;
        $colors[] = $color;
    }
}

$avg = $sum / 64;
$hash = '';
$curr = '';
$count = 0;
foreach ($colors as $color) {
    if ($color > $avg) {
        $curr .= '1';
    } else {
        $curr .= '0';
    }
    $count++;
    if (!($count % 4)) {
        $hash .= dechex(bindec($curr));
        $curr = '';
    }
}
print $hash . "\n";

将图片缩小,再取得其hash值。然后进行比较。

此源码来自github,地址:https://gist.github.com/mncaudill/1326966

方法三:

use ImageHash\ImageHash;

$file = "./img/1.jpg";
$hasher = new ImageHash;
$hash = $hasher->hash($file);
var_dump($hash);

需要下载imagehash包,github地址:https://github.com/jenssegers/imagehash

这个源码包比上面的扩展功能更强大,还可以直接
$distance = $hasher->compare('path/to/image1.jpg', 'path/to/image2.jpg');
这样调用,感兴趣得可以下载demo研究下。

本文为AndyYang原创,转载请注明出处!
如果您觉得好,可以打赏作者:
如果您觉得累了,是否想看点美女养养眼:猛戳>>朋友帮
如果您觉得皮了,是否想来点神吐槽:猛戳>>iPhone查询中

已有0条评论

昵称:
邮箱:

  • 最新评论

iPhone查询中 - bbs.ipcxz.com 朋友帮 - www.pengyb.cn iPhone查询中 - bbs.ipcxz.com
反馈
微信订阅号