您的位置:首页 > 移动开发 > 微信开发

微信小程序实现获取用户高清头像

2020-06-01 21:02 162 查看

微信小程序实现获取用户高清头像

获取用户高清头像的需求:

获取用户头像的实现:

  • 第一种方法很简便:是在wxml中使用
    <open-data type="userAvatarUrl"></open-data>
    组件直接展示用户头像,注意只是展示,并不能获取到用户的头像数据(即图片链接),而且展示的头像是132×132(单位:px)大小的,如果需求中要求更大且清晰的头像,那这种方法是行不通的。
  • 第二种方法是通过js获取app.globalData中的userInfo.avatarUrl,然后再经过wxml的image组件展示出来,优点是同时获取到了用户的头像信息,缺点依旧是获取不到用户的高清头像。关键在于,用户头像的图片链接
    app.globalData.userInfo.avatarUrl
    是以’/132’结尾的,’/xxx’表示像素点的大小,而把’/132’改成’/0’即可获取400×400像素的高清用户头像,代码如下:

获取用户高清头像

效果示意图:

代码:

wxml

<view class="weui-tab__content">
<view class="container-body">
<image class="image" src="{{bgPic}}" ></image>
<button class='button' bindtap="getavatar" open-type="getUserInfo" bindgetuserinfo="getUserInfo" type="submit">获取头像</button>
</view>
</view>

js

const app = getApp();
Page({

/**
* 页面的初始数据
*/
data: {
imageUrl: null,
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function() {
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse) {
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
getUserInfo: function (e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
getavatar: function(){
var that=this;
wx.downloadFile({
url: this.data.userInfo.avatarUrl,
success: function(res){
console.log(res)
that.setData({
bgPic: headimgHD(app.globalData.userInfo.avatarUrl)
})
}
})
}
})
function headimgHD (imageUrl) {
imageUrl = imageUrl.split('/');        //把头像的路径切成数组
//把大小数值为 46 || 64 || 96 || 132 的转换为0
if (imageUrl[imageUrl.length - 1] && (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {
imageUrl[imageUrl.length - 1] = 0;
}
imageUrl = imageUrl.join('/');   //重新拼接为字符串
return imageUrl;
}

在Page()外建立子函数—headimgHD()来将获取到的头像进行修改后返回高清头像。此例子是通过点击按钮获取用户头像,所以在自定义函数getavatar()中调用headimgHD();如果想实现进入该页面自动获取高清头像,则需要在onload()函数里面完成调用。

wxss

.weui-tab__content{
width: 100%;
height: 100%;
text-align: center;
}
.container-body {
padding-top: 120rpx;
}
.image {
width: 500rpx;
height: 500rpx;
border: 12rpx solid white;
border-radius: 5%;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: