Quantcast
Channel: Convert SVG to image (JPEG, PNG, etc.) in the browser - Stack Overflow
Viewing all articles
Browse latest Browse all 17

Answer by klues for Convert SVG to image (JPEG, PNG, etc.) in the browser

$
0
0

Here a function that works without libraries and returns a Promise:

/** * converts a base64 encoded data url SVG image to a PNG image * @param originalBase64 data url of svg image * @param width target width in pixel of PNG image * @return {Promise<String>} resolves to png data url of the image */function base64SvgToBase64Png (originalBase64, width) {    return new Promise(resolve => {        let img = document.createElement('img');        img.onload = function () {            document.body.appendChild(img);            let canvas = document.createElement("canvas");            let ratio = (img.clientWidth / img.clientHeight) || 1;            document.body.removeChild(img);            canvas.width = width;            canvas.height = width / ratio;            let ctx = canvas.getContext("2d");            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);            try {                let data = canvas.toDataURL('image/png');                resolve(data);            } catch (e) {                resolve(null);            }        };        img.onerror = function() {            resolve(null);        };        img.src = originalBase64;    });}

On Firefox there is an issue for SVGs without set width / height.

See this working example including a fix for the Firefox issue.


Viewing all articles
Browse latest Browse all 17

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>