-
Notifications
You must be signed in to change notification settings - Fork 9
/
base64.go
54 lines (47 loc) · 1.13 KB
/
base64.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
package imgo
import (
"bytes"
"encoding/base64"
"image/png"
"strings"
)
// ToBase64 returns the base64 encoded string of the image.
func (i Image) ToBase64() string {
buff := bytes.NewBuffer(nil)
err := png.Encode(buff, i.image)
if err != nil {
return ""
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buff.Bytes())
}
// LoadFromBase64 loads an image from a base64 encoded string.
func LoadFromBase64(base64Str string) (i *Image) {
i = &Image{}
base64Str = strings.Split(base64Str, ",")[1]
// Decode the base64 string
decodeString, err := base64.StdEncoding.DecodeString(base64Str)
if err != nil {
i.addError(err)
return
}
// Get the extension, mimetype and corresponding decoder function of the image.
ext, mimetype, decoder, err := GetImageType(decodeString[:8])
if err != nil {
i.addError(err)
return
}
// Decode the image.
buff := bytes.NewBuffer(decodeString)
img, err := decoder(buff)
if err != nil {
i.addError(err)
return
}
return &Image{
image: Image2RGBA(img),
width: img.Bounds().Dx(),
height: img.Bounds().Dy(),
extension: ext,
mimetype: mimetype,
}
}