chrome/ff中带有createObjectURL的对象URL的数据URI

Data URI to Object URL with createObjectURL in chrome/ff

本文关键字:对象 URL 数据 URI createObjectURL ff chrome      更新时间:2023-09-26

我有一个图像的base64字符串。如何将其转换为对象URL?目的是通过将Blob URL注入DOM而不是一个非常大的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

相反,我得到的是一个似乎损坏的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});
}

并像这个一样使用它

var objecturl = URL.createObjectURL(dataURItoBlob('your data url goes here'));

如果您想在iframe中显示html,会发生什么?

iframe.src = "data:text/html,"+encodeURIComponent( window.btoa(text) );

如果有人想将数据URI保存为服务器中的映像:

通过邮寄请求将数据URI传递到服务器:

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

保存图像: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));