2012-02-22 70 views
4

我有一個圖像的base64字符串。我怎樣才能將它轉換爲對象URL?目的是通過將Blob URL注入到DOM而不是一個非常大的base64字符串來嘗試查看我的svg編輯器是否會更快。這僅用於編輯SVG。在保存時,對象URL會重新轉換爲base64。在chrome/ff中使用createObjectURL的數據URI到對象URL

圖像大小通常爲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。

+0

只是,如果你能得到更好的表現出這種奇怪的?當我有太多的數據網址時,我也遇到了問題,我想知道是否將它們保留爲對象網址會更好。 – 2014-02-05 23:57:02

回答

3

Convert Data URI to File then append to FormData

在上述問題的作品答案。我只需要從上面的函數中獲取我的blob,並且圖像將呈現得很好。

我想我忽略了base64編碼字符串的字符串處理部分。 String.charCodeAt()就是答案。

0

如果要在iframe中顯示html,會發生什麼情況?

iframe.src = "data:text/html,"+encodeURIComponent(window.btoa(text)); 
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'));