Created
February 22, 2025 17:06
Conversion of SVG to data-uri format with prefix data:image/svg+xml - a primer in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on https://github.com/tigt/mini-svg-data-uri/issues/24 | |
// Usage: cat myicon.svg | node svgdataurify.js | |
let svg = ""; | |
process.stdin.on("data", (chunk) => { svg += chunk; }); | |
process.stdin.on("end", async () => | |
{ | |
const reWhitespace = /\s+/g, reUrlHexPairs = /%[\dA-F]{2}/g, hexDecode = {'%20': ' ', '%3D': '=', '%3A': ':', '%2F': '/'}, specialHexDecode = match => hexDecode[match] || match.toLowerCase(); | |
if(svg.charCodeAt(0) === 0xfeff) svg = svg.slice(1); | |
svg = svg.trim().replace(reWhitespace, ' ').replaceAll('"', '\''); | |
svg = encodeURIComponent(svg); | |
svg = svg.replace(reUrlHexPairs, specialHexDecode); | |
const datauri = 'data:image/svg+xml,' + svg.replace(/ /g, '%20'); | |
console.log(datauri); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment