uniapp开发微信小程序,实现个人头像裁剪并上传

背景

在开发微信小程序时,个人头像直接选择本地文件上传,由于图片尺寸与头像展示尺寸不匹配,导致头像会被压缩拉伸,显示失真。在uniapp插件市场搜索插件发现现有插件不太好用。

方法

方法很简单,调用了微信原生的裁剪图片接口方法wx.cropImage(),代码示例如下。

<template>
		<view class="avater">
			<image class="avater-img" :src="headAddress" @click="getImageAndUpload()"></image>
			<p>点击头像修改</p>
		</view>
</template>

<script>
	export default {
		data() {
			return {
				headAddress: '' 
			}
		},
		methods: {
			async getImageAndUpload() {
				try {
					const chooseImageRes = await uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera']
					});

					const tempFilePaths = chooseImageRes.tempFilePaths;
					if (tempFilePaths.length === 0) {
						throw new Error('没有选择图片');
					}

					const imgPath = tempFilePaths[0];

					const cropImageRes = await wx.cropImage({
						src: imgPath, // 图片路径
						cropScale: '1:1' // 裁剪比例   微信官方提供了多种裁剪比例以供选择
					});

					const cropImgPath = cropImageRes.tempFilePath;

					const token = this.$store.getters.getToken(); // 一般的上传接口都需要token校验。我这里应用了Vuex
					const uploadRes = await wx.uploadFile({
						url: config.baseURL + '/file/upload', // 你的服务器接口地址
						filePath: cropImgPath,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data',
							'Authorization': `Bearer ${token}`
						}
					});

					const data = JSON.parse(uploadRes.data);
					const {
						code,
						data: responseData,
						message
					} = data;
					
					if(code==200){
						// 头像上传成功
						console.log('头像上传成功')
					}
				} catch (error) {
					// 错误处理
					console.error(error);
					throw error;
				}
			}
		}
	}
</script>

<style lang="scss">
	
</style>

微信官方还提供了图片压缩方法,有需要的小伙伴可以去查查看官方文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值