圖片轉(zhuǎn)成base64
關(guān)于更多日常使用的公共類的操作方法,可以關(guān)注下小滑輪網(wǎng)站 http://www.feiaci.com/#/self/code
/**
* 蔣圖片轉(zhuǎn)成base64
* width、height調(diào)用時傳入具體像素值,控制大小 ,不傳則默認圖像大小
* 可以會有跨域問題,建議是同源
* @param imgSrc 圖片地址
* @param width
* @param height
* @returns {string}
*/
function getBase64Image(imgSrc, width, height) {
return new Promise((resolve) => {
const newImg = new Image();
newImg.setAttribute('crossOrigin', 'anonymous');
newImg.src = imgSrc;
const canvas = document.createElement('canvas');
canvas.width = width || img.width;
canvas.height = height || img.height;
const ctx = canvas.getContext('2d');
newImg.onload = function () {
ctx.drawImage(newImg, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/png', 1);
resolve(dataURL);
};
});
}