/
svg.go
86 lines (73 loc) · 2.06 KB
/
svg.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
package svg
import (
"bytes"
"crypto/md5"
"errors"
"image"
"io"
"io/ioutil"
"github.com/srwiley/oksvg"
"github.com/srwiley/rasterx"
)
// const svgHeader = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
// <svg onload="loaded()" xmlns="http://www.w3.org/2000/svg`
// Current placeholder to at least match all SVGs, need actual XML parsing for a real detection
// Also match files starting with an <svg tag
const svgHeader = `<`
func init() {
image.RegisterFormat("svg", svgHeader, Decode, DecodeConfig)
}
// -------------------------------------------------------------------------------------
// decode Encode SVG to image.Image object.
//
func decode(input []byte, width int, height int) (image.Image, error) {
key := svgCacheKey(input, width, height)
if img, ok := cacheImg[key]; ok {
return img, nil
}
in := bytes.NewReader(input)
icon, err := oksvg.ReadIconStream(in)
if err != nil {
return nil, err
}
w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
if width > 0 && height > 0 {
w, h = width, height
icon.SetTarget(0, 0, float64(w), float64(h))
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
scannerGV := rasterx.NewScannerGV(w, h, img, img.Bounds())
raster := rasterx.NewDasher(w, h, scannerGV)
icon.Draw(raster, 1.0)
cacheImg[key] = img
return img, nil
}
type cacheKey struct {
md5 [16]byte
width int
height int
}
var cacheImg = map[cacheKey]image.Image{}
func svgCacheKey(bs []byte, width, height int) cacheKey {
return cacheKey{md5.Sum(bs), width, height}
}
// Decode decodes the first frame of an SVG file into an image.
//
func Decode(r io.Reader) (image.Image, error) {
return DecodeSize(r, 0, 0)
}
// DecodeSize func.
//
func DecodeSize(r io.Reader, width int, height int) (image.Image, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return decode(b, width, height)
}
// DecodeConfig returns metadata.
//
func DecodeConfig(r io.Reader) (image.Config, error) {
return image.Config{}, errors.New("not implemented")
}
// -------------------------------------------------------------------------------------