[Javascript]将image地址url转成base64的data

2022-04-08 1121点热度 0人点赞 0条评论

例如在做一些图片处理的时候,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);
});

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论