圖片轉(zhuǎn)成base64

圖片轉(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);
        };
    });
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容