2024-10-03 14:10:45 +02:00
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
2024-10-27 15:05:11 +01:00
|
|
|
"encoding/base64"
|
2024-10-03 14:10:45 +02:00
|
|
|
"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-27 15:05:11 +01:00
|
|
|
func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, error) {
|
2024-10-03 14:10:45 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2024-10-27 15:05:11 +01:00
|
|
|
if img.Bounds().Dy() > maxHeight {
|
|
|
|
img = imaging.Resize(img, 0, maxHeight, imaging.Lanczos)
|
2024-10-03 14:10:45 +02:00
|
|
|
}
|
2024-10-27 15:05:11 +01:00
|
|
|
if img.Bounds().Dx() > maxWidth {
|
|
|
|
img = imaging.Resize(img, maxWidth, 0, imaging.Lanczos)
|
2024-10-03 14:10:45 +02:00
|
|
|
}
|
|
|
|
|
2024-10-04 12:10:12 +02:00
|
|
|
filename := fmt.Sprint(uuid.New(), ".webp")
|
2024-10-27 15:05:11 +01:00
|
|
|
file, err := os.Create(path + 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
|
|
|
|
}
|
2024-10-27 15:05:11 +01:00
|
|
|
|
|
|
|
func ServeBase64Image(c *Config, filename string) (string, error) {
|
|
|
|
file := c.PicsDir + "/" + filename
|
|
|
|
|
|
|
|
img, err := os.Open(file)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("error opening file %v: %v", file, err)
|
|
|
|
}
|
|
|
|
defer img.Close()
|
|
|
|
|
|
|
|
imgBytes, err := io.ReadAll(img)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("error turning %v into bytes: %v", file, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return base64.StdEncoding.EncodeToString(imgBytes), nil
|
|
|
|
}
|