Lanbo Lanbo - 1 year ago 201
Node.js Question

Render SVG to PNG on the server with pure JavaScript

The title says it. I know Imagemagick can do that, but let us assume I am on a cloud server that will only allow me JavaScript (coughnodestercough). Which is not a bad thing, actually.

Recently I heard that there are h.264 renderers in javascript, so png is not that far fetched?

Answer Source

A PNG renderer is not far fetched, in fact it already exists:

The problem here is that you would need a "fake canvas" implementation that doesn't draw anything, just builds a pixel array, that could then be saved to a PNG. There is nothing like that 'cause it's kind of useless except for this case...

i.e.: svg -> bitmap renderer (fake canvas) -> rgb array -> png file

Some hosting providers will allow you to declare system-level dependencies, or have some defaults available. gm would work fine for this purpose:

gm = require('gm')

gm('image.svg').write('image.png', function(err){
  if (!err) console.log('image converted.')

You can apparently install imagemagick/graphicsmagick on a machine, and dotcloud also has IM available. Ask the guys at nodester, it's very likely that they have a graphics library available.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download