diff --git a/AUTHORS b/AUTHORS index 844377c..12fdf25 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,2 +1,3 @@ ---AUTHORS--- [Dong-hee Na](https://github.com/corona10/) donghee.na92@gmail.com +[Gustavo Brunoro](https://github.com/brunoro/) git@hitnail.net diff --git a/imagehash.go b/imagehash.go index 5ffbc8b..785a34b 100644 --- a/imagehash.go +++ b/imagehash.go @@ -70,13 +70,13 @@ func (h *ImageHash) Set(idx int) { h.hash |= 1 << uint(idx) } -const strFmt = "%v:%0x" +const strFmt = "%1s:%016x" -// FromString returns an image hash from a hex representation -func FromString(s string) (*ImageHash, error) { +// ImageHashFromString returns an image hash from a hex representation +func ImageHashFromString(s string) (*ImageHash, error) { var kindStr string var hash uint64 - _, err := fmt.Sscanf(s, strFmt, kindStr, hash) + _, err := fmt.Sscanf(s, strFmt, &kindStr, &hash) if err != nil { return nil, errors.New("Couldn't parse string " + s) } diff --git a/imagehash_test.go b/imagehash_test.go index 77021a7..6c8c0fd 100644 --- a/imagehash_test.go +++ b/imagehash_test.go @@ -6,6 +6,11 @@ package goimagehash import ( "errors" + "image" + _ "image/jpeg" + "os" + "reflect" + "runtime" "testing" ) @@ -41,11 +46,58 @@ func TestNewImageHash(t *testing.T) { dis, err := hash1.Distance(hash2) if dis != tt.distance { - t.Errorf("Distance between %v and %v expected as %d but got %d.", data1, data2, tt.distance, dis) + t.Errorf("Distance between %v and %v expected as %d but got %d", data1, data2, tt.distance, dis) } if err != nil && err.Error() != tt.err.Error() { - t.Errorf("Expected err %s, actual %s.", tt.err, err) + t.Errorf("Expected err %s, actual %s", tt.err, err) + } + } +} + +func TestSerialization(t *testing.T) { + checkErr := func(err error) { + if err != nil { + t.Errorf("%v", err) } } + methods := []func(img image.Image) (*ImageHash, error){ + AverageHash, PerceptionHash, DifferenceHash, + } + examples := []string{ + "_examples/sample1.jpg", "_examples/sample2.jpg", "_examples/sample3.jpg", "_examples/sample4.jpg", + } + + for _, ex := range examples { + file, err := os.Open(ex) + checkErr(err) + + defer file.Close() + + img, _, err := image.Decode(file) + checkErr(err) + + for _, method := range methods { + methodStr := runtime.FuncForPC(reflect.ValueOf(method).Pointer()).Name() + + hash, err := method(img) + checkErr(err) + + hex := hash.ToString() + // len(kind) == 1, len(":") == 1, len(hash) == 16 + if len(hex) != 18 { + t.Errorf("Got invalid hex string '%v'; %v of '%v'", hex, methodStr, ex) + } + + reHash, err := ImageHashFromString(hex) + checkErr(err) + + distance, err := hash.Distance(reHash) + checkErr(err) + + if distance != 0 { + t.Errorf("Original and unserialized objects should be identical, got distance=%v; %v of '%v'", distance, methodStr, ex) + } + } + } }