svg.go 926 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package image
  2. import (
  3. "image"
  4. "image/color"
  5. "io"
  6. "github.com/srwiley/oksvg"
  7. "github.com/srwiley/rasterx"
  8. )
  9. func Decode(r io.Reader) (image.Image, error) {
  10. icon, err := oksvg.ReadIconStream(r)
  11. if err != nil {
  12. return nil, err
  13. }
  14. w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
  15. icon.SetTarget(0, 0, float64(w), float64(h))
  16. rgba := image.NewRGBA(image.Rect(0, 0, w, h))
  17. icon.Draw(rasterx.NewDasher(w, h, rasterx.NewScannerGV(w, h, rgba, rgba.Bounds())), 1)
  18. return rgba, err
  19. }
  20. func DecodeConfig(r io.Reader) (image.Config, error) {
  21. var config image.Config
  22. icon, err := oksvg.ReadIconStream(r)
  23. if err != nil {
  24. return config, err
  25. }
  26. config.ColorModel = color.RGBAModel
  27. config.Width = int(icon.ViewBox.W)
  28. config.Height = int(icon.ViewBox.H)
  29. return config, nil
  30. }
  31. func init() {
  32. image.RegisterFormat("svg", "<?xml ", Decode, DecodeConfig)
  33. image.RegisterFormat("svg", "<svg", Decode, DecodeConfig)
  34. }