最近的一个小程序项目中遇到了上传图片过长需要小程序裁剪的问题
这里需要用到小程序裁剪的库we-cropper 下载地址GitHub - we-plugin/we-cropper: 微信小程序图片裁剪工具
这里可以把步骤分为以下几个
1.下载we-cropper,解压后在dist中有这几个文件
可以把we-cropper.js文件放在小程序项目的utils中
2.在项目中新建一个page页面imgcorp.名字什么的随便你们自己改都行
imgcorp中的wxml要填入如下代码
<!-- 跳转裁剪的页面 -->
<template name="we-cropper">
<canvas class="cropper {{cutImage}}" disable-scroll="true" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd" style="width:{{width}}px;height:{{height}}px" canvas-id="{{id}}">
</canvas>
</template>
<view class="cropper-wrapper {{cutImage}}">
<template is="we-cropper" data="{{...cropperOpt}}"/>
</view>
<view class="operbtns">
<button class="button" type="primary" bindtap="getCropperImage">完成</button>
</view>
imgcorp中的js要填入如下代码
import WeCropper from '../../../utils/we-cropper'
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 100;
Page({
data: {
cropperOpt: {
id: 'cropper',
width,
height,
scale: 2.5,
zoom: 8,
cut: {
x: (width - 150) / 2,
y: (height - 150) / 2,
width: 150,
height: 150
}
}
},
onLoad: function (options) {
this.data.cropperOpt.src = options.img;
const { cropperOpt } = this.data
new WeCropper(cropperOpt)
.on('beforeImageLoad', (ctx) => {
wx.showToast({
title: '上传中',
icon: 'loading',
duration: 20000
})
})
.on('imageLoad', (ctx) => {
wx.hideToast()
})
.updateCanvas();
},
touchStart(e) {
this.wecropper.touchStart(e)
},
touchMove(e) {
this.wecropper.touchMove(e)
},
touchEnd(e) {
this.wecropper.touchEnd(e)
},
getCropperImage() {
var that = this;
that.wecropper.getCropperImage((src) => {
if (src) {
var pages = getCurrentPages();
var currPage = pages[pages.length - 1]; //当前页面
var prevPage = pages[pages.length - 2]; //上一个页面
prevPage.uploadImage(src);
wx.navigateBack();
}
})
},
})
3.图片裁剪上传要触发的函数
//跳转裁剪页
jumpTowecropper(){
var _this = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths[0];
wx.navigateTo({
url: '/pages/settlement/imgcorp/index?img='+tempFilePaths,
});
}
})
},
uploadImage(path){
var that = this;
wx.uploadFile({
url: that.data.baseUrl+'/api/img/uploadFile',
filePath: path,
name: 'image',
formData: {
'sessionId':that.data.token
},
success (res){
console.log(res);
// const data = res.date
let src=JSON.parse(res.data)
that.setData({
'value.shopImg':src.data
})
}
})
},
总结的步骤为一下几点
触发微信的api wx.chooseImage选择图片,
跳转裁剪页面并将图片的链接传过去,
之后执行裁剪操作并通过getCurrentPages()触发之前页面的上传函数执行上传操作