node base64 svg to png

To convert a base64 SVG image to PNG using Node.js, you can follow these steps:

  1. Require the necessary modules:
  2. fs: This module is used to read and write files.
  3. canvas: This module allows us to create a canvas on which we can draw the SVG image and convert it to PNG.

  4. Read the base64 SVG image data from a file or a variable.

  5. Decode the base64 SVG image data to a string using the Buffer object's from method and specifying the base64 encoding.

  6. Create a new canvas object with the desired width and height. This can be done using the createCanvas method from the canvas module.

  7. Obtain a 2D rendering context for the canvas using the getContext method.

  8. Use the DOMParser object to parse the SVG string and create an SVG document.

  9. Draw the SVG image onto the canvas using the drawImage method. Pass the SVG document's root element as the source.

  10. Convert the canvas to a PNG image data URL using the toDataURL method.

  11. Extract the base64 PNG image data from the data URL by removing the prefix (data:image/png;base64,).

  12. Write the base64 PNG image data to a file or use it as needed.

Here is an example code snippet to illustrate the steps:

const fs = require('fs');
const { createCanvas, loadImage } = require('canvas');

// Read the base64 SVG image data
const base64SVG = fs.readFileSync('image.svg', 'utf-8');

// Decode the base64 SVG image data
const svgString = Buffer.from(base64SVG, 'base64').toString('utf-8');

// Create a new canvas
const canvas = createCanvas(500, 500);
const context = canvas.getContext('2d');

// Parse the SVG string and create an SVG document
const parser = new DOMParser();
const svg = parser.parseFromString(svgString, 'image/svg+xml');

// Draw the SVG image onto the canvas
context.drawImage(svg.documentElement, 0, 0);

// Convert the canvas to a PNG image data URL
const pngDataURL = canvas.toDataURL('image/png');

// Extract the base64 PNG image data
const base64PNG = pngDataURL.replace(/^data:image\/png;base64,/, '');

// Write the base64 PNG image data to a file or use it as needed
fs.writeFileSync('image.png', base64PNG, 'base64');

Remember to install the required dependencies by running npm install canvas before running the code.