-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.go
85 lines (71 loc) · 1.58 KB
/
base.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
package storage
import (
"image"
"image/jpeg"
"image/png"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
type ContentType string
const (
JSONTYPE ContentType = "application/json;charset=uft-8"
IMAGEPNG ContentType = "image/png"
)
type NFTStorage interface {
Write(data []byte, output string, contentType ContentType) error
WriteImage(data *image.RGBA, output string) error
Read(path string) ([]byte, error)
ReadImage(path string) (image.Image, error)
}
type LocalStorage struct{}
func (LocalStorage) Write(data []byte, output string, contentType ContentType) error {
//bytes, _ := json.Marshal(data)
err := ioutil.WriteFile(output, data, 0644)
if err != nil {
return err
}
return nil
}
func (LocalStorage) WriteImage(data *image.RGBA, output string) error {
file, err := os.Create(output)
log.Println("create file:", err)
if err != nil {
return err
}
return png.Encode(file, data)
}
func (LocalStorage) Read(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return io.ReadAll(file)
}
func (LocalStorage) ReadImage(path string) (image.Image, error) {
absPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
imgFile, err := os.Open(absPath)
if err != nil {
return nil, err
}
defer imgFile.Close()
var img image.Image
splittedPath := strings.Split(path, ".")
ext := splittedPath[len(splittedPath)-1]
if ext == "jpg" || ext == "jpeg" {
img, err = jpeg.Decode(imgFile)
} else {
img, err = png.Decode(imgFile)
}
if err != nil {
return nil, err
}
return img, nil
}