-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebPFile.go
55 lines (43 loc) · 1.19 KB
/
WebPFile.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
package imageoutput
import (
"image"
"os"
"path"
"github.com/chai2010/webp"
"github.com/disintegration/imaging"
)
// WebPFile ...
type WebPFile struct {
Directory string
Width int
Height int
Quality float32
}
// Save writes the image in WebP format to the file system.
func (output *WebPFile) Save(avatar *MetaImage, baseName string) error {
img := avatar.Image
// Resize & crop
if img.Bounds().Dx() != output.Width || img.Bounds().Dy() != output.Height {
img = imaging.Fill(img, output.Width, output.Height, imaging.Center, imaging.Lanczos)
}
// Write to file
fileName := path.Join(output.Directory, baseName+".webp")
return saveWebP(img, fileName, output.Quality)
}
// Delete deletes the file from the file system.
func (output *WebPFile) Delete(baseName string) error {
return os.Remove(path.Join(output.Directory, baseName+".webp"))
}
// saveWebP saves an image as a file in WebP format.
func saveWebP(img image.Image, out string, quality float32) error {
file, writeErr := os.Create(out)
if writeErr != nil {
return writeErr
}
defer file.Close()
encodeErr := webp.Encode(file, img, &webp.Options{
Quality: quality,
Lossless: quality == 100,
})
return encodeErr
}