-
Notifications
You must be signed in to change notification settings - Fork 11
/
hash_test.go
80 lines (61 loc) · 1.3 KB
/
hash_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.
package imghash
import (
"image"
"image/png"
"os"
"testing"
)
// Maximum Hamming-distance at which we consider images to be equal.
const MaxDistance = 3
func TestResize(t *testing.T) {
img, err := loadImg("testdata/gopher_large.png")
if err != nil {
t.Fatal(err)
}
img = resize(img, 32, 32)
err = saveImg(img, "testdata/gopher_32x32.png")
if err != nil {
t.Fatal(err)
}
}
func TestAverage(t *testing.T) {
a := getHash(t, Average, "testdata/gopher_large.png")
b := getHash(t, Average, "testdata/gopher_small.png")
dist := Distance(a, b)
if dist > MaxDistance {
t.Fatalf("Hash mismatch: 0x%x 0x%x %d\n", a, b, dist)
}
}
func getHash(t *testing.T, hf HashFunc, file string) uint64 {
img, err := loadImg(file)
if err != nil {
t.Fatal(err)
}
return hf(img)
}
func loadImg(file string) (image.Image, error) {
fd, err := os.Open(file)
if err != nil {
return nil, err
}
defer fd.Close()
img, _, err := image.Decode(fd)
if err != nil {
return nil, err
}
return img, nil
}
func saveImg(img image.Image, file string) error {
fd, err := os.Create(file)
if err != nil {
return err
}
defer fd.Close()
err = png.Encode(fd, img)
if err != nil {
return err
}
return nil
}