@svg-fns/svg2img 

Convert SVG to PNG, JPEG, WebP, AVIF, Data URL, Blob, or Buffer β isomorphic, tree-shakeable, and typed.
β¨ Overview
@svg-fns/svg2img makes it effortless to transform raw SVG strings into modern image formats.
- Isomorphic β works in Browser (Canvas API) & Node.js (Sharp).
- Tree-shakeable β zero-bloat, minimal runtime.
- Typed β written in TypeScript for DX.
- Modern formats β PNG, JPEG, WebP, AVIF.
- Resizing & fitting β scale, width/height, cover/contain/fill.
π Quick Start
import { svgToDataUrl } from "@svg-fns/svg2img";
const mySvg = `<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" fill="royalblue" />
</svg>`;
const pngDataUrl = await svgToDataUrl(mySvg, { format: "png", width: 200 });
const img = document.createElement("img");
img.src = pngDataUrl;
document.body.appendChild(img);
π¦ Installation
pnpm add @svg-fns/svg2img
npm install @svg-fns/svg2img
yarn add @svg-fns/svg2img
π For Node.js (Buffer conversion), install sharp:
pnpm add sharp
π Core API
Browser
svgToBlob(svg, options) β Blob
svgToDataUrl(svg, options) β string (data URL)
Node.js
svgToBuffer(svg, options) β Buffer
svgToDataUrlNode(svg, options) β string (data URL)
Universal
svgToDataUrl(svg, options) β auto-detects env β returns Data URL
π¨ Examples
1. Browser β JPEG Blob
import { svgToBlob } from "@svg-fns/svg2img";
const blob = await svgToBlob(mySvg, {
format: "jpeg",
quality: 0.8,
background: "#fff",
});
const url = URL.createObjectURL(blob);
document.querySelector("img")!.src = url;
2. Node.js β WebP file
import { svgToBuffer } from "@svg-fns/svg2img";
import { writeFile } from "fs/promises";
const buffer = await svgToBuffer(mySvg, {
format: "webp",
width: 500,
height: 500,
fit: "contain",
});
await writeFile("output.webp", buffer);
βοΈ Options
interface SvgConversionOptions {
format?: "png" | "jpeg" | "webp" | "avif" | "svg";
quality?: number;
width?: number;
height?: number;
scale?: number;
background?: string;
fit?: "cover" | "contain" | "fill" | "inside" | "outside";
}
format β output type (default: "svg").
fit β how to resize (cover/crop vs contain/letterbox).
scale β for high-DPI rendering.
background β useful for JPEG (no alpha).
π€ Contributing
We welcome issues & PRs!
If @svg-fns/svg2img saves you time, consider sponsoring.
Your support fuels maintenance, features & community growth.
License
This library is licensed under the MPL-2.0 open-source license.
Please enroll in our courses or sponsor our work.
with π by Mayank Kumar Chaudhari