-
Notifications
You must be signed in to change notification settings - Fork 5
/
avatar.go
115 lines (104 loc) · 2.37 KB
/
avatar.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
package main
import (
"bytes"
"github.com/nfnt/resize"
"github.com/oliamb/cutter"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
)
func min(x, y int) int {
if x <= y {
return x
}
return y
}
func max(x, y int) int {
if x >= y {
return x
}
return y
}
// Avatar image with some metadata
type Avatar struct {
size int
data []byte
// below are used in header fields
cacheControl string
lastModified string
}
func avatar2Image(avatar *Avatar) (img image.Image, format string, err error) {
return image.Decode(bytes.NewBuffer(avatar.data))
}
// alters the avatar instance!
func image2Avatar(avatar *Avatar, img image.Image, format string) {
b := new(bytes.Buffer)
switch format {
case "jpeg":
jpeg.Encode(b, img, nil)
case "gif":
gif.Encode(b, img, nil)
case "png":
png.Encode(b, img)
}
avatar.data = b.Bytes()
}
// scales the avatar (altering it!)
func scale(avatar *Avatar, size int, requestFormat string) error {
img, format, err := avatar2Image(avatar)
if err != nil {
return err
}
targetFormat := format
if requestFormat != "" {
targetFormat = requestFormat
}
actualSize := img.Bounds().Dx() // assume square
log.Printf("Resizing img from %s %vx%v to %s %vx%v", format, actualSize, actualSize, targetFormat, size, size)
resized := resize.Resize(uint(size), uint(size), img, resize.Bicubic)
image2Avatar(avatar, resized, targetFormat)
return nil
}
func cropAndScale(avatar *Avatar) error {
img, format, err := avatar2Image(avatar)
if err != nil {
return err
}
x := img.Bounds().Dx()
y := img.Bounds().Dy()
size := min(x, y)
if x != y {
log.Printf("Cropping img from %vx%v to %vx%v", x, y, size, size)
img, err = cutter.Crop(img, cutter.Config{
Width: size,
Height: size,
Mode: cutter.Centered})
if err != nil {
return err
}
}
if size > maxSize {
log.Printf("Resizing img from %vx%v to %vx%v", size, size, maxSize, maxSize)
img = resize.Resize(uint(maxSize), uint(maxSize), img, resize.Bicubic)
}
image2Avatar(avatar, img, format)
return nil
}
func strictReadImage(reader io.Reader) (*Avatar, error) {
b := new(bytes.Buffer)
if _, e := io.Copy(b, reader); e != nil {
return nil, e
}
return &Avatar{size: -1, data: b.Bytes()}, nil
}
func readImage(reader io.Reader) *Avatar {
avatar, err := strictReadImage(reader)
if err != nil {
log.Print("Could not read image", err)
return nil
}
return avatar
}