小程序调用相册与拍照
微信小程序提供了许多方便api给开发者使用,比如说wx. showActionSheet()调用菜单栏,wx.chooseImage()从本地相册选择图片或使用相机拍照。我们可以利用这些模拟用户设置头像,就是从本地调用图片设置在页面上并缓存到storage,刷新页面时图片不刷掉。
1、点击头像时弹出底部菜单栏
2、由于我是直接使用电脑测试,所以点击拍照或者相册都是弹出本地图片对话框,如果手机测试的是可以调用摄像头拍照的。
3、我们选择图片并确认后,在storage上会多出我们选择的图片数据。这时我们的图片就成功缓存到了storage上了
废话不多说了,直接上代码(看注释)
index.wxml
<view class='header'>
<view class='avatar'>
<image bindtap='buttonclick' src="{{tempFilePaths}}"/>
</view>
<view class='login-info'>
<view class='login'>登录/注册</view>
</view>
<view class='arrow'>
<image src="/assets/images/arrow-right.png"/>
</view>
</view>
index.wxss
.header {
position: relative;
display: flex;
background: #3399FF;
height: 170rpx;
padding: 12rpx 30rpx;
color: #fff;
}
.avatar image {
width: 140rpx;
height: 140rpx;
border-radius: 70rpx;
background: #f2f2f2;
vertical-align: middle;
}
.login-info {
vertical-align: middle;
margin-left: 30rpx;
}
.login-info .login {
font-size: 36rpx;
margin-top: 38rpx;
}
.arrow {
position: absolute;
right: 30rpx;
margin-top: 30rpx;
}
.arrow image {
width: 60rpx;
height: 60rpx;
}
index.js
Page({
data: {
tempFilePaths:'',
sourceType: ['camera', 'album']
},
onLoad: function () {
this.setHeader();//页面数据刚加载时调用setHeader();
},
//头像点击处理事件,使用wx.showActionSheet()调用菜单栏
buttonclick: function () {
const that = this
wx.showActionSheet({
itemList: ['拍照', '相册'],
itemColor: '',
//成功时回调
success: function (res) {
if (!res.cancel) {
/*
res.tapIndex返回用户点击的按钮序号,从上到下的顺序,从0开始
比如用户点击本例中的拍照就返回0,相册就返回1
我们res.tapIndex的值传给chooseImage()
*/
that.chooseImage(res.tapIndex)
}
},
//失败时回调
fail: function (res) {
console.log('调用失败')
},
complete: function (res) { },
})
},
/*
判断storage是否缓存图片,如果是就将图片从storage取出并赋值给tempFilePaths
否则就使用默认的图片
*/
setHeader(){
const tempFilePaths = wx.getStorageSync('tempFilePaths');
if (tempFilePaths) {
this.setData({
tempFilePaths: tempFilePaths
})
} else {
this.setData({
tempFilePaths: '/assets/images/header.png'
})
}
},
chooseImage(tapIndex) {
const checkeddata = true
const that = this
wx.chooseImage({
//count表示一次可以选择多少照片
count: 1,
//sizeType所选的图片的尺寸,original原图,compressed压缩图
sizeType: ['original', 'compressed'],
//如果sourceType为camera则调用摄像头,为album时调用相册
sourceType: [that.data.sourceType[tapIndex]],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
//将选择到的图片缓存到本地storage中
wx.setStorageSync('tempFilePaths', tempFilePaths)
/*
由于在我们选择图片后图片只是保存到storage中,所以我们需要调用一次 setHeader()方法来使页面上的头像更新
*/
that.setHeader();
wx.showToast({
title: '设置成功',
icon: 'success',
duration: 2000
})
}
})
},
})
文章为本人原创,欢迎大家转载,但是注意标明文章出处或链接