5

I have base64 string of an image. How can I convert this to Object URL? The purpose is to try and see if my svg-editor will be faster, by injecting Blob URL to the DOM instead of a very large base64 string. This is used for editing the SVG only. On save, Object URLs are reconverted to base64 again.

Image size is typically 0.5 MB or bigger.

What I've tried:

var img = ...; //svg <image>
var bb = new BlobBuilder();
var dataStr = img.getAttributeNS(XLINKNS, 'href'); //data:image/jpeg;base64,xxxxxx
//dataStr = dataStr.replace(/data:.+;base64,/i, ''); //Strip data: prefix - tried both with & without
//dataStr = window.atob(dataStr); //tried both with & without

bb.append(dataStr);
var blob = bb.getBlob
img.setAttributeNS(XLINKNS, 'xlink:href', window.URL.createObjectURL(blob)); //blob:xxx

What I get instead is a seemingly corrupted jpeg image.

TIA.

syaz
  • 2,659
  • 6
  • 36
  • 44
  • 2
    Just curious if you were able to get better performance out of this? I'm also running into problems when I have too many data urls, I'm wondering if keeping them as object urls will work better. – Frank Schwieterman Feb 05 '14 at 23:57
  • Possible duplicate of [Convert Data URI to File then append to FormData](https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata) – Herohtar Jul 08 '19 at 19:16

3 Answers3

9

Try this code.

function dataURItoBlob(dataURI) {
  var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var binary = atob(dataURI.split(',')[1]);
  var array = [];
  for (var i = 0; i < binary.length; i++) {
     array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {type: mime});
}

and use it like this

var objecturl = URL.createObjectURL(dataURItoBlob('your data url goes here'));
Imal Hasaranga Perera
  • 9,683
  • 3
  • 51
  • 41
0

What happens if you want to show html in an iframe?

iframe.src = "data:text/html,"+encodeURIComponent( window.btoa(text) );
Gabamnml
  • 146
  • 1
  • 10
0

If somebody want to save Data URI as an image in server:

Pass Data URI to server by post request:

var imgData = canvas.toDataURL('image/png');
$.post("https://path-to-your-script/capture.php", {image: imgData},
    function(data) {
        console.log('posted');
});

Save image: capture.php

$data = $_POST['image'];

// remove "data:image/png;base64," from image data.
$data = str_replace("data:image/png;base64,", "", $data);

// save to file
file_put_contents("/tmp/image.png", base64_decode($data));
Sibin John Mattappallil
  • 1,739
  • 4
  • 23
  • 37