微信小程序对上传的图片进行裁剪

  1. 背景:

使用uniapp中uni.chooseImage的裁剪参数crop只能在App中生效,在微信小程序中不生效。

  1. 实现思路

  1. uni.chooseImage打开相册获取图片路径(uni.chooseImage(OBJECT) | uni-app官网 (dcloud.net.cn)

  1. 将获取到的图片路径传入wx.cropImage对图片进行裁剪(wx.cropImage(Object object) | 微信开放文档 (qq.com)

  1. 将裁减后的图片路径通过uni.uploadFile上传到服务器生成网络地址(uni.uploadFile(OBJECT) | uni-app官网 (dcloud.net.cn)

  1. 代码如下:

                // 1 打开相册获取图片路径
                uni.chooseImage({
                    count: 1, //默认选取1张图片
                    sourceType: ['album'], //从相册选择
                    success: function (res) {
                        // 2 对获取到的图片进行裁剪
                        wx.cropImage({
                          src: res.tempFilePaths[0], // 图片路径
                          cropScale: '1:1', // 裁剪比例
                          success:function(res){
                              // 3 将裁剪好的图片上传到服务器
                              uni.uploadFile({
                                  url: app.globalData.miniComent,//自己服务器的路径
                                  filePath: res.tempFilePath,//图片地址
                                  name: 'file',
                                  formData: {
                                      userCode:that.userCode
                                  },
                                  success: (res1) => {
                                      let url = JSON.parse(res1.data).data
                                      console.log(url,"裁剪成功后的图片网络地址");
                                      that.userInfo.headimgurl = url;//更新头像
                                  },
                                  complete: (res) => {
                                      console.log(res,"上传调用结束");
                                  }
                              });
                          },
                          complete: (res) => {
                              console.log(res,"裁剪调用结束");
                          }
                        })

猜你喜欢

转载自blog.csdn.net/sxy323/article/details/128968592
今日推荐