程序员微信头像_处理微信小程序上传头像裁剪功能。

本文介绍如何处理微信小程序的头像上传裁剪功能。使用WeCropper组件,设置裁剪参数,如宽度、高度、缩放比例等,并实现触摸事件处理。裁剪后通过调用`getCropperImage`方法获取裁剪图片,再上传到服务器。最后展示上传成功后的处理逻辑。
摘要由CSDN通过智能技术生成

import WeCropper from '../../we-cropper/we-cropper.js'

const device = wx.getSystemInfoSync()

const width = device.windowWidth

const height = device.windowHeight - 50

Page({

data: {

cropperOpt: {

id: 'cropper',

width,

height,

scale: 2.5,

zoom: 8,

cut: {

x: (width - 300) / 2,

y: (height - 300) / 2,

width: 300,

height: 300

}

}

},

touchStart(e) {

this.wecropper.touchStart(e)

},

touchMove(e) {

this.wecropper.touchMove(e)

},

touchEnd(e) {

this.wecropper.touchEnd(e)

},

//这个是保存上传裁剪后的图片的方法

getCropperImage() {

var that = this

this.wecropper.getCropperImage((avatar) => {

if (avatar) {

uploadImage(avatar, function (res) { })

function uploadImage(filePath, cb) {   //个人封装的简单的上传单张图片上传的方法

wx.uploadFile({

url: “xxx/xx/xx”,

filePath: filePath,

name: 'file',

header: {

"Content-Type": "multipart/form-data"

},

formData: {

token: getApp().globalData.userData.token,

userName: "",

portrait: filePath

},

success: function (res) {

// 获取到裁剪后的图片

wx.switchTab({

url: `../A/A?avatar=${avatar}`   如果需要这图片地址就传过去 ,因为我上传后跳转页面后会自己获取服务器的是地址了。这里仅提供思路参考。

})

console.log('上传图片成功')

console.log(res);

wx.showToast({

title: '上传成功',

})

cb(res);

},

fail: function (res) {

console.log('上传图片失败!')

console.log(res)

wx.showToast({

title: '上传失败',

})

},

})

}

} else {

console.log('获取图片失败,请稍后重试')

}

})

},

uploadTap() {

const self = this

wx.chooseImage({

count: 1, // 默认9

sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

success(res) {

const src = res.tempFilePaths[0]

// 获取裁剪图片资源后,给data添加src属性及其值

self.wecropper.pushOrign(src)

}

})

},

onLoad(option) {

const { cropperOpt } = this.data

if (option.src) {

cropperOpt.src = option.src

new WeCropper(cropperOpt)

.on('ready', (ctx) => {

console.log(`wecropper is ready for work!`)

})

.on('beforeImageLoad', (ctx) => {

console.log(`before picture loaded, i can do something`)

console.log(`current canvas context:`, ctx)

wx.showToast({

title: '上传中',

icon: 'loading',

duration: 20000

})

})

.on('imageLoad', (ctx) => {

console.log(`picture loaded`)

console.log(`current canvas context:`, ctx)

wx.hideToast()

})

.on('beforeDraw', (ctx, instance) => {

console.log(`before canvas draw,i can do something`)

console.log(`current canvas context:`, ctx)

})

.updateCanvas()

}

}

})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值