小程序图片压缩

本文探讨了在小程序中如何处理图片压缩的问题,特别是在iOS环境下,由于canvas尺寸限制,需确保不超过700像素以避免显示空白。文章可能涉及JavaScript、CSS和HTML的相关技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<canvas style="width:600px;height:600px;position:fixed;left:9000px;"  id="picCanvas" type="2d"></canvas>

  注:ios 的canvas尺寸不能太大,要不然会出现空白,最好在700以内

afterRead() {
   uni.chooseImage({
     count: 6, //默认9
     sizeType: ['original', 'compressed'],  //可以指定是原图还是压缩图,默认二者都有
     sourceType: ['camera','album'], //从相机或相册选择
     success: async (res: any) => {
       let f: any = res;
       const _this:any = this;
       console.log(res)
       for ( let i=0;i<f.tempFiles.length;i++){//for循环解决异步问题
          let  item = f.tempFiles[i]
         wx.showLoading({title:'图片加载...'})
         await this.$CompressedFiles(item.path,_this).then((data:any)=>{
           let index:any = item.path.lastIndexOf("//tmp/")
           let fileName:string = item.path.substring(index+6,item.path.length);
           this.fileList.push({path:item.path,base64:data,fileName:fileName});
           wx.hideLoading()
         })
       }
     }
   });
 }

$CompressedFiles(path:string,_this:any){
    return new Promise((resolve, reject)=>{
        wx.getImageInfo({
            src:path,
            success:function(res){
                //图片的宽度和高度
                let canvasRatio = 1.1;
                let path = res.path;
                let picWidth:any = res.width //图片原始长宽
                let picHeight:any = res.height
                let quality = 1;
                while (picWidth > 800 || picHeight > 800) { // 保证宽高在400以内
                    picWidth = Math.trunc(res.width / canvasRatio)
                    picHeight = Math.trunc(res.height / canvasRatio)
                    canvasRatio = canvasRatio + 0.1;
                    quality = 0.6;
                }
                const query = wx.createSelectorQuery()
                query.select('#picCanvas').fields({
                    node: true,
                    size: true
                }).exec(async (res) =>  {
                    try{

                       let canvas = res[0].node
                        let ctx = canvas.getContext('2d')
                        let dpr = wx.getSystemInfoSync().pixelRatio
                        _this.canvasWidth = picWidth / dpr
                        _this.canvasHeight = picHeight / dpr
                        canvas.width = picWidth
                        canvas.height = picHeight
                      const img = canvas.createImage()
                        img.src = path
                        img.onload = () => {
                            ctx.drawImage(img, 0, 0, picWidth, picHeight);
                            setTimeout(async () => {
                                await  wx.canvasToTempFilePath({
                                    fileType: "jpg",
                                    canvas: canvas,
                                    destWidth: picWidth,
                                    destHeight: picHeight,
                                    quality,
                                    success: async function (res:any) {
                                        console.log(2,ctx)
                                        //转为base64
                                       await wx.getFileSystemManager().readFile({
                                            filePath: res.tempFilePath,
                                            encoding: "base64",
                                            success: function (res1) {
                                                console.log(3, res.tempFilePath)
                                                let base64:any = ('data:image/png;base64,' + res1.data);
                                                resolve(base64)
                                            },
                                            fail:(res)=>{
                                                uni.showToast({
                                                    title:'图片转为base64失败',
                                                    icon:'none'
                                                })
                                            }
                                        })
                                    },
                                    fail: function (res) {
                                        console.log(res)
                                        reject(res)
                                    }
                                }, _this)
                            }, 600)
                        }
                    }catch (e) {
                    }
                })

            }
        })
    })

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值