記錄以下uniapp寫小程序然后進行圖片上傳壓縮


今天記錄一下uniapp寫小程序上傳圖片壓縮的功能

首先定義上傳圖片的方法

 

 

然后res.tempFilePath[0]就是圖片的臨時路徑

其次定義壓縮圖片然后獲取壓縮后圖片大小的方法,方法使用canvas

首先咱們寫一個canvas的標簽

 

 

 在data里定義寬和高首先先為0

最后定義壓縮圖片的方法,這個我直接放代碼,方便各位小伙伴復制

// 圖片壓縮
            compressImage(src) {
                let that = this
                uni.getImageInfo({
                    src,
                    success(res) {
                        var ratio = 2;
                        var canvasWidth = res.width //圖片原始長寬
                        var canvasHeight = res.height
                        while (canvasWidth > 400 || canvasHeight > 400) { // 保證寬高在400以內
                            canvasWidth = Math.trunc(res.width / ratio)
                            canvasHeight = Math.trunc(res.height / ratio)
                            ratio++;
                        }
                        that.cWidth = canvasWidth
                        that.cHeight = canvasHeight
                        var ctx = uni.createCanvasContext('canvas')

                        ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)

                        ctx.draw(false, setTimeout(() => {
                            uni.canvasToTempFilePath({
                                canvasId: 'canvas',
                                destWidth: canvasWidth,
                                destHeight: canvasHeight,
                                fileType: 'jpg',
                                quality: 0.4,
                                success: function(res1) {
                                    uni.getFileInfo({
                                        filePath: res1.tempFilePath,
                                        success(ress) {
                                            console.log(ress)
                                        }
                                    })

                                },
                                fail: function(res) {
                                    console.log(res.errMsg)
                                }
                            })
                        }, 100)) //留一定的時間繪制canvas
                    },
                    fail(err) {
                        console.log(err.errMsg)
                    }
                })
            },

最后壓縮后的圖片大小就在ress里面了,圖片臨時路徑是在res1中

今天的記錄就到此了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM