npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

svg-scaler-png

v1.0.0

Published

A Node.js library to convert SVG to scaled PNG, JPEG, or WebP with CLI support

Downloads

11

Readme

SVG Scaler PNG

A powerful Node.js library and command-line tool to convert SVG images to PNG, JPEG, or WebP with flexible scaling options. This library uses Sharp for high-performance image processing.

Features

  • Convert SVG to PNG, JPEG, or WebP formats
  • Apply custom scaling factors (1x, 2x, 4x, etc.)
  • Set output quality for lossy formats
  • Add background colors to transparent SVGs
  • Control density for higher detail
  • Use as a library in your Node.js code OR as a command-line tool
  • No external dependencies beyond Sharp

Installation

Global Installation (for CLI)

npm install -g svg-scaler-png

Local Installation (for library usage)

npm install svg-scaler-png
# or
yarn add svg-scaler-png

Note: Sharp often requires compilation during installation, which might need build tools. See the Sharp installation documentation if you encounter issues.

Command-Line Usage

Once installed globally, you can use the svg-scaler-png command:

svg-scaler-png [options] <input-svg-file>

Options

| Option | Description | |--------|-------------| | -h, --help | Show help message | | -v, --version | Show version number | | -o, --output <file> | Output file path (default: <input-name>.<format> in current working directory) | | -s, --scale <factor> | Scale factor (default: 4) | | -d, --density <dpi> | Base density in DPI (default: 72) | | -f, --format <format> | Output format: png, jpeg, or webp (default: png) | | --background <color> | Background color (e.g., white, #FFF) | | --quality <value> | Output quality for jpeg/webp (0-100, default: 80) |

Examples

# Basic conversion with default settings (4x scale, PNG format in current directory)
svg-scaler-png logo.svg

# 2x scaling
svg-scaler-png -s 2 logo.svg

# 1x scaling with custom output path
svg-scaler-png -s 1 -o logo-large.png logo.svg

# Convert to JPEG with white background and 90% quality
svg-scaler-png --format jpeg --quality 90 --background white logo.svg

Library Usage

import { convertSVGToPNG, parseSVGDimensions, calculateOutputDimensions } from 'svg-scaler-png';
import fs from 'fs/promises';
import path from 'path';

// Example: Convert SVG to PNG with 2x scaling
async function example() {
  try {
    // You can provide SVG content as a string
    const svgString = `<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
                      </svg>`;
    
    // Or read from a file
    // const svgString = await fs.readFile('path/to/your.svg', 'utf8');
    
    const scaleFactor = 2;
    const outputPath = path.join(process.cwd(), 'output_x2.png');
    
    // Option 1: Convert and save directly to file
    await convertSVGToPNG(svgString, scaleFactor, outputPath);
    console.log(`PNG saved to ${outputPath}`);
    
    // Option 2: Get the image as a Buffer
    const imageBuffer = await convertSVGToPNG(svgString, scaleFactor);
    console.log(`Generated image buffer (${imageBuffer.length} bytes)`);
    
    // Option 3: Advanced options
    await convertSVGToPNG(svgString, scaleFactor, 'output_custom.jpeg', {
      format: 'jpeg',
      quality: 90,
      background: 'white'
    });
    
    // Bonus: You can also calculate the dimensions of the output image
    const dimensions = await calculateOutputDimensions(svgString, scaleFactor);
    console.log(`Output dimensions will be ${dimensions.width}x${dimensions.height} pixels`);
    
  } catch (error) {
    console.error('Conversion failed:', error);
  }
}

API Reference

convertSVGToPNG(svgInput, scale, [outputFilePath], [options])

Converts an SVG to PNG, JPEG, or WebP image with scaling.

  • svgInput (String | Buffer): The SVG content.
  • scale (Number): The scaling factor (e.g., 1, 2, 4, 0.5). Default is 4 when using CLI.
  • outputFilePath (String, Optional): If provided, saves to this file. If omitted, returns a Buffer.
  • options (Object, Optional): Additional conversion options:
    • format (String): Output format: 'png', 'jpeg', or 'webp' (default: 'png')
    • quality (Number): Quality for JPEG/WebP (1-100, default: 80)
    • background (String): Background color (default: transparent)
    • density (Number): Custom density in DPI (overrides scale calculation)

Returns: Promise<Buffer | void> - Buffer with the image data if outputFilePath is omitted, or void when the file is written.

parseSVGDimensions(svgString)

Extracts width and height from an SVG string.

  • svgString (String): The SVG content.

Returns: Object with width and height properties (null if not found).

calculateOutputDimensions(svgInput, scale)

Calculates the expected dimensions of the output image after applying the scale factor.

  • svgInput (String | Buffer): The SVG content.
  • scale (Number): The scaling factor to apply.

Returns: Promise<Object> with width and height properties.

Error Handling

The library provides detailed error messages with helpful suggestions when things go wrong. All errors are instances of SVGConverterError and include:

  • An error code identifying the type of error (e.g., INVALID_INPUT, FILE_ERROR)
  • A detailed error message
  • Suggestions on how to resolve the issue

How Scaling Works

SVG is a vector format without inherent pixel dimensions. To rasterize an SVG to a bitmap format (PNG/JPEG/WebP) at different scales, this library:

  1. Determines the base dimensions from the SVG's width, height, or viewBox attributes
  2. Adjusts the rendering density (DPI) based on the scale factor (e.g., scale 4 = 288 DPI instead of 72 DPI)
  3. Renders the SVG at this higher density, resulting in more pixels in the output

This approach preserves the SVG's vector quality while allowing precise control over the output size.

License

ISC