Convert SVG to PNG Using Node.js & Sharp
Do you need to convert a SVG file to the Portable Network Graphic (PNG) format? This article will walk you through how to do that.
We'll use Node.js as our coding language of choice and the Sharp NPM package to do most of the heavy lifting for us.
Table Of Contents
Install Sharp Npm Package
First, you need to install the NPM package. You can install it with either the NPM or Yarn command below:
NPM:
npm install sharp --save
Yarn:
yarn add sharp
If everything went as planned, you should now have the Sharp NPM package installed.
Convert SVG to PNG
Now we're ready to start writing some code and converting an image! Make sure you have a SVG file in the root of your project directory that we can play around with.
Using the Sharp NPM package, here is the full code:
const sharp = require("sharp")
sharp("file.svg")
.png()
.toFile("new-file.png")
.then(function(info) {
console.log(info)
})
.catch(function(err) {
console.log(err)
})
Let's break down each part of the code:
- First, we import the
sharp
NPM package and hold it in thesharp
variable. - Then, we use the
sharp
package to read ourfile.svg
file, convert it to a PNG and write the new PNG file to your directory with the.toFile()
function. - The
sharp
method is a promise and we use it to get theinfo
for the file once it has been written to our directory. - Last, we use
.catch()
method to catch andconsole.log()
any errors.
When you run the code, you should get a similar output to this:
{
format: 'png',
width: 2500,
height: 527,
channels: 4,
premultiplied: false,
size: 47194
}
You should also see the new PNG file in your project directory.
There are also additional options you can pass to the .png()
method to alter the output image. These include the compression level, quality, colors, and more. You can check them out in their documentation.