feat(hash):增加pHash图像感知哈希算法。

This commit is contained in:
徐涛
2023-07-12 15:26:49 +08:00
parent 29cebf455c
commit 2a2283ec4c
4 changed files with 69 additions and 1 deletions

48
hash/phash/phash.go Normal file
View File

@@ -0,0 +1,48 @@
// 提供图像感知哈希算法功能pHash
package phash
import (
"encoding/binary"
"encoding/hex"
"image"
"os"
"github.com/azr/phash"
)
// 计算图像的感知哈希值,并返回字节数组。
func Hash(image image.Image) []byte {
var bashBytes = make([]byte, 8)
hash := phash.DTC(image)
binary.BigEndian.PutUint64(bashBytes, hash)
return bashBytes
}
// 计算图像的感知哈希值,并返回十六进制字符串。
func HashHex(image image.Image) string {
return hex.EncodeToString(Hash(image))
}
// 计算指定图像文件的感知哈希值,并返回字节数组。
func HashFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
}
return Hash(img), nil
}
// 计算指定图像文件的感知哈希值,并返回十六进制字符串。
func HashFileHex(file string) (string, error) {
hash, err := HashFile(file)
if err != nil {
return "", err
}
return hex.EncodeToString(hash), nil
}