小程序基于we-cropper实现头像上传裁剪保存

第一步从下载资源中下载we-cropper.zip(免费)或者从下面原链接下载
we-cropper

第二步
压缩包后,将里面的
common.wxss,
we-cropper.min.js,
we-cropper.wxml

放在自己的小程序项目中,比如utils中然后进行下面的操作

页面1,添加图片

wxml
<view class="info-photo" style="background-image:url('{{businessCards.headImage || defultImg}}')">
  <view class="replace-photo" bindtap="switchPhoto">更换</view>
</view>

wxss
.info-photo{
  width: 560rpx;
  height: 560rpx;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  margin: 0 auto 21rpx;
  position: relative;
}
.info-photo .replace-photo{
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  color: #ffffff;
  position: absolute;
  bottom: 0;
  background:rgba(0,0,0,.4);
}
//调用api选择图片后跳转到裁剪页面进行编辑
switchPhoto: function(e) {
   let self = this;
   //调用微信api
   wx.chooseImage({
     count: 1,//选择数量
     sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
     sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
     success: function(res) {
       //图片的临时路径
       const src = res.tempFilePaths[0];
       wx.navigateTo({
         url: `/pages2/user-photo-edit/user-photo-edit?src=${src}`
       })
     },
   })
 }

页面2(user-photo-edit),获取到传过来的图片,进行编辑保存

wxml:
<import src='../../utils/we-cropper/we-cropper.wxml'/>
<view class="cropper-wrapper">
    <template is="we-cropper" data="{{...cropperOpt}}"/>
    <view class="cropper-buttons">
        <view class="upload" bindtap="uploadTap">重新上传</view>
        <view class="getCropperImage" bindtap="getCropperImage">完成</view>
    </view>
</view>

wxss:
@import "../../utils/we-cropper/common.wxss";
page {
  height: 100%
}
.cropper {
  position: absolute;
  top: 0;
  left: 0;
}
.cropper-buttons {
  color: #ffffff;
}
js:
import WeCropper from '../../utils/we-cropper/we-cropper.min.js';
const device = wx.getSystemInfoSync(), // 获取设备信息
      width = device.windowWidth,
      height = device.windowHeight + 10;

Page({
  data: {
    cropperOpt: {
      id: 'cropper', // 用于手势操作的canvas组件标识符
      targetId: 'targetCropper', // 用于用于生成截图的canvas组件标识符
      pixelRatio: device.pixelRatio, // 传入设备像素比
      width, // 画布宽度
      height, // 画布高度
      src: '',
      scale: 2.5, // 最大缩放倍数
      zoom: 8, // 缩放系数
      cut: {
        x: (width - 320) / 2, // 裁剪框x轴起点
        y: (width - 320) / 2, // 裁剪框y轴起点
        width: 320, // 裁剪框宽度
        height: 320 // 裁剪框高度
      }
    }
  },
  // 页面onLoad函数中实例化WeCropper
  onLoad: function (options) {
    this.setData({id: options.id})
    const {
      cropperOpt
    } = this.data;
    cropperOpt.src = options.src;
    if (cropperOpt.src) {
      this.cropper = new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
          console.log(`wecropper!`)
        })
        .on('beforeImageLoad', (ctx) => {
          wx.showToast({
            title: '上传中',
            icon: 'loading',
            duration: 3000
          })
        })
        .on('imageLoad', (ctx) => {
          wx.hideToast()
        })
    }
  },
  // 插件通过touchStart、touchMove、touchEnd方法来接收事件对象。
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
  // 自定义裁剪页面的布局中,可以重新选择图片
  uploadTap() {
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        self.cropper.pushOrign(src)
      }
    })
  },

  // 生成图片
  getCropperImage(){
    wx.showLoading({
      title: '保存中',
    })
    let self = this;
    self.cropper.getCropperImage(tempFilePath => {
      // tempFilePath 为裁剪后的图片临时路径
      if (tempFilePath) {
        console.log("裁剪地址2",tempFilePath)
        // 拿到裁剪后的图片路径的操作
        wx.uploadFile({
          url: `后台api接口`,
          filePath: tempFilePath,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success: function(res) {
            var uploadData = JSON.parse(res.data);
            //上传图片到服务器后的地址
            var imgPath = uploadData.data[0].file;
            console.log("上传后路径",imgPath)
            //根据业务逻辑进行后续操作
          }
        })
      } else {
        console.log('获取图片地址失败,请稍后重试')
      }
    })
  }  
})

有些方法是参照的其他博主,仅供参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用vant-uploader和vue-cropper来实现裁剪图片并上传,你可以按照以下步骤进行操作: 1. 首先,安装vant和vue-cropper插件。你可以使用npm或yarn来安装它们。 2. 在你的Vue组件中,引入vant-uploader和vue-cropper组件。 3. 在模板中,使用vant-uploader组件来实现图片上传功能。设置上传的action属性为你的上传接口地址,并设置on-success事件来处理上传成功后的逻辑。 4. 在on-success事件中,获取到上传成功后的图片地址,并将其传递给vue-cropper组件。 5. 在vue-cropper组件中,设置裁剪框的样式和裁剪比例等属性。使用v-model指令来绑定裁剪后的图片数据。 6. 在提交按钮的点击事件中,将裁剪后的图片数据上传到服务器。 下面是一个简单的示例代码: ```vue <template> <div> <van-uploader action="/upload" :on-success="handleUploadSuccess" ></van-uploader> <vue-cropper v-if="showCropper" :src="cropperSrc" :output-size="{ width: 200, height: 200 }" :output-type="'jpeg'" :fixed-box="true" :fixed-number="\[1, 1\]" v-model="croppedImage" ></vue-cropper> <button @click="handleSubmit">提交</button> </div> </template> <script> import { VanUploader } from 'vant'; import VueCropper from 'vue-cropper'; export default { components: { VanUploader, VueCropper, }, data() { return { showCropper: false, cropperSrc: '', croppedImage: '', }; }, methods: { handleUploadSuccess(response) { // 获取上传成功后的图片地址 const imageUrl = response.data.imageUrl; // 显示裁剪组件 this.showCropper = true; // 设置裁剪组件的图片地址 this.cropperSrc = imageUrl; }, handleSubmit() { // 提交裁剪后的图片数据到服务器 // this.croppedImage 包含裁剪后的图片数据 }, }, }; </script> ``` 请注意,以上代码只是一个简单的示例,你需要根据你的实际需求进行适当的修改和调整。同时,你还需要在后端实现相应的上传裁剪功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值