-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource.go
78 lines (68 loc) · 1.18 KB
/
resource.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
package model
import (
"image"
"image/jpeg"
"image/png"
"io/fs"
"log"
"os"
"strings"
"golang.org/x/image/webp"
)
type Resource struct {
Name string
Path string
Scheme Scheme
IsDir bool
Size int64
Width int32
Height int32
Err error `json:"-" yaml:"-"`
}
func SetupResource(res *Resource, path string, classn int32) {
var (
info fs.FileInfo
err error
)
res.Path = path
res.Scheme = File
defer func() {
res.Err = err
}()
// path = filepath.Clean(path)
i := strings.LastIndexByte(path, '.')
if i > 0 {
ext := path[i+1:]
log.Println("NewFileResource", path, ext)
res.Width, res.Height = GetDimensions(path, ext)
}
info, err = os.Stat(path)
if err == nil {
res.Name = info.Name()
res.Size = info.Size()
res.IsDir = info.IsDir()
}
}
func GetDimensions(path, ext string) (width int32, height int32) {
r, err := os.Open(path)
if err != nil {
return
}
var (
cfg image.Config
)
switch ext {
case "png":
cfg, err = png.DecodeConfig(r)
case "jpeg":
case "jpg":
cfg, err = jpeg.DecodeConfig(r)
case "webp":
cfg, err = webp.DecodeConfig(r)
}
defer r.Close()
if err != nil {
return
}
return int32(cfg.Width), int32(cfg.Height)
}