1

I do not know if I'm asking in the correct "Stack", but at the moment I seem to be the most appropriate one. Let me also note if I'm wrong, I'll immediately move the question to another Stack.

I need to save a vector image (most likely it will be SVG format). We are considering how to memorize this image. The point is that we prefer to use only a JSON file, which means that you have to convert the SVG image to at least Base54, but is it lossless or not?

The alternative would be to save the local path of this SVG image in a field in the JSON file. This image and JSON files should not be sent over the network and conversion from Bas64 to SVG should not be too slow considering a PC environment. Based on your experiences, what do you recommend doing?

peak
  • 105,803
  • 17
  • 152
  • 177
shogitai
  • 1,823
  • 1
  • 23
  • 50

2 Answers2

5

base64 is a simple serialization algorithm, no loss involved.

But then, SVG is already a serialized (XML) string format, encoded in utf-8. There is no need to use an extra serialization layer, and no problem in storing it in a JSON file, which is also in utf-8 (apart from the need to escape double quotes). If you don't want to use base64, data URLs (which you might be aiming for, you didn't say) can also contain plain XML data. Like this:

data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg">...</svg>

(Make sure to url-excape # as %23.)

Performance is something you need to test for yourself. In a specific use case I decided to use a JSON file containing base64-encoded strings because it was in fact the most performant solution, but that is no precedence you can rely on.

ccprog
  • 20,308
  • 4
  • 27
  • 44
4

You could use jq to encode the contents of the .svg file as a JSON string, e.g.

jq -Rs . media.svg

Of course, you would probably want to use a more complex jq filter to embed the contents of the .svg file in your JSON.

As implied by the answers at Does SVG support embedding of bitmap images? you should not need to base64-encode a SVG, but if you do need to base64-encode something, you can use jq's @base64 filter. You can verify this works for some file (say FILENAME) by decoding the string and comparing with the original. If your jq has @based64d, this can be done by:

diff FILENAME <(jq -Rs @base64 FILENAME | jq -r @base64d)
peak
  • 105,803
  • 17
  • 152
  • 177