Created
May 17, 2023 13:19
-
-
Save whiler/dc8c71aa567c2f2c02bcb5e8c68f84cf to your computer and use it in GitHub Desktop.
使用 golang 将 SVG 图像转换成 PNG 图像
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
大佬不好用啊,生成的png文字无法显示,都是黑色的