js圖片壓縮 原

寫在前面

在移動端,手機相冊裏的圖片基本上都大!!在傳輸前都需要壓縮一下,百之谷之,採用cavan進行壓制

上代碼

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();
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章