-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimage.go
99 lines (81 loc) · 2.01 KB
/
image.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
package main
import (
"bytes"
"image"
"image/png"
"os"
"time"
"github.com/go-redis/redis"
"github.com/vmihailenco/msgpack"
"github.com/go-redis/cache"
dither "github.com/esimov/dithergo"
resize "github.com/nfnt/resize"
)
var stucki = dither.Dither{
"Stucki",
dither.Settings{
[][]float32{
[]float32{0.0, 0.0, 0.0, 8.0 / 42.0, 4.0 / 42.0},
[]float32{2.0 / 42.0, 4.0 / 42.0, 8.0 / 42.0, 4.0 / 42.0, 2.0 / 42.0},
[]float32{1.0 / 42.0, 2.0 / 42.0, 4.0 / 42.0, 2.0 / 42.0, 1.0 / 42.0},
},
},
}
// Load an image (PNG or JPG), resize, convert to monochrome and return as PNG
func ConvertImageMono(in []byte, width uint) ([]byte, error) {
orig, _, err := image.Decode(bytes.NewReader(in))
if err != nil {
return nil, err
}
img := resize.Resize(width, 0, orig, resize.Lanczos3)
imgmono := stucki.Monochrome(img, 1.0)
var out bytes.Buffer
png.Encode(&out, imgmono)
return out.Bytes(), nil
}
// SaveImagePNG save an image to a PNG file.
func SaveImagePNG(img image.Image, path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
png.Encode(f, img)
return nil
}
type ImageCache struct {
cache *cache.Codec
}
func NewImageCache(redisUrl string) (*ImageCache, error) {
opts, err := redis.ParseURL(redisUrl)
if err != nil {
return nil, err
}
inst := redis.NewClient(opts)
if cmd := inst.Ping(); cmd.Err() != nil {
return nil, err
}
cache := &cache.Codec{
Redis: inst,
Marshal: func(v interface{}) ([]byte, error) {
return msgpack.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return msgpack.Unmarshal(b, v)
},
}
return &ImageCache{cache: cache}, nil
}
func (ic *ImageCache) Set(key string, object interface{}, expiration time.Duration) error {
return ic.cache.Set(&cache.Item{
Key: key,
Object: object,
Expiration: expiration,
})
}
func (ic *ImageCache) Get(key string, object interface{}) error {
return ic.cache.Get(key, &object)
}
func (ic *ImageCache) Del(key string) error {
return ic.cache.Delete(key)
}