How to compress image size in JavaScript?

前端 未结 2 378
广开言路
广开言路 2020-12-18 17:23

I am trying to compress image size using JavaScript. but it returns canvas error. below is my code.

 var reader = new FileReader();
        reader.readAsDat         


        
2条回答
  •  醉梦人生
    2020-12-18 17:46

    You might have to resize the canvas size

    refer the following example here

    function resizeImg(base, width, height) {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        var context = canvas.getContext("2d");
        var deferred = $.Deferred();
        $("").attr("src", "data:image/gif;base," + base).load(function() {
            context.scale(width/this.width,  height/this.height);
            context.drawImage(this, 0, 0); 
            deferred.resolve($("").attr("src", canvas.toDataURL()));               
        });
        return deferred.promise();    
    }
    

提交回复
热议问题