【问题标题】:Data URI to Object URL with createObjectURL in chrome/ff在 chrome/ff 中使用 createObjectURL 指向对象 URL 的数据 URI
【发布时间】:2012-02-22 02:43:37
【问题描述】:

我有一张图片的 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。

【问题讨论】:

标签: javascript html


【解决方案1】:

试试这个代码。

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'));

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      通过 post 请求将数据 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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 1970-01-01
        • 2014-04-21
        • 2011-10-08
        • 1970-01-01
        • 2012-07-15
        • 2013-06-30
        相关资源
        最近更新 更多