-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsopimg.go
123 lines (104 loc) · 1.97 KB
/
sopimg.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package sopimg
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"errors"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io/ioutil"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type SopImg interface {
Base64ToFile(info ImgInfo) error
}
type ImgInfo struct{
Type string
Base64 string
Path string
}
type RepImgInfo struct {
Name string
PathLong string
PathSmall string
Postfix string
Width int
Height int
}
func (im *ImgInfo) Base64ToFile() (rep RepImgInfo,err error){
s, err := base64.StdEncoding.DecodeString(im.Base64) //转码
bf := bytes.NewBuffer(s) //写入buffer
//格式判断
var img image.Image
var err2 error
var postfix string
postfix = "jpg"
err2 = errors.New("格式不正确")
switch strings.ToLower(im.Type) {
case "png":
img,err2 = png.Decode(bf)
postfix = "png"
break
case "jpg","jpeg":
img,err2 = jpeg.Decode(bf)
postfix = "jpg"
break
case "gif":
img,err2 = gif.Decode(bf)
postfix = "gif"
break
}
//获取宽高
var w,h int
if err2 ==nil{
c := img.Bounds()
w = c.Max.X
h = c.Max.Y
}else{
w = 0
h = 0
}
name,p := im.GetName()
//目录判断
if im.Path ==""{
im.Path = "/tmp/data/images"
}
//创建目录
err = os.MkdirAll(im.Path + p,0711)
if err != nil{
return
}
fileName := name + "." + postfix
filePath := im.Path + p + fileName
rep.Name = fileName
rep.PathLong = filePath
rep.PathSmall = p + fileName
rep.Postfix = postfix
rep.Width = w
rep.Height = h
//写入文件
err = ioutil.WriteFile(filePath, s, 0666)
if err !=nil{
return
}
return
}
func (im *ImgInfo) GetName() (name string,path string){
ctx := md5.New()
t := time.Now().UnixNano()
ts := strconv.FormatInt(t,10)
n := rand.Int63n(100000)
ns := strconv.FormatInt(n,10)
ctx.Write([]byte(im.Base64+ts+ns))
name = hex.EncodeToString(ctx.Sum(nil))
ym := time.Now().Format("200601")
path = "/" + ym + "/" + string([]rune(name)[10:12]) + "/" + string([]rune(name)[21:23]) + "/"
return
}