Lanbo Lanbo - 9 days ago 7
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

A PNG renderer is not far fetched, in fact it already exists: http://devongovett.github.com/png.js/

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 http://no.de machine, and dotcloud also has IM available. Ask the guys at nodester, it's very likely that they have a graphics library available.

Comments