Converting a SVG to URI
Converting an SVG file to a data URI allows you to include the contents of an SVG file directly in your HTML, CSS, or JavaScript, rather than linking to an external file. This can be useful for small icons or graphics, or for styling an element with an SVG background image.
To convert an SVG file to a data URI, you can use the following JavaScript function:
function svgToDataUri(svgFile) {
// Check that the file is an SVG
if (!svgFile || !svgFile.type.match('image/svg+xml')) {
throw new Error('Invalid file type. Please select an SVG file.');
}
// Read the file as a text string
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
// Encode the SVG as a data URI
const dataUri = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(reader.result);
resolve(dataUri);
};
reader.onerror = reject;
reader.readAsText(svgFile);
});
}
To use this function, you can pass in an SVG file that you've selected using a file input element. Here's an example of how you might do this:
const fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', () => {
const svgFile = fileInput.files[0];
svgToDataUri(svgFile).then(dataUri => {
// Do something with the data URI, such as displaying it in an <img> element
const imgElement = document.querySelector('#image');
imgElement.src = dataUri;
});
});
If you have a string of SVG code instead of a file, you can use the following function to convert it to a data URI:
function svgToDataUri(svgCode) {
// Encode the SVG code as a data URI
const dataUri = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgCode);
return dataUri;
}
You can then use the data URI in an <img>
element or elsewhere in your application.
With just a few lines of JavaScript, you can easily convert an SVG file or string of SVG code to a data URI.
That's it.