-
Notifications
You must be signed in to change notification settings - Fork 21
/
thumbs.go
118 lines (96 loc) · 2.4 KB
/
thumbs.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"flag"
"log"
"os"
"path/filepath"
"strings"
"image"
"image/color"
"image/jpeg"
"image/png"
"golang.org/x/image/draw"
)
var (
colnum = flag.Int("c", 8, "columns for images")
cellsize = flag.Int("s", 128, "cell width/height")
output = flag.String("o", ".thumb", "output file")
cell = 0
)
func openimg(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
m, _, err := image.Decode(file)
return m, err
}
func savejpg(path string, m image.Image) error {
os.MkdirAll(filepath.Dir(path), 0755)
path = path[:len(path)-len(filepath.Ext(path))] + ".jpg"
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return jpeg.Encode(file, m, &jpeg.Options{Quality: 90})
}
func savepng(path string, m image.Image) error {
os.MkdirAll(filepath.Dir(path), 0755)
path = path[:len(path)-len(filepath.Ext(path))] + ".png"
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return png.Encode(file, m)
}
func process(dir, path string) error {
m, err := openimg(filepath.Join(dir, path))
if err != nil {
return err
}
size := m.Bounds().Size()
if size.X > size.Y {
size.X, size.Y = cell, size.Y*cell/size.X
} else {
size.X, size.Y = size.X*cell/size.Y, cell
}
dst := image.NewRGBA(image.Rect(0, 0, size.X, size.Y))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.RGBA{0xFF, 0xFF, 0xFF, 0xFF}), image.Point{}, draw.Src)
draw.CatmullRom.Scale(dst, dst.Bounds(), m, m.Bounds(), draw.Over, nil)
log.Println(filepath.Join(*output, path))
return savejpg(filepath.Join(*output, path), dst)
}
func main() {
flag.Parse()
cell = *cellsize
dir := flag.Arg(0)
if dir == "" {
dir = "."
}
files := []string{}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() && filepath.HasPrefix(path, ".") && path != "." && path != ".." {
return filepath.SkipDir
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".png" && filepath.Ext(path) != ".jpg" {
return nil
}
if strings.Contains(path, ".sketch.") {
return nil
}
files = append(files, filepath.Join(dir, path))
return process(dir, path)
})
if err != nil {
log.Println(err)
}
}