SVG convert <g> tag to an <image> tag containing base64 PNG URI (read more)

Viewed 549

I got an interesting problem (I hope!) I have noticed that there are two "types" of SVGs

First we have the conventional SVG file with and tags for example:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 841.89 1190.55" style="enable-background:new 0 0 841.89 1190.55;" xml:space="preserve">
     <g id="Background">
        <rect id="Color1" class="st3" width="840.94" height="1190.55"/>
        <g id="Texture" class="st4">
            <path class="st5" d="M843.67,410.13c-73.29 ...

Secondly we have embedded tags in the image, not sure what to call them, so I've just named them "fake SVG", an example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="3718" height="4899" viewBox="0 0 3718 4899">
  <image id="Lager_1" data-name="Lager 1" width="185.9" height="244.95000000000002" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUh ...

My question is: Is there is any smooth way to convert a conventional SVG into a "fake" SVG? (please tell me if they have a real name). Also keep in mind that I would like to keep the groupings so each <g> should convert to a <image> tag

My thoughts: I am thinking about loading the conventional SVG into a <canvas> tag, it seems to be able to understand the <g> groupings in the conventional SVG well and consistently, and from there, somehow, convert those groups individually into base64 PNG URI, and reconstruct it into a fake SVG, perhaps there should be some library out there that can help out, does anyone have any ideas?

2 Answers

I'm not sure if this will exactly answer what you are trying to do, but you can do this:

<image id="something" href='data:image/svg+xml;utf8,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" .../>' />

Where you can just embed the original SVG as a string in the href when the encoding is set to data:image/svg+xml;utf8.

This will render the SVG in an <image> tag, but not in Base64 (I could not get this working, but there may be a way).

Source: https://css-tricks.com/probably-dont-base64-svg/

It is possible to convert an inline SVG with tags in the DOM to an image data-url. You just need to turn it into one like this:

imageTag.src = 'data:image/svg+xml,' + window.escape(svgTag.outerHTML);

The imageTag version can not have external links embedded in the SVG. It also needs width and height attributes on the SVG tag otherwise it will not show in some browsers. You could also draw this image to a canvas to rasterize the image, but as the comment mentioned that would only make it uglier if scaled.

If you want to convert it to a SVG file you should add this as a first line and then add the outerHTML of the svgTag.

<?xml version="1.0" encoding="UTF-8"?>

You can save the file with the .svg extension

Related