SVG To PNG & Base64 Converter In JavaScript – svgToPng

Category: Image , Javascript | April 15, 2022
Author:iwstkhr
Views Total:1,489 views
Official Page:Go to website
Last Update:April 15, 2022
License:MIT

Preview:

SVG To PNG & Base64 Converter In JavaScript – svgToPng

Description:

Ever faced a problem trying to convert a usable image format like SVG to a traditional image format? Maybe you have some data that is in SVG, and you need it in a more common image format. So you think: “Why not just download it, open it and copy the contents of the file?”

Well, that won’t work because SVG doesn’t contain a regular bitmap, which is actually what’s inside the .svg file. Instead, SVG contains special instructions coded into XML that instruct the browser to do something with that image as it is being rendered.

To address this, I’d love to share you with a JavaScript library that makes it easy to convert SVG to PNG and Base64 encoded strings. It supports all the features of the SVG image and is completely written in Javascript.

How to use it:

1. Import the svgToPng.

// ES module
import { svgToPng } from '@iwstkhr/svg-to-png';
// Browser
<script src="main.js"></script>

2. Take the data from the SVG image embedded in your document and convert it into a Base64 encoded string.

// TypeScript
const svg = document.querySelector('#svg') as SVGSVGElement;
svgToPng(svg).subscribe(value => console.info(value));
// Browser
svgToPngLib.svgToPng(document.querySelector('#svg')).subscribe(function (value) {
  // do something with the value
});

You Might Be Interested In:


Leave a Reply