Convert SVG to PNG with a single line of code

HTML element img accepts an SVG file as its source, therefore you can convert SVG to PNG with a single line of code:

<img src="svg-logo.svg" />

Then you can save it as a PNG image. This way is not only the simplest, but also gets the same picture quality as the SVG file.

You can also set a customized size for it:

<img src="svg-logo.svg" width="256" height="256" />


Note: If your SVG references a font, the font will be replaced by a default one in the image, meaning referenced fonts are not supported.

Other methods

Using HTML5 canvas

svg to png provides a more complicated method, it uses HTML5 canvas’s drawImage method to draw the SVG on canvas and gets an encoded PNG from it.

var svg     = document.querySelector('#svg'),
    img     = document.querySelector('#png'),
    canvas   = document.createElement('canvas'),   // New element
    context  = can.getContext('2d'),
    loader   = new Image;

loader.width  = canvas.width  = tgtImage.width;
loader.height = canvas.height = tgtImage.height;
loader.onload = function(){
  context.drawImage(loader, 0, 0, loader.width, loader.height);
  tgtImage.src = can.toDataURL();
var svgXML = (new XMLSerializer).serializeToString(svg);
loader.src = 'data:image/svg+xml,' + encodeURIComponent(svgXML);

I found there will be a loss of picture quality obtained in this way. It also does not support referenced fonts.


svgexport is a open-source nodejs module. You need to install node.js and install svgexport module before using it.

The biggest issue is that it does not support referencing elements in SVG.