/
thumbnail.go
85 lines (74 loc) · 1.6 KB
/
thumbnail.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
package worker
import (
"crypto/md5"
"encoding/hex"
"fmt"
"image"
"image/jpeg"
"image/png"
"log"
"os"
"path/filepath"
"runtime"
"github.com/nfnt/resize"
)
var ThumbnailChan = make(chan string, 500)
func GetMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
func generateThumbnail(path string, size uint, prefix string) {
cachePath := fmt.Sprintf("cache/%s%s.jpg", prefix, GetMD5Hash(path))
if _, err := os.Stat(cachePath); err == nil {
return
}
os.MkdirAll("cache", os.ModePerm)
file, err := os.Open(path)
if err != nil {
//fmt.Println(path)
return
}
// decode jpeg into image.Image
extension := filepath.Ext(path)
var img image.Image
var img_err error
switch extension {
case ".jpg":
img, img_err = jpeg.Decode(file)
case ".png":
img, img_err = png.Decode(file)
}
if img_err != nil {
return
}
file.Close()
// resize to width 1000 using Lanczos resampling
// and preserve aspect ratio
log.Printf("Creating Thumbnail for user: %s", path)
m := resize.Resize(size, 0, img, resize.Bilinear)
out, err := os.Create(cachePath)
if err != nil {
log.Fatal(err)
}
defer out.Close()
jpeg.Encode(out, m, nil)
}
func MakeThumbnail(path string) {
generateThumbnail(path, 400, "")
}
func MakeLargeThumbnail(path string) {
generateThumbnail(path, 1200, "large_")
}
func worker(id int, jobs <-chan string) {
log.Printf("Strarting Worker: %d \n", id)
for j := range jobs {
MakeThumbnail(j)
MakeLargeThumbnail(j)
}
}
func StartWorkers() {
for w := 1; w <= runtime.NumCPU(); w++ {
go worker(w, ThumbnailChan)
}
}