第一种方式
function getBase64(src, callback, outputFormat) {
let image = new Image();
image.crossOrigin = 'Anonymous';
image.onload = function () {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
image.src = src;
if (image.complete || image.complete === undefined) {
image.src = "data:image/gif;base64, R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
image.src = src;
}
}
第二种方式
function getBase64(url, callback) {
let xhRequest = new XMLHttpRequest();
xhRequest.onload = function () {
let reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhRequest.response);
};
xhRequest.open('GET', url);
xhRequest.responseType = 'blob';
xhRequest.send();
}
第三种方式
function getBase64(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status == 200) {
const blob = URL.createObjectURL(this.response);
resolve(blob);
} else {
reject(false);
}
};
xhr.send();
});
}
第四种方式
function getBase64(url, type = 'image/jpeg') {
return new Promise((resolve, reject) => {
const img = new Image()
const canvas = document.createElement('canvas');
img.crossOrigin = '*';
img.onload = function () {
const width = img.width, height = img.height;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, width, height);
const base64 = canvas.toDataURL(type);
resolve(base64);
};
img.onerror = function () {
reject(new Error('message'));
};
img.src = url;
});
}
实际应用场景中会遇到跨域的问题,需要后端来协助。
在工作中遇到这个问题的话,就需要你的后端小伙伴在服务器配置一个字段
Access-Control-Allow-Origin: *
如果服务器不配置,客户端怎么操作也是没用的。
参考链接:一个关于image访问图片跨域的问题