How to Encode SVG as Base64 (and When You Actually Need To)
Converting an SVG to base64 means encoding the file's text content as a base64 string, usually to embed it as a data URI in CSS or HTML. You can do it in JavaScript with two lines of code, or paste the SVG into a converter and copy the result. The more useful question is whether you need base64 at all. Often you don't. What base64 encoding actually does SVG files are XML: plain text. Base64…
Encoding an SVG into base64 involves transforming the SVG file's text content into a base64 string, typically to embed it as a data URI in CSS or HTML. This can be achieved using JavaScript with just two lines of code, or by using an online converter. While the more pertinent question is whether base64 is necessary, the answer is often no. Base64 encoding transmits XML-based SVG files as a string that only uses safe characters, making it suitable for embedding in CSS properties, JSON values, or HTML attributes without disrupting the surrounding format.
However, this encoding process triples the file size. The encoded string is then enclosed in a data URI to help the browser understand how to treat it. For instance, `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5...` signifies that the browser should read the data after the comma as image content. To perform this encoding in JavaScript, you can use two lines: first, store the SVG content in a string variable, then convert it to base64 using `btoa()`.
Due to its limitation of handling only Latin-1 characters, you may need to percent-encode and unescape the SVG string before encoding it with `btoa()`. Using base64 encoding for CSS background images is common, as it allows referencing the SVG without a separate file request. However, URL-encoding the SVG instead of base64-encoding it is another option.
While base64 encoding is larger, URL encoding is more compact and compresses better with gzip, resulting in a smaller overall CSS. In most cases, though, URL encoding is the preferable choice. On the command line, base64 encoding can be done using `base64 -i icon.svg` on macOS or Linux, or `certutil -encodehex icon.svg icon.b64` on Windows.
These commands output the base64 string. Base64 encoding is not needed when embedding the SVG directly in an HTML file, as inline SVG offers both a smaller file size and direct access to the SVG's internal elements via CSS and JavaScript.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.