forked from jason/cpolis
Automatically resize images and save them as webp
This commit is contained in:
38
cmd/backend/images.go
Normal file
38
cmd/backend/images.go
Normal file
@ -0,0 +1,38 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/chai2010/webp"
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func SaveImage(c *Config, src io.Reader) (string, error) {
|
||||
img, err := imaging.Decode(src, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error decoding image: %v", err)
|
||||
}
|
||||
|
||||
if img.Bounds().Dy() > c.MaxImgHeight {
|
||||
img = imaging.Resize(img, 0, c.MaxImgHeight, imaging.Lanczos)
|
||||
}
|
||||
if img.Bounds().Dx() > c.MaxImgWidth {
|
||||
img = imaging.Resize(img, c.MaxImgWidth, 0, imaging.Lanczos)
|
||||
}
|
||||
|
||||
filename := fmt.Sprint(c.PicsDir, "/", uuid.New(), ".webp")
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating new image file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if err = webp.Encode(file, img, &webp.Options{Lossless: true}); err != nil {
|
||||
return "", fmt.Errorf("error encoding image as webp: %v", err)
|
||||
}
|
||||
|
||||
return filename, nil
|
||||
}
|
Reference in New Issue
Block a user