Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I render SVG to PNG using SkiaSharp?

Tags:

c#

svg

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.

like image 702
t9mike Avatar asked Feb 12 '17 01:02

t9mike


People also ask

Can you turn an SVG into a PNG?

Use Adobe Photoshop to convert SVG images to PNG images. Get lossless compression, preserve image resolution, and lower your file size by converting from SVG to PNG. Use Photoshop for a fast way to turn large file formats into smaller, easier-to-use graphic types.

How do I convert SVG to PNG locally?

svg file, right click on it and click on the context menu item 'Save SVG as PNG. Lets you click on the extension icon or right click on an . svg file and choose Save SVG as PNG.


1 Answers

Use this Code. i painted a flag from a svg web service.

  var svg = new SkiaSharp.Extended.Svg.SKSvg();
  svg.Load(msSvg);
  using (var bitMap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height))
  using (SKCanvas canvas = new SKCanvas(bitMap))
  {
    canvas.DrawPicture(svg.Picture);
    canvas.Flush();
    canvas.Save();

    using (SKImage image = SKImage.FromBitmap(bitMap))
    {
      using (SKData data = image.Encode(SKEncodedImageFormat.Png, 80))
      {
        MemoryStream memStream = new MemoryStream(); 
        data.SaveTo(memStream);
        memStream.Seek(0, SeekOrigin.Begin);
        this._flagImage = ImageSource.FromStream(() => memStream);
      }
    }
  }
like image 53
Jorge Garcia Casalett Avatar answered Oct 29 '22 08:10

Jorge Garcia Casalett