-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgetBase64.js
executable file
·44 lines (44 loc) · 1.42 KB
/
getBase64.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* @description 获取图片base64(可解决浏览器不兼容webp格式问题)
* @param {string} imgSrc - 图片地址(需要允许跨域)
* @returns {Promise}
*/
export const getBase64 = (imgSrc) => {
return new Promise((resolve, reject) => {
if (typeof FileReader !== 'undefined') {
const xhr = new XMLHttpRequest();
xhr.open('GET', imgSrc, true);
xhr.responseType = 'blob';
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200 || (xhr.status === 0 && xhr.response)) {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
}
}
};
xhr.send(null);
} else {
const img = new Image();
img.src = imgSrc;
img.crossOrigin = 'Anonymous';
img.onload = () => {
try {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
} catch (error) {
console.log(error);
reject(error);
}
};
img.onerror = (error) => reject(error);
}
});
};