我们可以使用wx为我们提供的api直接打开图片
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'], //使用图片还是相机
success (res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
}
})
详情查看官方文档
如果不满意官方提供的拍照界面,我们也可以自己手动实现,不过略微麻烦,
上代码
wxml
使用camera 组件 定义属性
<camera class="camera" mode="normal" wx:if="{{isCamera}}" resolution="high" device-position="{{camPos}}" flash="{{light}}">
<cover-view class="btn-box">
<cover-view class="camera-btn" bindtap="changeLight">灯光</cover-view>
<cover-view class="camera-btn" bindtap="tackPhoto">拍照</cover-view>
<cover-view class="camera-btn" bindtap="changeCarmera">切换</cover-view>
</cover-view>
</camera>
data: {
isCamera:false, //相机是否打开
camPos:"back", //相机后置设想
light:"off", //闪光灯
photoPath:"", //拍照和打开图片的路径
},
loadLogo(){ //打开照相机函数;
wx.showActionSheet({
itemList: ["相机","相册"],
success:(res)=>{
if(res.tapIndex===0){
this.setData({
isCamera:true,
})
}else{
wx.chooseImage({
count: 1,
sourceType:"album",
sizeType:"original",
success:(res)=>{
this.setData({
photoPath:res.tempFilePaths
})
}
})
}
}
})
},
//修改前置还是后置
changeCarmera(){
this.setData({
camPos:this.data.camPos=='front'?"back":"front"
})
},
//修改闪光灯
changeLight(){
this.setData({
light:this.data.light=="off"?"torch":"off",
})
},
//拍摄图片
tackPhoto(){
let carmera = wx.createCameraContext();
carmera.takePhoto({
quality:'high',
success:(res)=>{
this.setData({
photoPath:res.tempImagePath,
isCamera:false,
})
}
})
},
//长按图片进行保存
longImage(){
wx.vibrateLong({
success: (res) => {
wx.saveImageToPhotosAlbum({
filePath:this.data.photoPath,
success:(res)=>{
this.setData({
photoPath:res.savedFilePath
})
}
})
},
})
},