使用纯 JavaScript 在服务器上将 SVG 渲染为 PNG
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7932964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Render SVG to PNG on the server with pure JavaScript
提问by Lanbo
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.
标题说了算。我知道ImageMagick的可以做到这一点,但让我们假设我是一个云服务器将只允许我的JavaScript(在咳嗽nodester咳嗽)。实际上,这并不是一件坏事。
Recently I heard that there are h.264 renderers in javascript, so png is not that far fetched?
最近听说javascript有h.264渲染器,那么png是不是很牵强?
采纳答案by Ricardo Tomasi
A PNG rendereris not far fetched, in fact it already exists: http://devongovett.github.com/png.js/
PNG渲染器并不遥不可及,事实上它已经存在: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...
这里的问题是你需要一个“假画布”实现,它不绘制任何东西,只构建一个像素数组,然后可以保存到 PNG。没有类似的东西,因为除了这种情况外,它有点无用......
i.e.: svg -> bitmap renderer (fake canvas) -> rgb array -> png file
即:svg -> 位图渲染器(假画布)-> rgb 数组 -> png 文件
Some hosting providers will allow you to declare system-level dependencies, or have some defaults available. gmwould 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.demachine, and dotcloudalso has IM available. Ask the guys at nodester, it's very likely that they have a graphics library available.
您显然可以在http://no.de机器上安装 imagemagick/graphicsmagick ,dotcloud也有 IM 可用。问 nodester 的人,他们很可能有可用的图形库。
回答by Brian Nickel
Unfortunately, all of the advanced rendering available in JavaScript is through browser implementations of the HTML5 canvas. NodeJS lacks these features.
不幸的是,JavaScript 中可用的所有高级渲染都是通过浏览器实现的 HTML5 画布。NodeJS 缺少这些功能。
There are extensions for NodeJS that let you do image manipulation, but you can only use those if your host installs them.
NodeJS 有一些扩展可以让您进行图像处理,但只有在您的主机安装了它们后才能使用这些扩展。
- http://ajaxorg.posterous.com/canvas-api-for-nodejs
- https://github.com/rsms/node-imagemagick(just requires that imagemagick is installed)
回答by Max Girkens
There's svg2png, which uses a headless browser to render svgs to png.
有 svg2png,它使用无头浏览器将 svgs 呈现为 png。
https://github.com/domenic/svg2png
https://github.com/domenic/svg2png