Search code examples
c#svgskiasharp

Can I render SVG to PNG using SkiaSharp?


I'm trying to use SkiaSharp to convert an SVG file to PNG. I know there are many alternatives, but I wanted to evaluate it's SVG load support.

Is this possible? I tried this:

var svg = new SKSvg(new SKSize(200, 200));
svg.Load("image.svg");

var bitmap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height);
var canvas = new SKCanvas(bitmap);
canvas.DrawPicture(svg.Picture);
canvas.Flush();
canvas.Save();

using (var image = SKImage.FromBitmap(bitmap))
using (var data = image.Encode(SKImageEncodeFormat.Png, 80))
{
    // save the data to a stream
    using (var stream = File.OpenWrite("image.png"))
    {
        data.SaveTo(stream);
    }
}

But I just get an empty image.


Solution

  • Yes it can. The above code works against test SVG shipped with SkiaSharp. https://github.com/mono/SkiaSharp/blob/8ca298b448810cf65ab13cd7b2de94c627a033c1/tests/Content/images/logos.svg.

    My SVG may not be supported. I will post different question if I want to investigate further.