by Timur Dautov

How to Generate PNG Images from SVG with Node.js

In this article, we will learn how to generate images with different sizes from SVG. Chrome Web Store icons are a common reason to do this; the extension build is in How to Build a Chrome Extension.

Basically we will use sharp npm library: https://github.com/lovell/sharp

Generate Images with Different Sizes from SVG#

Step 1: Install Sharp#

npm install sharp

Step 2: Create a Script to Generate Images#

import sharp from "sharp";
import fs from "fs";
import path from 'path';

const inputSvg = "public/icons/notes.svg"; // Path to your SVG file
const outputSizes = {
  "16": "public/icons/icon16.png",
  "32": "public/icons/icon32.png",
  "48": "public/icons/icon48.png",
  "128": "public/icons/icon128.png",
};

// Ensure the output directory exists
fs.mkdirSync("public/icons", { recursive: true });

async function convertIcons() {
  for (const [size, outputPath] of Object.entries(outputSizes)) {
    await sharp(inputSvg)
      .resize(parseInt(size), parseInt(size)) // Resize to the given size
      .png()
      .toFile(outputPath);
    console.log(`Generated: ${outputPath}`);
  }
}

convertIcons().catch(console.error);

Step 3: Run the Script#

node generate-images.js

Step 4: Check the Output#

ls -l public/icons

Comments