Skip to content

How to Generate Images from SVG

In this article, we will learn how to generate images with different sizes from SVG.

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