关于javascript:图片转成base64

图片转成base64

对于更多日常应用的公共类的操作方法,能够关注下小滑轮网站 http://www.feiaci.com/#/self/…

/**
 * 蒋图片转成base64
 * width、height调用时传入具体像素值,管制大小 ,不传则默认图像大小
 * 能够会有跨域问题,倡议是同源
 * @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);
        };
    });
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理