最近开发微信小程序,有一个小需求,用户上传图片,作为用户的头像。
开发用的taro框架,本以为分分钟搞定,chooseImage后把路径在前端显示并上传后台就OK了
Taro.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
}).then((res) => {
const tempFilePaths = res.tempFilePaths
// this.setState({ avatarShow: true, avatarSrc: tempFilePaths })
// uploadUserAvatar(res.tempFilePath,uid)
})
然后后端说图片太大了,能不能压缩后上传,产品说能不能只居中显示图片,这样压扁的头像看起来很难受,你不能要求用户上传正方形图片,你自己处理一下。所以下面是解决方案代码:
const ctx = Taro.createCanvasContext('canvas')
const screenWidth = Taro.getSystemInfoSync().screenWidth;
const scale = screenWidth / 375; // 注意不同手机的宽高比例不一样
Taro.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
}).then((res)=>{
const tempFilePaths = res.tempFi