/
pic.go
95 lines (81 loc) · 1.79 KB
/
pic.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"github.com/afajl/log"
"hash/adler32"
"image"
_ "image/png"
"io"
"os"
"path/filepath"
)
type Pic struct {
originalPath string
id string
isWide bool
height, width int
}
func NewPic(path string) (*Pic, error) {
pic := new(Pic)
pic.originalPath = path
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
pic.id = picHash(f)
f.Seek(0, 0)
pic.height, pic.width, err = picSize(f)
if err != nil {
return nil, err
}
pic.isWide = pic.height < pic.width
return pic, err
}
func picHash(picf io.Reader) string {
hash := adler32.New()
if _, err := io.Copy(hash, picf); err != nil {
log.Panic(err)
}
return fmt.Sprintf("%x", hash.Sum32())
}
func picSize(picf io.Reader) (int, int, error) {
m, _, err := image.Decode(picf)
if err != nil {
return 0, 0, err
}
r := m.Bounds()
return r.Dy(), r.Dx(), nil
}
/*func picIsWide(pic *Pic, portraitRatio float64) (isWide bool, err error) {*/
/*landscapeRatio := portraitRatio / 2*/
/*ratio := float64(pic.height) / float64(pic.width)*/
/*if math.Mod(ratio, portraitRatio) < 0.01 {*/
/*isWide = false*/
/*} else if math.Mod(ratio, landscapeRatio) < 0.01 {*/
/*isWide = true*/
/*} else {*/
/*err = fmt.Errorf("pic ratio is wrong: w:%v h:%v, ratio:%v", pic.height, pic.width, ratio)*/
/*}*/
/*return*/
/*}*/
func findPic(name string, pics []*Pic) *Pic {
for _, pic := range pics {
if filepath.Base(pic.originalPath) == name {
return pic
}
}
return nil
}
func namesToPics(picnames []string, pics []*Pic) (res []*Pic, err error) {
res = make([]*Pic, 0, len(picnames))
for _, picname := range picnames {
pic := findPic(picname, pics)
if pic == nil {
err = fmt.Errorf("no pic found named %q", picname)
return
}
res = append(res, pic)
}
return
}