Skip to content

Commit

Permalink
初始化
Browse files Browse the repository at this point in the history
  • Loading branch information
lujihong committed Jun 13, 2021
0 parents commit d7b5757
Show file tree
Hide file tree
Showing 29 changed files with 1,152 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/phpunit.xml export-ignore
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/vendor
composer.lock
.phpunit.result.cache
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Jens Segers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
101 changes: 101 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
ImageHash
=========
> A perceptual hash is a fingerprint of a multimedia file derived from various features from its content. Unlike cryptographic hash functions which rely on the avalanche effect of small changes in input leading to drastic changes in the output, perceptual hashes are "close" to one another if the features are similar.
Perceptual hashes are a different concept compared to cryptographic hash functions like MD5 and SHA1. With cryptographic hashes, the hash values are random. The data used to generate the hash acts like a random seed, so the same data will generate the same result, but different data will create different results. Comparing two SHA1 hash values really only tells you two things. If the hashes are different, then the data is different. And if the hashes are the same, then the data is likely the same. In contrast, perceptual hashes can be compared -- giving you a sense of similarity between the two data sets.

This code was inspired/based on:
- https://github.com/kennethrapp/phasher
- http://www.phash.org
- http://blockhash.io
- http://www.hackerfactor.com/blog/?/archives/529-Kind-of-Like-That.html
- http://www.hackerfactor.com/blog/?/archives/432-Looks-Like-It.html
- http://blog.iconfinder.com/detecting-duplicate-images-using-python

Requirements
------------

- PHP 7.1 or higher
- The [gd](http://php.net/manual/en/book.image.php) or [imagick](http://php.net/manual/en/book.imagick.php) extension
- Optionally, install the [GMP](http://php.net/manual/en/book.gmp.php) extension for faster fingerprint comparisons

Installation
------------

*This package has not reached a stable version yet, backwards compatibility may be broken between 0.x releases. Make sure to lock your version if you intend to use this in production!*

Install using composer:

composer require lujihong/image-hash

Usage
-----

The library comes with 4 built-in hashing implementations:

- `Lujihong\ImageHash\Implementations\AverageHash` - Hash based the average image color
- `Lujihong\ImageHash\Implementations\DifferenceHash` - Hash based on the previous pixel
- `Lujihong\ImageHash\Implementations\BlockHash` - Hash based on blockhash.io **Still under development**
- `Lujihong\ImageHash\Implementations\PerceptualHash` - The original pHash **Still under development**

Choose one of these implementations. If you don't know which one to use, try the `DifferenceHash` implementation. Some implementations allow some configuration, be sure to check the constructor.

```php
use Lujihong\ImageHash\ImageHash;
use Lujihong\ImageHash\Implementations\DifferenceHash;

$hasher = new ImageHash(new DifferenceHash());
$hash = $hasher->hash('path/to/image.jpg');

echo $hash;
// or
echo $hash->toHex();
```

The resulting `Hash` object, is a hexadecimal image fingerprint that can be stored in your database once calculated. The hamming distance is used to compare two image fingerprints for similarities. Low distance values will indicate that the images are similar or the same, high distance values indicate that the images are different. Use the following method to detect if images are similar or not:

```php
$distance = $hasher->distance($hash1, $hash2);
// or
$distance = $hash1->distance($hash2);
```

Equal images will not always have a distance of 0, so you will need to decide at which distance you will evaluate images as equal. For the image set that I tested, a max distance of 5 was acceptable. But this will depend on the implementation, the images and the number of images. For example; when comparing a small set of images, a lower maximum distances should be acceptable as the chances of false positives are quite low. If however you are comparing a large amount of images, 5 might already be too much.

The `Hash` object can return the internal binary hash in a couple of different format:

```php
echo $hash->toHex(); // 7878787c7c707c3c
echo $hash->toBin(); // 0111100001111000011110000111110001111100011100000111110000111100
echo $hash->toInt(); // 8680820757815655484
echo $hash->toBytes(); // "\x0F\x07ƒƒ\x03\x0F\x07\x00"
```

Choose your preference for storing your hashes in your database. If you want to reconstruct a `Hash` object from a previous calculated value, use:

```php
$hash = Hash::fromHex('7878787c7c707c3c');
$hash = Hash::fromBin('0111100001111000011110000111110001111100011100000111110000111100');
$hash = Hash::fromInt('8680820757815655484');
```

Demo
----

These images are similar:

![Equals1](https://raw.githubusercontent.com/Lujihong/imagehash/master/tests/images/forest/forest-high.jpg)
![Equals2](https://raw.githubusercontent.com/Lujihong/imagehash/master/tests/images/forest/forest-copyright.jpg)

Image 1 hash: 3c3e0e1a3a1e1e1e (0011110000111110000011100001101000111010000111100001111000011110)
Image 2 hash: 3c3e0e3e3e1e1e1e (0011110000111110000011100011111000111110000111100001111000011110)
Hamming distance: 3

These images are different:

![Equals1](https://raw.githubusercontent.com/Lujihong/imagehash/master/tests/images/office/tumblr_ndyfnr7lk21tubinno1_1280.jpg)
![Equals2](https://raw.githubusercontent.com/Lujihong/imagehash/master/tests/images/office/tumblr_ndyfq386o41tubinno1_1280.jpg)

Image 1 hash: 69684858535b7575 (0010100010101000101010001010100010101011001010110101011100110111)
Image 2 hash: e1e1e2a7bbaf6faf (0111000011110000111100101101001101011011011101010011010101001111)
Hamming distance: 32
34 changes: 34 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "lujihong/image-hash",
"description": "Perceptual image hashing for PHP",
"keywords": [
"imagehash",
"perceptual",
"hash",
"dhash",
"ahash",
"phash",
"image hash"
],
"homepage": "https://github.com/lujihong/imagehash",
"license": "MIT",
"require": {
"php": "^7.1|^8.0",
"intervention/image": "^2.4",
"phpseclib/phpseclib": "^2.0|^3.0"
},
"require-dev": {
"phpunit/phpunit": "^7|^8|^9",
"php-coveralls/php-coveralls": "^2.0"
},
"suggest": {
"ext-gmp": "GMP results in faster comparisons",
"ext-gd": "GD or ImageMagick is required",
"ext-imagick": "GD or ImageMagick is required"
},
"autoload": {
"psr-4": {
"Lujihong\\ImageHash\\": "src"
}
}
}
30 changes: 30 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
version: '3'

services:

gd:
build:
context: .
dockerfile: docker/gd.Dockerfile
volumes:
- .:/code
working_dir: /code
command: ./vendor/bin/phpunit

imagick:
build:
context: .
dockerfile: docker/imagick.Dockerfile
volumes:
- .:/code
working_dir: /code
command: ./vendor/bin/phpunit

gmp:
build:
context: .
dockerfile: docker/gmp.Dockerfile
volumes:
- .:/code
working_dir: /code
command: ./vendor/bin/phpunit
11 changes: 11 additions & 0 deletions docker/gd.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
ARG PHP_VERSION=7.2
ARG COMPOSER_VERSION=1.8

FROM composer:${COMPOSER_VERSION}
FROM php:${PHP_VERSION}-cli

RUN apt-get update && \
apt-get install libpng-dev libjpeg-dev --no-install-recommends -qy && \
rm -rf /var/lib/apt/lists/* && \
docker-php-ext-configure gd --enable-gd-native-ttf --with-png-dir=/usr/include --with-jpeg-dir=/usr/include && \
docker-php-ext-install -j$(nproc) gd
12 changes: 12 additions & 0 deletions docker/gmp.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ARG PHP_VERSION=7.2
ARG COMPOSER_VERSION=1.8

FROM composer:${COMPOSER_VERSION}
FROM php:${PHP_VERSION}-cli

RUN apt-get update && \
apt-get install libgmp-dev libpng-dev libjpeg-dev --no-install-recommends -qy && \
rm -rf /var/lib/apt/lists/* && \
ln -s /usr/include/x86_64-linux-gnu/gmp.h /usr/include/gmp.h && \
docker-php-ext-configure gd --enable-gd-native-ttf --with-png-dir=/usr/include --with-jpeg-dir=/usr/include && \
docker-php-ext-install -j$(nproc) gmp gd
11 changes: 11 additions & 0 deletions docker/imagick.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
ARG PHP_VERSION=7.2
ARG COMPOSER_VERSION=1.8

FROM composer:${COMPOSER_VERSION}
FROM php:${PHP_VERSION}-cli

RUN apt-get update && \
apt-get install libmagickwand-dev --no-install-recommends -qy && \
rm -rf /var/lib/apt/lists/* && \
ln -s /usr/include/x86_64-linux-gnu/gmp.h /usr/include/gmp.h && \
pecl install imagick && docker-php-ext-enable imagick
21 changes: 21 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="pHash">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist addUncoveredFilesFromWhitelist="false">
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
94 changes: 94 additions & 0 deletions src/Hash.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace Lujihong\ImageHash;

use JsonSerializable;
use phpseclib\Math\BigInteger;

class Hash implements JsonSerializable
{
/**
* @var BigInteger
*/
protected $value;

private function __construct(BigInteger $value)
{
$this->value = $value;
}

public static function fromHex(string $hex): self
{
return new self(new BigInteger($hex, 16));
}

/**
* @param string|array $bits
* @return self
*/
public static function fromBits($bits): self
{
if (is_array($bits)) {
$bits = implode('', $bits);
}

return new self(new BigInteger($bits, 2));
}

public static function fromInt(int $int): self
{
return new self(new BigInteger($int, 10));
}

public function toHex(): string
{
return $this->value->toHex();
}

public function toBytes(): string
{
return $this->value->toBytes();
}

public function toBits(): string
{
return $this->value->toBits();
}

public function toInt(): int
{
return hexdec($this->toHex());
}

public function distance(Hash $hash): int
{
if (extension_loaded('gmp')) {
return gmp_hamdist('0x' . $this->toHex(), '0x' . $hash->toHex());
}

$bits1 = $this->toBits();
$bits2 = $hash->toBits();
$length = max(strlen($bits1), strlen($bits2));

// Add leading zeros so the bit strings are the same length.
$bits1 = str_pad($bits1, $length, '0', STR_PAD_LEFT);
$bits2 = str_pad($bits2, $length, '0', STR_PAD_LEFT);

return count(array_diff_assoc(str_split($bits1), str_split($bits2)));
}

public function equals(Hash $hash): bool
{
return $this->toHex() === $hash->toHex();
}

public function __toString(): string
{
return $this->toHex();
}

public function jsonSerialize(): string
{
return (string)$this;
}
}
Loading

0 comments on commit d7b5757

Please sign in to comment.