feat(hash):增加pHash图像感知哈希算法。
This commit is contained in:
		
							
								
								
									
										48
									
								
								hash/phash/phash.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										48
									
								
								hash/phash/phash.go
									
									
									
									
									
										Normal 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
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user