2024-10-03 14:10:45 +02:00
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-10-04 16:06:33 +02:00
|
|
|
"image"
|
2024-10-03 14:10:45 +02:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/chai2010/webp"
|
|
|
|
"github.com/disintegration/imaging"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
2024-10-04 16:06:33 +02:00
|
|
|
var ErrUnsupportedFormat error = image.ErrFormat // used internally by imaging
|
|
|
|
|
2024-10-03 14:10:45 +02:00
|
|
|
func SaveImage(c *Config, src io.Reader) (string, error) {
|
|
|
|
img, err := imaging.Decode(src, imaging.AutoOrientation(true))
|
|
|
|
if err != nil {
|
2024-10-04 16:06:33 +02:00
|
|
|
if err == ErrUnsupportedFormat {
|
|
|
|
return "", ErrUnsupportedFormat
|
|
|
|
}
|
2024-10-03 14:10:45 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2024-10-04 12:10:12 +02:00
|
|
|
filename := fmt.Sprint(uuid.New(), ".webp")
|
|
|
|
file, err := os.Create(c.PicsDir + "/" + filename)
|
2024-10-03 14:10:45 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("error creating new image file: %v", err)
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
2024-10-27 07:21:36 +01:00
|
|
|
if err = webp.Encode(file, img, &webp.Options{Quality: 80}); err != nil {
|
2024-10-03 14:10:45 +02:00
|
|
|
return "", fmt.Errorf("error encoding image as webp: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return filename, nil
|
|
|
|
}
|