uni-app圖片壓縮轉base64位 利用遞歸來實現多張圖片壓縮

chooseImage(){
    let that =this
    uni.chooseImage({
    sizeType: ['original','compressed'], //可以指定是原圖還是壓縮圖,默認二者都有
    count: 9,//默認9
    success: (rem) => {
    console.log(rem)
    that.tempFilePaths = rem.tempFilePaths;
    //#ifdef MP-WEIXIN
        //圖片壓縮並轉base64
        that.weixin_img(0,rem)
    //#endif
                        
    //#ifdef APP-PLUS
        //圖片壓縮
        that.app_img(0,rem)    
    //#endif
                        
    }
    })
},

複製代碼

複製代碼

//app壓縮圖片  用for循環 來處理圖片壓縮 的問題,原因是 plus.zip.compressImage 方法 是異步執行的,for循環很快, 同時手機可執行的壓縮方法有限制:應該是3個吧。超出直接就不執行了。所以 原理就是 在圖片壓縮成功後 繼續 回調 壓縮函數。 以到達循環壓縮圖片的功能。
            app_img(num,rem){
                let that=this
                let index = rem.tempFiles[num].path.lastIndexOf(".");//獲取圖片地址最後一個點的位置  
                let img_type  = rem.tempFiles[num].path.substring(index+1,rem.tempFiles[num].path.length);//截取圖片類型如png jpg
                let img_yuanshi = rem.tempFiles[num].path.substring(0,index);//截取圖片原始路徑
                let d2 = new Date().getTime(); //時間戳
                //壓縮圖片
                plus.zip.compressImage(
                    {
                        src:rem.tempFiles[num].path,//你要壓縮的圖片地址
                        dst:img_yuanshi+d2+'.'+img_type,//壓縮之後的圖片地址(注意壓縮之後的路徑最好和原生路徑的位置一樣,不然真機上報code-5)
                        quality:10//[10-100]
                    },
                    function(e) {
                        console.log("Compress success!",e.target);
                        //壓縮之後路徑轉base64位的
                        //通過URL參數獲取目錄對象或文件對象
                        plus.io.resolveLocalFileSystemURL(e.target, function( entry ) {
                            // 可通過entry對象操作test.html文件 
                            entry.file( function(file){//獲取文件數據對象
                                var fileReader = new plus.io.FileReader();// 文件系統中的讀取文件對象,用於獲取文件的內容
                                //alert("getFile:" + JSON.stringify(file));
                                fileReader.readAsDataURL( file ); //以URL編碼格式讀取文件數據內容
                                fileReader.onloadend = function(evt) {//讀取文件成功完成的回調函數
                                    console.log(evt.target.result.split(",")[1])//拿到'data:image/jpeg;base64,'後面的
                                    
                                    rem.tempFiles[num].Base64_Path=evt.target.result.split(",")[1]
                                }
                            })
                        })
                        that.materialList = that.materialList.concat(rem.tempFiles[num]);
                        //利用遞歸循環來實現多張圖片壓縮
                        if(num==rem.tempFiles.length-1){
                            return
                        }else{
                            that.app_img(num+1,rem)
                        }
                        console.log('end',that.materialList)
                    },function(error) {
                        console.log("Compress error!");
                        console.log(JSON.stringify(error));
                    }    
                );
            },

複製代碼

複製代碼

    //微信壓縮
            weixin_img(num,rem){
                let that=this
                wx.getImageInfo({//獲取這個圖片 圖片壓縮
                    src: rem.tempFiles[num].path,//需要獲取的圖片 圖片選擇不用我說了吧
                    success: function (res) {
                        var ctx = wx.createCanvasContext('attendCanvasId');//使用一個canvas
                        var canvasWidth = res.width//原圖寬度 
                        var canvasHeight = res.height;//原圖高度
                        var ratio = 2;
                         // 保證寬高均在200以內
                        while (canvasWidth > 200 || canvasHeight > 200){
                            //比例取整
                            canvasWidth = Math.trunc(res.width / ratio)
                            canvasHeight = Math.trunc(res.height / ratio)
                            ratio++;
                        }
                        //繪製新圖
                        ctx.drawImage(rem.tempFiles[num].path, 0, 0, canvasWidth, canvasHeight)
                        ctx.draw(false, () => {
                            //獲取圖像數據, API 1.9.0
                            wx.canvasGetImageData({
                                canvasId: 'attendCanvasId',
                                x: 0,
                                y: 0,
                                width: canvasWidth,
                                height: canvasHeight,
                                success : (res) => {
                                    let platform = wx.getSystemInfoSync().platform
                                    if (platform == 'ios') {
                                        // 兼容處理:ios獲取的圖片上下顛倒
                                        res = that.reverseImgData(res)
                                    }
                                    // 3. png編碼
                                    let pngData = upng.encode([res.data.buffer],canvasWidth, canvasHeight)  
                                    // 4. base64編碼
                                    let base64 = wx.arrayBufferToBase64(pngData)
                                    // console.log('1111','data:image/jpeg;base64,'+base64)
                                    rem.tempFiles[num].Base64_Path=base64
                                    that.materialList = that.materialList.concat(rem.tempFiles[num]);
                                    //利用遞歸循環來實現多張圖片壓縮
                                    if(num==rem.tempFiles.length-1){
                                        return
                                    }else{
                                        that.weixin_img(num+1,rem)
                                    }
                                    console.log('end',that.materialList)
                                }
                            })
                        })
                    },
                })
                
                
            },
            // 兼容處理:ios獲取的圖片上下顛倒
            reverseImgData(res) {
                var w = res.width
                var h = res.height
                let con = 0
                for (var i = 0; i < h / 2; i++) {
                    for (var j = 0; j < w * 4; j++) {
                    con = res.data[i * w * 4 + j]
                    res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j]
                    res.data[(h - i - 1) * w * 4 + j] = con
                    }
                }
                return res
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章