微信小程序实现从相机或手机相册选择并设置头像的代码如下:

  1. 在 wxml 文件中添加一个按钮用于触发选择图片的操作:
<view class="avatar">
  <image src="{{avatarUrl}}" mode="aspectFill"></image>
  <button bindtap="chooseImage">选择图片</button>
</view>
  1. 在 wxss 文件中设置头像的样式:
.avatar {
  width: 200rpx;
  height: 200rpx;
  position: relative;
}

.avatar image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar button {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 10rpx;
  padding: 10rpx 20rpx;
}
  1. 在 js 文件中编写逻辑代码:
Page({
  data: {
    avatarUrl: ''
  },

  chooseImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePaths = res.tempFilePaths
        this.setData({
          avatarUrl: tempFilePaths[0]
        })
      }
    })
  }
})

以上代码实现了点击选择图片按钮后,弹出选择图片的操作面板,可以从相机或手机相册选择图片,并将选择的图片设置为头像

微信小程序实现从相机或手机相册选择并设置头像给出具体的实现代码

原文地址: http://www.cveoy.top/t/topic/iIvD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录