slideshow-api/internal/scale.go

44 lines
1.1 KiB
Go
Raw Normal View History

2023-11-28 15:52:53 +01:00
package internal
import (
"errors"
"io"
"os/exec"
"strings"
"time"
"git.velvettear.de/velvettear/loggo"
"git.velvettear.de/velvettear/slideshow/internal/config"
)
// scale an image
func ScaleImage(image string) ([]byte, error) {
timestamp := time.Now().UnixMilli()
cmd := exec.Command("convert", image, "-resize", config.Resolution+"^", "-gravity", "center", "-extent", config.Resolution, "-")
stdout, stdoutError := cmd.StdoutPipe()
stderr, stderrError := cmd.StderrPipe()
var data []byte
cmd.Start()
if stdoutError != nil {
return data, stdoutError
}
if stderrError != nil {
return data, stdoutError
}
data, stdoutError = io.ReadAll(stdout)
if stdoutError != nil {
return data, stdoutError
}
errorBytes, stderrError := io.ReadAll(stderr)
if stderrError != nil {
return data, stdoutError
}
cmd.Wait()
errorMessage := strings.TrimSpace(string(errorBytes))
if len(errorMessage) > 0 {
return data, errors.New(errorMessage)
}
loggo.DebugTimed("successfully scaled image", timestamp, "image: "+image, "resolution: "+config.Resolution)
return data, nil
}