-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
48 lines (38 loc) · 856 Bytes
/
utils.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
package main
import (
"bufio"
"bytes"
"github.com/disintegration/imageorient"
"image/jpeg"
"image/png"
"io/ioutil"
"mime/multipart"
)
func compressIfPossible(file multipart.File, ext string) ([]byte, error) {
img, _, err := imageorient.Decode(file)
if err != nil {
return nil, err
}
if ext != ".jpg" && ext != ".jpeg" && ext != ".png" {
buffer, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return buffer, nil
}
var buffer bytes.Buffer
dst := bufio.NewWriter(&buffer)
if ext == ".jpg" || ext == ".jpeg" {
err = jpeg.Encode(dst, img, &jpeg.Options{Quality: 40})
if err != nil {
return nil, err
}
} else if ext == ".png" {
encoder := png.Encoder{CompressionLevel: png.BestCompression}
err = encoder.Encode(dst, img)
if err != nil {
return nil, err
}
}
return buffer.Bytes(), nil
}