Skip to content

Commit

Permalink
adds hex serialization methods to ImageHash
Browse files Browse the repository at this point in the history
The ToString and FromString methods create a string representation
of an ImageHash, following the format:
`<first letter of type>:<hex representation of hash`
  • Loading branch information
brunoro authored and corona10 committed Nov 17, 2017
1 parent 22bcbf7 commit 40b64ed
Showing 1 changed file with 49 additions and 7 deletions.
56 changes: 49 additions & 7 deletions imagehash.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ package goimagehash

import (
"errors"
"fmt"
)

// hashKind describes the kinds of hash.
type hashKind int
// Kind describes the kinds of hash.
type Kind int

// ImageHash is a struct of hash computation.
type ImageHash struct {
hash uint64
kind hashKind
kind Kind
}

const (
// Unknown is a enum value of the unknown hash.
Unknown hashKind = iota
Unknown Kind = iota
// AHash is a enum value of the average hash.
AHash
//PHash is a enum value of the perceptual hash.
Expand All @@ -31,14 +32,14 @@ const (
)

// NewImageHash function creates a new image hash.
func NewImageHash(hash uint64, kind hashKind) *ImageHash {
func NewImageHash(hash uint64, kind Kind) *ImageHash {
return &ImageHash{hash: hash, kind: kind}
}

// Distance method returns a distance between two hashes.
func (h *ImageHash) Distance(other *ImageHash) (int, error) {
if h.GetKind() != other.GetKind() {
return -1, errors.New("Image hashes's kind should be identical.")
return -1, errors.New("Image hashes's kind should be identical")
}

diff := 0
Expand All @@ -60,11 +61,52 @@ func (h *ImageHash) GetHash() uint64 {
}

// GetKind method returns a kind of image hash.
func (h *ImageHash) GetKind() hashKind {
func (h *ImageHash) GetKind() Kind {
return h.kind
}

// Set method sets a bit of index.
func (h *ImageHash) Set(idx int) {
h.hash |= 1 << uint(idx)
}

const strFmt = "%v:%0x"

// FromString returns an image hash from a hex representation
func FromString(s string) (*ImageHash, error) {
var kindStr string
var hash uint64
_, err := fmt.Sscanf(s, strFmt, kindStr, hash)
if err != nil {
return nil, errors.New("Couldn't parse string " + s)
}

kind := Unknown
switch kindStr {
case "a":
kind = AHash
case "p":
kind = PHash
case "d":
kind = DHash
case "w":
kind = WHash
}
return NewImageHash(hash, kind), nil
}

// ToString returns a hex representation of the hash
func (h *ImageHash) ToString() string {
kindStr := ""
switch h.kind {
case AHash:
kindStr = "a"
case PHash:
kindStr = "p"
case DHash:
kindStr = "d"
case WHash:
kindStr = "w"
}
return fmt.Sprintf(strFmt, kindStr, h.hash)
}

0 comments on commit 40b64ed

Please sign in to comment.