Simple SVG To PNG/JPG Converter In JavaScript (TypeScript)

Category: Image , Javascript | May 6, 2024
Author:Janith-Umeda
Views Total:27 views
Official Page:Go to website
Last Update:May 6, 2024
License:MIT

Preview:

Simple SVG To PNG/JPG Converter In JavaScript (TypeScript)

Description:

A simple SVG-to-Image converter built with TypeScript that allows you to convert SVG files into raster image formats like PNG and JPEG on the client side.

It can be particularly helpful when you need to display SVG graphics on platforms or browsers that don’t support SVG natively or have limited SVG support.

How it works:

The SVG-to-Image converter utilizes JavaScript promises to handle asynchronous image processing.

The process starts with defining the image type and initiating a conversion function that processes each SVG URL provided.

For JPEGs, it ensures the background is white to avoid transparency issues. The SVG is loaded as an image, drawn onto a canvas adjusted to the specified dimensions, and then converted to the desired image format.

The final step is converting this canvas to a Data URL, which is then converted into a Blob URL or file.

How to use it:

1. Download & install:

# NPM
$ npm install svg-to-image-converter

2. Import the SVGToImage class into your project from the distribution. This class provides a static toBlob method that accepts the desired image type (‘png’, ‘jpg’, or ‘jpeg’), an array of SVG file URLs, and optional width and height parameters for the output image.

import SVGToImage from './dist/lib/es6/index.js';
// OR
import SVGToImage from "svg-to-image-converter";

3. This example shows how to convert an SVG file into a 512×512 pixel JPEG image and insert it into an img tag.

SVGToImage.toBlob(
  'jpg', // or png
  ['/path/to/image.svg'],
  256,256
).then((data)=>{
  const blobUrl = SVGToImage.toBlobUrl(data,data.type)
  document.querySelector("img").src = blobUrl
}).catch(console.warn)

4. Download the image directly.

SVGToImage.forceDownload(data);

5. The library also allows users to upload an SVG image with a file input as follows:

document.getElementById("svgFileInput").onchange = (evt)=>{
  SVGToImage.toBlob('png',[evt.target.files[0]],1024,1024).then((data)=>{
    document.getElementById("download").onclick = ()=>{
      SVGToImage.forceDownload(data);
    }
  }).catch(console.error);
}

Changelog:

v1.0.2 (05/06/2024)

  • Direct Download supports.
  • Direct File inputs Supports

You Might Be Interested In:


Leave a Reply