背景:在由用户上传图片生成自定义海报的时候,会存在图片尺寸太大造成拉伸的情况。所以在选择图片之后,对图片进行裁剪再进行上传。
插件地址:https://github.com/1977474741/image-cropper,详细功能请查看文档。
- 下载插件之后,把相关文件放到uniapp项目的wxcomponents目录里面,并在page.json配置好裁剪页的组件引入。例:
{
"path" : "posterActivity/cropper/index",
"style" : {
"navigationBarTitleText" : "",
"enablePullDownRefresh" : false,
"usingComponents": {
"image-cropper": "/wxcomponents/image-cropper/image-cropper"
}
}
}
- 上传图片页,点击选择图片之后把图片临时地址带到裁剪页。
handleUpload() {
uni.chooseImage({
count: 1,
crop: {
width: 412
},
success:(val)=> {
uni.navigateTo({
url: `/pagesActivity/posterActivity/cropper/index?url=${val.tempFilePaths[0]}`
})
}
})
},
- 裁剪页,配置插件相关参数,裁剪成功之后把图片地址存到vuex。
<template>
<view class="cropper_popup">
<image-cropper ref="image-cropper" :limit_move="true" :disable_rotate="true" :disable_ratio="true" width="190" height="330" max_width="228" max_height="396" :quality="1" :imgSrc="imgSrc"></image-cropper>
<view class="btns">
<view @click="handleCancel">取消</view>
<view @click="handleSure">确认</view>
</view>
</view>
</template>
<script>
export default{
data() {
return {
imgSrc: '',
}
},
onLoad(options) {
this.imgSrc = options.url
},
mounted(){},
methods:{
handleCancel() {
uni.navigateBack({ delta: 1 })
},
handleSure() {
// getImg获取裁剪后的图片信息
this.$refs['image-cropper'].getImg(res => {
this.$store.commit('SET_POSTERURL', res.url)
uni.navigateBack({ delta: 1 })
})
}
},
}
</script>
<style lang='scss' scoped>
.cropper_popup {
width: 100%;
height: 100vh;
position: relative;
.btns {
width: 100%;
display: flex;
justify-content: space-around;
position: absolute;
bottom: 80rpx;
z-index: 999999;
color: #fff;
}
}
</style>
- 回到上传图片页,从vuex获取裁剪后的临时图片地址,并进行上传即可。
onShow() {
let posterUrl = this.$store.state.posterUrl
if(posterUrl) {
上传操作...
}
},
onUnload() {
this.$store.commit('SET_POSTERURL', '')
},
网友评论