2016-12-10 92 views
0

所以我有一個代碼,圖像編碼到Base64一個..如何刪除base64編碼圖像中的開始字符串?

function toDataUrl(url, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.responseType = 'blob'; 
    xhr.onload = function() { 
     var reader = new FileReader(); 
     reader.onloadend = function() { 
     callback(reader.result); 
     } 
     reader.readAsDataURL(xhr.response); 
    }; 
    xhr.open('GET', url); 
    xhr.send(); 
    } 

    toDataUrl('img/no_image_icon.png', function(base64Img) { 
    console.log(base64Img); // remove the data:image/png;base64, in the beginning 
    }); 

此代碼的工作,雖然我想刪除data:image/png;base64,在生成base64Img的開始。另外,如何在功能外訪問它? Like example

toDataUrl('img/no_image_icon.png', function(base64Img) { 
    var accessOutside = base64Img; // remove the data:image/png;base64, in the beginning 
    }); 

    var newVariable = accessOutside; 

任何幫助將不勝感激。

+0

[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323 #14220323)你爲什麼要刪除該標題? – Thomas

+0

@Thomas因爲在我的前端代碼(角)我已經有一個 – FewFlyBy

+0

第一:如果你已經使用角,看看[它的承諾](https://docs.angularjs.org/api/ng /服務/ $ q)*(承諾一般)*,和[我已經鏈接的線程](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from -an-asynchronous-call/14220323#14220323),這會幫助你解決異步問題。第二:你說,你在你的前端代碼中添加頭文件?不要這樣做,那兩個部分緊密地結合在一起。因此,您的前端只能使用base64編碼的PNG,而不是任何圖像的URL。你看到這是如何限制? – Thomas

回答

1

使用String.replace()方法

var base64Img = "data:image/png;base64,AAA="; 
 
base64Img = base64Img.replace("data:image/png;base64,", ""); 
 
console.log(base64Img);

+1

你可以更通用的替換:'/ data:。+?,/' – Thomas

1

首先,你需要將XHR改爲同步請求。

xhr.open('GET', url, false); 

然後將accessOutside定義爲全局變量。

toDataUrl('img/no_image_icon.png', function(base64Img) { 
    accessOutside = base64Img; // remove the data:image/png;base64, in the beginning 
    }); 

然後你可以從外面得到accessOutside值。

+0

我不知道你爲什麼需要從站點獲取價值,最好把你的業務代碼放在回調中,把xhr改成asyn。 – chaoluo

+0

不,請不要。這都是不好的做法/建議,最終會讓你陷入屁股。 – Thomas

+0

這只是一種從外部獲取價值的方法,最好將xhr更改爲asyn並在回調函數中執行您的操作 – chaoluo

相關問題