js图片压缩

写在前面

在移动端,手机相册里的图片基本上都大!!在传输前都须要压缩一下,百之谷之,采用cavan进行压制javascript

上代码

function _Image() {
    this.compressDefaults = {
            // 默认目标大小
            size:1024*1024,
            // 默认图片base64
            img:'',
            //默认一次压缩质量
            obj:{
                quality:0.25
            },
            //默认回调
            callback:function(){},
        }
}

_Image.prototype = {
    // 校验图片 经过check.js
    isImage:function(img){
        if(!img){
            return false;
        }
        return check.checkImg(img);
    },

    //图片转换为base64 异步
    ImageToBase64:function(param){
        var defaults = {
            file:{},
            fn:function(){},
        }
        var option = $.extend(defaults, param);


        if(!this.isImage(option.file)){
            return false;
        }

        var ready = new FileReader();
        ready.readAsDataURL(file);
        // ready.onload = option.fn;
        ready.onload = function(e){
            option.fn(e);
        };
    },
    /**
     * 将以base64的图片url数据转换为Blob
     * @param urlData
     *            用url方式表示的base64图片数据
     */
    convertBase64UrlToBlob:function(urlData){
        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);
        }
        return new Blob([u8arr], {type:mime});
    },

    // 比较base64大小
    base64LengthCompare:function(base64,size){
        _base64 = base64 + '';
        str = _base64.substring(22);
        var equalIndex= str.indexOf('=');
        if(str.indexOf('=')>0){
            str=str.substring(0, equalIndex);
        }

        var strLength=str.length;
        var fileLength=parseInt(strLength-(strLength/8)*2);

        var _size = parseInt(size);
        if(fileLength > _size){
            return 1;
        }else if(fileLength < _size){
            return -1;
        }else{
            return 0;
        }
    },

    // 压缩图片
    // param{
    //        size:目标大小
    //        img:图片文件base64
    //        obj:{width :压缩后宽,height :压缩后高,quality :压缩质量}
    // }
    compressImage:function(param){
        var option = $.extend(this.compressDefaults, param);
        if(option.size <= 0){
            return false;
        }

        if(this.base64LengthCompare(option.img,option.size) < 1){
            // 图片符合大小要求
            option.callback(option.img);
            return true;
        }

        // 利用全局temp临时保存句柄
        commonInitFn.temp._Image = {};
        commonInitFn.temp._Image.that = this;
        commonInitFn.temp._Image.compress = {};
        commonInitFn.temp._Image.compress.option = option;

        this.compress(option.img,option.obj,function(base64){
            commonInitFn.temp._Image.that.compressImage({
                size:commonInitFn.temp._Image.compress.option.size,
                img:base64,
                obj:commonInitFn.temp._Image.compress.option.obj,
                callback:commonInitFn.temp._Image.compress.option.callback,
            })
        })
    },

    // 执行压缩
    // path:base64
    // obj:{width :压缩后宽,height :压缩后高,quality :压缩质量}
    // callback:结果回调
    compress:function(path,obj,callback) {        
        var img = new Image();
            img.src = path;
        img.onload = function(){
            var that = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            // w = obj.width || w*(1/Math.sqrt(((1/obj.quality).toFixed(2)).toFixed(2)));
            w = obj.width || w*0.5;
            h = obj.height || (w / scale);

            //生成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);

            var base64 = canvas.toDataURL('image/jpeg', 1);

            callback(base64);
        }
    },

    upload:function(base64,fn){
        // base64转为Blob
        var bl = _image.convertBase64UrlToBlob(base64);
        // 上传资源
        commonInitFn.upload(bl,function(e){
            //上传完成后刷新头像
            if(e.code == '100'){
                fn(e.result.url);
            }else{
                fn(false);
            }
        })
    },


}

$(function () {
    //设置全局
    _image = new _Image();
})
相关文章
相关标签/搜索