/
image_compress.go
63 lines (57 loc) · 1.24 KB
/
image_compress.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
package utils
import (
"image"
"image/jpeg"
"image/png"
"os"
"path"
"path/filepath"
"github.com/nfnt/resize"
)
func ImageCommpress(pathStr string) (string, error) {
fileIn, err := os.Open(pathStr)
defer func() {
_ = fileIn.Close()
}()
if CheckError(err) {
ErrorLog(err)
return "", err
}
lastPaths := filepath.Dir(pathStr)
fileSuffix := path.Ext(pathStr)
lastPaths = lastPaths + "/" + "tmp" + fileSuffix
var origin image.Image
if fileSuffix == ".png" {
origin, err = png.Decode(fileIn)
if CheckError(err) {
origin, err = jpeg.Decode(fileIn)
}
} else {
origin, err = jpeg.Decode(fileIn)
}
if CheckError(err) {
ErrorLog(err)
return "", err
}
fileOut, err := os.Create(lastPaths)
if CheckError(err) {
ErrorLog(err)
return "", err
}
defer fileOut.Close()
b := origin.Bounds()
oWidth := b.Max.X
DebugLog("oWidthoWidthoWidth", oWidth)
oHeight := b.Max.Y
DebugLog("oHeightoHeightoHeight", oHeight)
width := uint(300)
height := float32((300.0 / float32(oWidth))) * float32(oHeight)
DebugLog("heightheightheight", height)
canvas := resize.Thumbnail(width, uint(height), origin, resize.Bicubic)
err = png.Encode(fileOut, canvas)
if CheckError(err) {
ErrorLog(err)
return "", err
}
return lastPaths, nil
}