JavaScript reduce the size and quality of image with based64 encoded code

后端 未结 2 705
萌比男神i
萌比男神i 2020-11-28 06:54

I have the based64 encoded code of an image. Now I want to reduce the size and quality of the image. How can I do this in JavaScript or jQuery?

Resolve here

2条回答
  •  感动是毒
    2020-11-28 07:36

    A non-jquery solution based on @paulitto 's answer for future googlers like me:

    /**
     * Resize a base 64 Image
     * @param {String} base64 - The base64 string (must include MIME type)
     * @param {Number} newWidth - The width of the image in pixels
     * @param {Number} newHeight - The height of the image in pixels
     */
    function resizeBase64Img(base64, newWidth, newHeight) {
        return new Promise((resolve, reject)=>{
            var canvas = document.createElement("canvas");
            canvas.style.width = newWidth.toString()+"px";
            canvas.style.height = newHeight.toString()+"px";
            let context = canvas.getContext("2d");
            let img = document.createElement("img");
            img.src = base64;
            img.onload = function () {
                context.scale(newWidth/img.width,  newHeight/img.height);
                context.drawImage(img, 0, 0); 
                resolve(canvas.toDataURL());               
            }
        });
    }
    

    Use it like:

    resizeBase64Img(basedata, 50, 50).then((result)=>{
        console.log("After resize: "+result);
    });
    

提交回复
热议问题