js 前端 图片压缩

/**
File图片类型
callback回调函数,里面传压缩后的File
**/

function compress(file,callback){
    var ms = file.size/1024;
    console.log("压缩前的大小"+file.size);
    if(ms>249) {
        var ready = new FileReader();
        ready.onload = function () {
         // ready.readAsDataURL(file);
        var path = this.result;
        var img = new Image();
        img.onload = function () {
            var that = this;
            var w = that.width,
                h = that.height
            scale = w / h;

            if (w > 1000) {// 宽大大于1000的话。
                w = 1000;
                h = w / scale;
            }

            var quality = 0.5; // quality 值越小,绘制出的图片越模糊  图片大小为10000,压缩为0.2 大小为2000,压缩1,大小为4000,压缩0.5
            // 生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');

            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);

            // 将base64的图片数据转换成blob
            var urlData = canvas.toDataURL('image/jpeg', quality);

            var arr = urlData.split(","), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }

            var blobfile = new Blob([u8arr], {type: mime});
			console.log("压缩前的大小"+blobfile.size);
            // callback
            callback(blobfile);
        }

        img.src = this.result;
        console.log(img.src);


    }


    ready.readAsDataURL(file);




}else {
    callback(file);
}
}

你可能感兴趣的:(js,前端,js图片压缩,纯前端原生)