Skip to content

Instantly share code, notes, and snippets.

@whiler
Created May 17, 2023 13:19
Show Gist options
  • Save whiler/dc8c71aa567c2f2c02bcb5e8c68f84cf to your computer and use it in GitHub Desktop.
Save whiler/dc8c71aa567c2f2c02bcb5e8c68f84cf to your computer and use it in GitHub Desktop.
使用 golang 将 SVG 图像转换成 PNG 图像
package main
import (
"bytes"
"image"
"image/png"
"io"
"github.com/srwiley/oksvg"
"github.com/srwiley/rasterx"
)
func SVG2PNG(svg io.Reader) (io.Reader, error) {
if icon, err := oksvg.ReadIconStream(svg); err != nil {
return nil, err
} else {
width, height := int(icon.ViewBox.W), int(icon.ViewBox.H)
icon.SetTarget(0, 0, icon.ViewBox.W, icon.ViewBox.H)
rgba := image.NewRGBA(image.Rect(0, 0, width, height))
icon.Draw(rasterx.NewDasher(width, height, rasterx.NewScannerGV(width, height, rgba, rgba.Bounds())), 1)
buf := &bytes.Buffer{}
if err = png.Encode(buf, rgba); err != nil {
return nil, err
} else {
return buf, nil
}
}
}
@lingok1
Copy link

lingok1 commented May 14, 2024

大佬不好用啊,生成的png文字无法显示,都是黑色的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment