-
Notifications
You must be signed in to change notification settings - Fork 0
/
nativeGoIconManager.go
100 lines (80 loc) · 2.17 KB
/
nativeGoIconManager.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
package icons
import (
"Server/config"
"bytes"
"encoding/base64"
"fmt"
"github.com/Pallinder/go-randomdata"
"github.com/gin-gonic/gin"
"github.com/nfnt/resize"
"github.com/pkg/errors"
"image"
"image/png"
"net/http"
"os"
)
type GoIconManager struct {
OutPath string
}
func CreateGoIconManager(conf config.Config) IconManager {
if _, err := os.Stat("tmp"); os.IsNotExist(err) {
os.Mkdir("tmp", os.ModePerm)
}
return &GoIconManager{
OutPath: conf.GetIconsDir(),
}
}
func (m *GoIconManager) StoreNewIconFromImage(img image.Image) (string, string, error) {
largeOutPath := randomdata.RandStringRunes(10) + ".png"
smallOutPath := randomdata.RandStringRunes(10) + ".png"
largeImg := resize.Resize(512, 512, img, resize.Lanczos3)
smallImg := resize.Resize(128, 128, img, resize.Lanczos3)
largeOut, err := os.Create(m.OutPath + largeOutPath)
if err != nil {
return "", "", err
}
defer largeOut.Close()
smallOut, err := os.Create(m.OutPath + smallOutPath)
if err != nil {
return "", "", err
}
defer smallOut.Close()
png.Encode(largeOut, largeImg)
png.Encode(smallOut, smallImg)
return smallOutPath, largeOutPath, nil
}
func (m *GoIconManager) StoreNewIconFromBase64String(icon string) (string, string, error) {
b, err := base64.StdEncoding.DecodeString(icon)
if err != nil {
return "", "", errors.New("Cannot decode b64")
}
r := bytes.NewReader(b)
img, err := png.Decode(r)
if err != nil {
panic("Bad png")
}
return m.StoreNewIconFromImage(img)
}
func (m *GoIconManager) StoreNewIconFromForm(ctx *gin.Context) (string, string, error) {
tmpFileLoc := "tmp/" + randomdata.RandStringRunes(10)
formFile, err := ctx.FormFile("icon")
if err != nil {
ctx.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
return "", "", err
}
if err := ctx.SaveUploadedFile(formFile, tmpFileLoc); err != nil {
ctx.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
return "", "", err
}
defer os.Remove(tmpFileLoc)
file, err := os.Open(tmpFileLoc)
if err != nil {
return "", "", err
}
img, err := png.Decode(file)
if err != nil {
return "", "", err
}
file.Close()
return m.StoreNewIconFromImage(img)
}