Skip to content

Instantly share code, notes, and snippets.

@SeanMcP
Created December 6, 2018 05:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeanMcP/4d65b8782d249b3c66372786b893d913 to your computer and use it in GitHub Desktop.
Save SeanMcP/4d65b8782d249b3c66372786b893d913 to your computer and use it in GitHub Desktop.
Convert an SVG to Base64
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<img id="image" />
<?xml version="1.0" standalone="no"?>
<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5" />
</svg>
</body>
<script type="text/javascript">
var serializedString = new XMLSerializer().serializeToString(document.querySelector('svg'));
var encodedData = window.btoa(serializedString);
document.getElementById('image').src = `data:image/svg+xml;base64,${encodedData}`;
</script>
</html>
@SeanMcP
Copy link
Author

SeanMcP commented Dec 6, 2018

The plan is to use this to programmatically create images for Twitter cards on a Gatsby site

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment