-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
79 lines (71 loc) · 1.34 KB
/
util.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
package ximg
import (
"fmt"
"image"
_ "image/gif" // ...
"image/jpeg"
"image/png"
"os"
"github.com/falcolee/xutils/xencoding"
"github.com/falcolee/xutils/xfile"
)
// Parse ...
func Parse(filepath string) (image.Image, string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, "", err
}
defer f.Close()
return image.Decode(f)
}
// Type ...
func Type(filepath string) string {
_, t, err := Parse(filepath)
if err != nil {
return ""
}
return t
}
// Size ...
func Size(filepath string) (int, int) {
img, _, err := Parse(filepath)
if err != nil {
return 0, 0
}
return img.Bounds().Dx(), img.Bounds().Dy()
}
// Read ...
func Read(filepath string) image.Image {
img, _, err := Parse(filepath)
if err != nil {
return nil
}
return img
}
// Write ...
func Write(filepath string, src image.Image) error {
file, err := os.Create(filepath)
if err != nil {
return err
}
defer file.Close()
ext := xfile.GetFileExt(filepath)
switch ext {
case "jpg", "jpeg":
return jpeg.Encode(file, src, &jpeg.Options{
Quality: jpeg.DefaultQuality,
})
case "png":
return png.Encode(file, src)
default:
return fmt.Errorf("invalid image type: %s", ext)
}
}
// Base64 ...
func Base64(filepath string) string {
return fmt.Sprintf(
"data:image/%s;base64,%s",
Type(filepath),
xencoding.Base64Encode(xfile.Read(filepath)),
)
}