javascript 数据 URI 到对象 URL 与 chrome/ff 中的 createObjectURL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9388412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Data URI to Object URL with createObjectURL in chrome/ff
提问by syaz
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.
我有一个图像的 base64 字符串。如何将其转换为对象 URL?目的是通过将 Blob URL 注入 DOM 而不是非常大的 base64 字符串来尝试查看我的 svg-editor 是否会更快。这仅用于编辑 SVG。保存时,对象 URL 将再次转换为 base64。
Image size is typically 0.5 MB or bigger.
图像大小通常为 0.5 MB 或更大。
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.
我得到的是一个看似损坏的 jpeg 图像。
TIA.
TIA。
回答by imal hasaranga perera
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'));
回答by Gabamnml
What happens if you want to show html in an iframe?
如果你想在 iframe 中显示 html 会发生什么?
iframe.src = "data:text/html,"+encodeURIComponent( window.btoa(text) );
回答by Sibin John Mattappallil
If somebody want to save Data URI as an image in server:
如果有人想将数据 URI 保存为服务器中的图像:
Pass Data URI to server by post request:
通过 post 请求将数据 URI 传递给服务器:
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
保存图片: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));