Picture to Base64

Time:2020-10-31

Picture to Base64

For more daily use of the public class operation method, you can pay attention to the small pulley websitehttp://www.feiaci.com/#/self/…

/**
 *Change Jiang's picture to Base64
 *When width and height are called, the specific pixel value is passed in to control the size. If not, the default image size is used
 *There may be cross domain problems, and the proposal is homologous
 *@ param imgsrc image address
 * @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);
        };
    });
}