我有一个图像的base64字符串.如何将其转换为对象URL?目的是通过向DOM注入Blob URL而不是非常大的base64字符串来尝试查看我的svg编辑器是否会更快.这仅用于编辑SVG.在保存时,对象URL将再次重新转换为base64.
图像大小通常为0.5 MB或更大.
我尝试过的:
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
Run Code Online (Sandbox Code Playgroud)
我得到的是一个看似腐败的jpeg图像.
TIA.
试试这个代码。
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});
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
var objecturl = URL.createObjectURL(dataURItoBlob('your data url goes here'));
Run Code Online (Sandbox Code Playgroud)
如果你想在 iframe 中显示 html 会发生什么?
iframe.src = "data:text/html,"+encodeURIComponent( window.btoa(text) );
Run Code Online (Sandbox Code Playgroud)