-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
63 lines (56 loc) · 1.42 KB
/
file.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 main
import (
"bytes"
"image"
"image/jpeg"
"image/png"
"path/filepath"
"strings"
"github.com/gabriel-vasile/mimetype"
"github.com/kolesa-team/go-webp/encoder"
"github.com/kolesa-team/go-webp/webp"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
)
func optimizeFile(outputFilepath *string, fileBytes *bytes.Buffer) {
mtype := mimetype.Detect(fileBytes.Bytes())
mtypeString := mtype.String()
switch {
case strings.HasPrefix(mtypeString, "image/"):
if mtypeString == "image/webp" {
return
}
var img image.Image
var err error
switch {
case strings.HasSuffix(mtypeString, "jpeg"):
img, err = jpeg.Decode(fileBytes)
case strings.HasSuffix(mtypeString, "png"):
img, err = png.Decode(fileBytes)
case strings.HasSuffix(mtypeString, "bmp"):
img, err = bmp.Decode(fileBytes)
case strings.HasSuffix(mtypeString, "tiff"):
img, err = tiff.Decode(fileBytes)
default:
return // Unsupported image format
}
if err != nil {
return
}
webpOptions, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, 75)
if err != nil {
return
}
if err := webp.Encode(fileBytes, img, webpOptions); err != nil {
return
}
*outputFilepath = replaceExtension(*outputFilepath, ".webp")
default:
return
}
}
func replaceExtension(path string, newExt string) string {
currentExt := filepath.Ext(path)
pathWithoutExt := strings.TrimSuffix(path, currentExt)
return pathWithoutExt + newExt
}