1. 程式人生 > >uni-app圖片壓縮轉base64位 利用遞迴來實現多張圖片壓縮

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
            }
        }

微信小程式壓縮圖片需要用到

const upng = require('../../static/js/upng.js');和pake.min.js去下載兩個檔案放一起

地址https://github.com/zh8637688/wx-cardscanner/tree/master/cardscanner/upng-js