ag_toolsbox/hash/phash/phash.go

49 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 提供图像感知哈希算法功能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
}