/
compress.go
79 lines (71 loc) · 1.45 KB
/
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
*Created by XieJian on 2020/12/24 16:04
*@Desc:
*/
package resize
import (
"bytes"
"errors"
"fmt"
"github.com/nfnt/resize"
"image"
"image/gif"
"image/jpeg"
"image/png"
"os"
"path/filepath"
)
type CompressType string
const (
CompressNone CompressType = ""
CompressAuto = "auto"
CompressCustom = "custom"
)
func Compress(t CompressType, base int, file string) ([]byte, error) {
size, img, err := getReadSizeFile(file)
if err != nil {
return nil, err
}
var x, y int
switch t {
case CompressAuto:
if size < base {
base = 1
} else {
base = size / base
}
x, y = img.Bounds().Dx()/base, img.Bounds().Dy()/base
case CompressCustom:
x, y = img.Bounds().Dx()/base, img.Bounds().Dy()/base
default:
x, y = img.Bounds().Dx(), img.Bounds().Dy()
}
fmt.Println(base)
var buf = bytes.NewBuffer(nil)
img = resize.Thumbnail(uint(x), uint(y), img, resize.Lanczos3)
err = jpeg.Encode(buf, img, nil)
return buf.Bytes(), err
}
func getReadSizeFile(file string) (size int, img image.Image, err error) {
fh, err := os.Open(file)
if err != nil {
return
}
defer fh.Close()
// get file size
fileInfo, err := fh.Stat()
if err != nil {
return
}
switch filepath.Ext(file) {
case ".jpg", ".jpeg":
img, err = jpeg.Decode(fh)
case ".png":
img, err = png.Decode(fh)
case ".gif":
img, err = gif.Decode(fh)
default:
err = errors.New("no support picture extension")
}
return int(fileInfo.Size()), img, err
}