97 lines
1.9 KiB
Go
97 lines
1.9 KiB
Go
package format
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"tomatentum.net/svg-templater/pkg/svg"
|
|
)
|
|
|
|
type ConversionParameters struct {
|
|
Format string
|
|
Width, Height int
|
|
}
|
|
|
|
func ConvertByte(svgblob []byte, param ConversionParameters) ([]byte, error) {
|
|
reader, err := ConvertReader(svgblob, param)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer reader.Close()
|
|
|
|
result, err := io.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func ConvertReader(svgblob []byte, param ConversionParameters) (io.ReadCloser, error) {
|
|
if param.Format == "svg" {
|
|
return io.NopCloser(bytes.NewReader(svgblob)), nil
|
|
}
|
|
file, err := svg.CreateTemp(bytes.NewReader(svgblob), "svg")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer os.Remove(file)
|
|
|
|
switch param.Format {
|
|
case "png":
|
|
return convertPNG(file, param)
|
|
}
|
|
return nil, errors.New("Format not supported")
|
|
}
|
|
|
|
func convertPNG(input string, param ConversionParameters) (io.ReadCloser, error) {
|
|
var args []string
|
|
var outExt string
|
|
|
|
fontsdir, err := svg.Storage.GetFontsDir()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
args = append(args, "--skip-system-fonts")
|
|
args = append(args, "--use-fonts-dir", fontsdir)
|
|
|
|
if param.Width > 0 {
|
|
args = append(args, "-w", strconv.Itoa(param.Width))
|
|
}
|
|
if param.Height > 0 {
|
|
args = append(args, "-h", strconv.Itoa(param.Height))
|
|
}
|
|
|
|
outFile := strings.TrimSuffix(input, filepath.Ext(input)) + outExt
|
|
args = append(args, input)
|
|
args = append(args, outFile)
|
|
|
|
cmd := exec.Command("resvg", args...)
|
|
cmd.Dir = svg.TempDir
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
log.Println(string(out))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resvg failed: %w: %s", err, string(out))
|
|
}
|
|
|
|
file, err := os.Open(outFile)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return file, nil
|
|
}
|
|
|
|
func CheckResvg() bool {
|
|
_, err := exec.LookPath("resvg")
|
|
return err == nil
|
|
}
|