Search code examples
javascripttypescriptsvgdata-uriidenticon

Convert Data URI to Blob


I'm currently using Jdenticon library for generating user identicons as a default profile picture. I'd like to convert the data URI for SVG to a Blob or make it as an image file so that I could store an image file into Firebase.

I've tried a few example code from Stack Overflow, but none of them were worked for me. (I've not converted the data into base64. I don't think SVG syntax has any crazy characters in it.)

createIdenticonBlob(hash: string) {
  if (hash) {
    let svg = jdenticon.toSvg(hash, Math.min(50, 50));
    let uri = "data:image/svg+xml," + encodeURIComponent(svg);
    return this.uploadService.convertDataURIToBlob(uri); // I'm not sure :(
  }
}

jdenticon.toSvg(hash|value, size[, padding])

I'm not sure how to convert Data URI to an image file. Any thoughts?


Solution

  • You don't want to convert a dataURI to a file, you want to make a file from the svg markup, which is just text, and if your plugin really returns an svg markup, this is really easy to do:

    createIdenticonBlob(hash: string) {
      if (hash) {
        let svg = jdenticon.toSvg(hash, Math.min(50, 50));
        let blob = new Blob([svg], {type: 'image/svg+xml'});
        return blob;
      }
    }