ag_toolsbox/hash/phash/phash.go

50 lines
1.1 KiB
Go
Raw Permalink 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"
"fmt"
"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, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, fmt.Errorf("未能解码指定图像文件,%w", 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
}