Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data URI to Object URL with createObjectURL in chrome/ff

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.

like image 571
syaz Avatar asked Feb 22 '12 02:02

syaz


People also ask

What is URL createObjectURL ()?

createObjectURL() The URL. createObjectURL() static method creates a string containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

What is revokeObjectURL URL?

The URL revokeObjectURL() method releases an existing object URL which was created by using URL createObjectURL(). This method is called when you are finished using an object URL and don't want the browser to keep the reference to that file any longer. Syntax: URL.

Is Blob a URL?

Blob URLs contain pseudo protocols that can create a temporary URL to audio and video files. This type of URL essentially acts as a fake source for the media on the website, so you can't download it directly. Instead, you have to use third-party conversion tools. First, however, you have to find the blob URL itself.

What is data URL in Javascript?

A Data URL is a URI scheme that provides a way to inline data in a document, and it's commonly used to embed images in HTML and CSS.


1 Answers

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'));
like image 122
imal hasaranga perera Avatar answered Sep 28 '22 21:09

imal hasaranga perera