Creating SVG to PNG Converter Using Node.js & Sharp

Do you want to know how to convert SVG images to regular PNG? Well, there are plenty of SVG to PNG online converters available, but as a programmer let’s make our own.

In this article, we will learn about the Sharp module in Node.js which can convert SVG to PNG in a few lines of code. Let’s get started.

What is Scalable Vector Graphics?

Scalable vector graphics or SVG is a special kind of image format. Unlike regular pictures, SVG images are like flexible drawings that can change size without losing their quality. They use a special code called XML to describe the shapes and colours. SVG images are great for websites that need different-sized images. They can move, change colours, and even respond to clicks.

Need for SVG to PNG Conversion

  • Some old internet browsers don’t understand SVG files well. So, turning SVG into PNG helps our pictures show up nicely everywhere.
  • When we want to share our pictures with others, turning them into a PNG file format can be handy because it is widely recognized and supported.
  • PNG images load fast on websites, making sure people don’t have to wait too long to see cool pictures.
  • This conversion can also help us compress the size without losing quality. This helps us upload it to places where a low size is required or to save our own memory space.

Node.js Sharp Library

Sharp in Node.js is a speedy image-processing wizard. This library provides a range of functionalities for tasks such as resizing, cropping, rotating, and image compression. It is a trusted tool, always getting better with regular updates. It is the best way to convert to PNG format in Node.js.

Installation:

To use Sharp in your Node.js project, you need to first install it. Run the given command in your terminal:

npm install sharp
Sharp Install

Convert SVG Files to PNG Format in Node.js

Imagine you have a project where you want to create drawings of trees in SVG format. Later, you also want to convert these SVG drawings into PNG images. Let’s see how.

Create a file named index.js and write the following code:

const fs = require('fs');
const sharp = require('sharp');

// Create a simple SVG content
const svgContent = `
<svg width="200" height="300" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="skyblue" />

<!-- Tree trunk -->
<rect x="80" y="150" width="40" height="100" fill="saddlebrown" />

<!-- Tree leaves -->
<circle cx="100" cy="100" r="60" fill="forestgreen" />
<circle cx="140" cy="140" r="50" fill="forestgreen" />
<circle cx="60" cy="140" r="50" fill="forestgreen" />
</svg>
`;

// Save the SVG content to a file
fs.writeFileSync('example.svg', svgContent, 'utf-8');

// Convert SVG to PNG using sharp
sharp('example.svg')
  .png()
  .toFile('example.png')
  .then(() => {
    console.log('SVG successfully converted to PNG');
  })
  .catch(error => {
    console.error('Error converting SVG to PNG:', error);
  });

Explanation:

  • We use the fs library to help with reading and writing files and the sharp library for converting images.
  • Then we write the XML SVG code, This is like giving instructions to draw a sky-blue background, a brown tree trunk, and green leaves. And we are wrapping these instructions in a variable named svgContent.
  • It is then saved in a file called example.svg.
  • Then the drawing that was saved as example.svg is to be taken and transformed into a picture file named example.png. If the process goes smoothly, you get the “SVG successfully converted to PNG” message displayed. However, if any issues arise, the error is shown.

Run the following command in the terminal to run your node file:

node index.js
Svg Converted Successfully
Console
Tree Result
example.png
Before And After
Two new sections were created after running the code

And that’s it! We have just created a project where we have a tree SVG and then we turn it into a PNG image.

Performance Benefits of Using Sharp for SVG to PNG Conversion

  • Sharp is fast as it uses native bindings to low-level libraries like libvips for quicker performance compared to pure JavaScript.
  • It is ideal for handling multiple conversions simultaneously.
  • It is recognized for its low memory usage, making it efficient for processing large images. 
  • Sharp supports streaming, enabling image processing without loading the entire image into memory.
  • Sharp is faster than PhantomJS for SVG to PNG conversion, especially in server-side applications.
  • It also surpasses Inkscape and CairoSVG as it excels in large-scale batch processing.

Summary

This article is your guide to using the Sharp library in Node.js to turn cool, flexible SVG drawings into regular PNG images. It explains why you might want to do this and walks you through the process with a simple example. Sharp is highlighted for its speed and efficiency, making the conversion a breeze. 

Further Reading:

Reference

https://www.npmjs.com/package/sharp

Snigdha Keshariya
Snigdha Keshariya
Articles: 98