例如在做一些图片处理的时候,img标签需要加载src为data base64的图片格式,有时候也需要把url(例如https://www.example.com/test.jpg)转成base64的data。
类似这样子的格式:<img src="data:image/jpg;base64,abc123..." />
工具方法和使用示例如下:
// 把imageUrl转成base64的Data
function imageUrlToBase64Data(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
// 使用:
var imageUrl = "https://www.example.com/test.jpg";
imageUrlToBase64Data(imageUrl, function(base64Data) {
console.log(base64Data);
});
// 把imageUrl转成base64的Data
function imageUrlToBase64Data(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
// 使用:
var imageUrl = "https://www.example.com/test.jpg";
imageUrlToBase64Data(imageUrl, function(base64Data) {
console.log(base64Data);
});
// 把imageUrl转成base64的Data function imageUrlToBase64Data(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function() { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); } // 使用: var imageUrl = "https://www.example.com/test.jpg"; imageUrlToBase64Data(imageUrl, function(base64Data) { console.log(base64Data); });
文章评论