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
Maintainers
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-pngLocal Installation (for library usage)
npm install svg-scaler-png
# or
yarn add svg-scaler-pngNote: 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.svgLibrary 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:
- Determines the base dimensions from the SVG's
width,height, orviewBoxattributes - Adjusts the rendering density (DPI) based on the scale factor (e.g., scale 4 = 288 DPI instead of 72 DPI)
- 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
