-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsvg2png.go
95 lines (78 loc) · 1.92 KB
/
svg2png.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package svg2png
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
var (
DefaultChromePaths = []string{
"/usr/bin/chromium-browser",
"/usr/bin/chromium",
"/usr/bin/google-chrome-stable",
"/usr/bin/google-chrome",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"C:/Program Files/Google/Chrome/Application/chrome.exe"}
)
func getChromePath() string {
for _, path := range DefaultChromePaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
return path
}
}
return ""
}
func SvgToPng(svg string, height int, width int) ([]byte, error) {
// write val to svg in temp
// convert to png
tempDir := os.TempDir()
svgFile := strings.Replace(tempDir+"\\temp.svg", "\\", "/", -1)
f, err := os.Create(svgFile)
if err != nil {
return nil, err
}
pngFile := tempDir + "\\temp.png"
_, err = f.WriteString(svg)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
args := []string{
"--headless",
"--no-sandbox",
"--disable-crash-reporter",
"--hide-scrollbars",
"--default-background-color=00000000",
"--disable-gpu",
"--window-size=" + fmt.Sprintf("%d,%d", width, height),
"--screenshot=" + pngFile,
"file://" + svgFile,
}
ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second)
defer cancel()
if err := exec.CommandContext(ctx, getChromePath(), args...).Run(); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return nil, errors.New("takes screenshot got timeout")
}
return nil, err
}
if _, err := os.Stat(pngFile); os.IsNotExist(err) {
return nil, err
}
png, err := os.ReadFile(pngFile)
if err != nil {
return nil, err
}
_ = os.Remove(svgFile)
_ = os.Remove(pngFile)
return png, nil
}