• Stars
    star
    573
  • Rank 77,865 (Top 2 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 12 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Converts SVGs to PNGs, using PhantomJS

SVG-to-PNG Converter Using PhantomJS

You have a SVG file. For whatever reason, you need a PNG. svg2png can help.

const fs = require("pn/fs"); // https://www.npmjs.com/package/pn
const svg2png = require("svg2png");

fs.readFile("source.svg")
    .then(svg2png)
    .then(buffer => fs.writeFile("dest.png", buffer))
    .catch(e => console.error(e));

In the above example, we use the width and height attributes specified in the SVG file to automatically determine the size of the SVG. You can also explicitly set the size:

svg2png(sourceBuffer, { width: 300, height: 400 })
    .then(buffer => ...)
    .catch(e => console.error(e));

This is especially useful for images without width or heights. You can even specify just one of them and (if the image has an appropriate viewBox) the other will be set to scale.

Finally, some SVG files reference external resources using relative paths. You can set them up for correct conversion by passing the filename or url option:

svg2png(sourceBuffer, { url: "https://example.com/awesomeness.svg" })
    .then(buffer => ...)
    .catch(e => console.error(e));

svg2png(sourceBuffer, { filename: path.resolve(__dirname, "images/fun.svg") })
    .then(buffer => ...)
    .catch(e => console.error(e));

Sync variant

There's also a sync variant, for use in your shell scripts:

const outputBuffer = svg2png.sync(sourceBuffer, options);

How the conversion is done

svg2png is built on the latest in PhantomJS technology to render your SVGs using a headless WebKit instance. I have found this to produce much more accurate renderings than other solutions like GraphicsMagick or Inkscape. Plus, it's easy to install cross-platform due to the excellent phantomjs npm package—you don't even need to have PhantomJS in your PATH.

Rendering isn't perfect; we have a number of issues that are blocked on PhantomJS getting its act together and releasing a cross-platform version with updated WebKit.

Exact resizing behavior

Previous versions of svg2png attempted to infer a good size based on the width, height, and viewBox attributes. As of our 3.0 release, we attempt to stick as close to the behavior of loading a SVG file in your browser as possible. The rules are:

  • Any width or height attributes that are in percentages are ignored and do not count for the subsequent rules.
  • The dimensions option { width, height } overrides any width or height attributes in the SVG file, including for the subsequent rules. If a key is missing from the dimensions object (i.e. { width } or { height }) the corresponding attribute in the SVG file will be deleted.
  • width and height attributes without a viewBox attribute cause the output to be of those dimensions; this might crop the image or expand it with empty space to the bottom and to the right.
  • width and/or height attributes with a viewBox attribute cause the image to scale to those dimensions. If the ratio does not match the viewBox's aspect ratio, the image will be expanded and centered with empty space in the extra dimensions. When a viewBox is present, one of either width or height can be omitted, with the missing one inferred from the viewBox's aspect ratio.
  • When there are neither width nor height attributes, the promise rejects.

One thing to note is that svg2png does not and cannot stretch your images to new aspect ratios.

CLI

This package comes with a CLI version as well; you can install it globally with npm install svg2png -g. Use it as follows:

$ svg2png --help
Converts SVGs to PNGs, using PhantomJS

svg2png input.svg [--output=output.png] [--width=300] [--height=150]

Options:
  -o, --output  The output filename; if not provided, will be inferred  [string]
  -w, --width   The output file width, in pixels                        [string]
  -h, --height  The output file height, in pixels                       [string]
  --help        Show help                                              [boolean]
  --version     Show version number                                    [boolean]

Node.js requirements

svg2png uses the latest in ES2015 features, and as such requires a recent version of Node.js. Only the 6.x series onward is supported.

More Repositories

1

promises-unwrapping

The ES6 promises spec, as per September 2013 TC39 meeting
JavaScript
1,238
star
2

count-to-6

An intro to some ES6 features via a set of self-guided workshops.
JavaScript
326
star
3

restify-oauth2

A simple OAuth 2 endpoint for Restify
CoffeeScript
294
star
4

opener

Opens stuff, like webpages and files and executables, cross-platform
JavaScript
293
star
5

html-as-custom-elements

HTML as Custom Elements
CSS
259
star
6

proposal-blocks

Former home of a proposal for a new syntactic construct for serializable blocks of JavaScript code
215
star
7

zones

Former home of the zones proposal for JavaScript
205
star
8

worm-scraper

Scrapes the web serial Worm and its sequel Ward into an eBook format
JavaScript
179
star
9

jadeify

A simple browserify transform for turning .jade files into template functions
JavaScript
162
star
10

mocha-as-promised

Adds “thenable” promise support to the Mocha test runner.
JavaScript
132
star
11

especially

Abstract operations and other functions drawn from the ECMAScript specification
JavaScript
91
star
12

dict

A lightweight but safe dictionary, for when Object won't cut it
CoffeeScript
75
star
13

infinite-list-study-group

Moved to WICG/virtual-scroller
72
star
14

understanding-node

Material for the "Understanding the Node.js Platform" class at General Assembly
JavaScript
66
star
15

promise-tests

DEPRECATED: use https://github.com/promises-aplus/promises-tests instead!
JavaScript
61
star
16

proposal-arraybuffer-transfer

Former home of the now-withdrawn ArrayBuffer.prototype.transfer() proposal for JavaScript
60
star
17

path-is-inside

Tests whether one path is inside another path
JavaScript
40
star
18

streams-demo

Demo for Fetch + Streams
HTML
40
star
19

sorted-object

Returns a copy of an object with its keys sorted
JavaScript
35
star
20

traceur-runner

Runs JavaScript.next code in Node by compiling it with Traceur on the fly, seamlessly
JavaScript
35
star
21

last

A small helper for getting only the latest result of an asynchronous operation you perform multiple times in a row.
JavaScript
31
star
22

get-originals

A web platform API that allows access to the "original" versions of the global built-in objects' properties and methods
28
star
23

webidl-class-generator

Generates classes from WebIDL plus implementation code
JavaScript
28
star
24

pubit

Responsible publish/subscribe. Hide the event publisher, only exposing the event emitter.
CoffeeScript
28
star
25

browserify-deoptimizer

Transforms browserify bundles into a collection of single files
CoffeeScript
26
star
26

unhandled-rejections-browser-spec

Spec patches for HTML and ES for tracking unhandled promise rejections with events
22
star
27

wpt-runner

Runs web platform tests in Node.js using jsdom
JavaScript
21
star
28

template-parts

Brainstorming a <template> parts proposal
20
star
29

cooperatively-sized-iframes

A proposal for iframes which can resize according to their content
20
star
30

client-side-packages-demo

A demo application that shows recent commits to npm, using npm packages on the client side via browserify
JavaScript
18
star
31

es6isnigh

A presentation on the future of the JavaScript language.
JavaScript
17
star
32

specgo

A command-line tool for opening web specifications
JavaScript
16
star
33

element-constructors

Some ideas for how to implement constructors for Element, HTMLElement, etc.
JavaScript
15
star
34

html-dashboard

A dashboard for issue and pull request management in whatwg/html
JavaScript
14
star
35

amd-wrap

Wraps CommonJS files in `define(function (require, exports, module) { ... })`.
JavaScript
11
star
36

dynamo-as-promised

A promise-based client for Amazon's DynamoDB.
CoffeeScript
11
star
37

chromiumizer

Convert an image into the Chromium color pallette
JavaScript
10
star
38

domains-tragedy

An illustration of how Node.js domains can fail you when EventEmitters get involved.
JavaScript
10
star
39

rewrapper

A web application for rewrapping text to fit a column limit
HTML
9
star
40

extensions

Useful extension methods from my own projects
C#
8
star
41

webidl-html-reflector

Implements the algorithms to reflect HTML content attributes as WebIDL attributes
JavaScript
8
star
42

grunt-amd-wrap

Grunt task to wrap CommonJS files in `define(function (require, exports, module) { ... })`.
JavaScript
8
star
43

remember-to-eat

My personal meal/calorie/protein tracker
JavaScript
6
star
44

global-wrap

Exposes your CommonJS-based libraries as a global.
JavaScript
6
star
45

origin-agent-cluster-demo.dev

Some Origin-Agent-Cluster demos
HTML
6
star
46

v8-extras-geometry

An exploration of using V8 extras to implement the Geometry spec
JavaScript
6
star
47

jake-diagram-generator

Generates "Jake diagrams", i.e. browser session history timeline diagrams
JavaScript
6
star
48

blog.domenic.me

Hidden Variables: my infrequently-updated blog
Nunjucks
6
star
49

eslint-config

My personal base ESLint config
JavaScript
6
star
50

jsdom-proxy-benchmark

Benchmark for proxies that uses jsdom to build the ECMAScript spec
JavaScript
6
star
51

unownbot-filtered

A daemon that will filter @UnownBot to specific areas and text you about it
JavaScript
6
star
52

cs4h

Homework for General Assembly's CS for Hackers course (Summer 2012)
JavaScript
5
star
53

gmify

A simple interface to GraphicsMagick for streaming image processing.
JavaScript
4
star
54

wk-scripts

My userscripts for WaniKani
JavaScript
4
star
55

emu-algify

Use Ecmarkup's <emu-alg> elements in your HTML
JavaScript
3
star
56

warmup-reps

Initial work on an algorithmically-sound warmup rep calculator
JavaScript
3
star
57

grunt-global-wrap

Grunt task to expose your CommonJS-based libraries as a global.
JavaScript
3
star
58

domains-romance

An illustration of how domains can catch errors on your Node.js server
JavaScript
3
star
59

corrigibility

Corrigibility with Utility Preservation, in TypeScript
TypeScript
3
star
60

throw-catch-cancel-syntax

SweetJS macros for throw cancel and catch cancel
JavaScript
2
star
61

streaming-mediastreams

A spec for extracting the contents of a MediaStream object as a ReadableStream
Shell
2
star
62

diplomacy-visualizer

A visualizer for the Diplomacy board game
JavaScript
1
star
63

test262-to-mjsunit

Converts test262 tests to mjsunit tests
JavaScript
1
star
64

whatwg-participant-data-test

A dumping ground test repository for developing whatwg/participate.whatwg.org
1
star
65

baseline-tester

Runs a function against given inputs and tests the result against baseline outputs
JavaScript
1
star
66

pidgey-calc

A progressive web app that calculates how many Pidgeys you need for your next evolution spree in in Pokémon Go.
HTML
1
star