1. 程式人生 > 程式設計 >微信小程式使用前置攝像頭拍照

微信小程式使用前置攝像頭拍照

本文例項為大家分享了微信小程式使用前置攝像頭拍照的具體程式碼,供大家參考,具體內容如下

微信小程式使用前置攝像頭拍照

1、拍照頁面:

<template>
 <view title="拍照">
 <camera v-if="openCamera" device-position="front" frame-size="large" class="zipai" @error="error"> </camera>
 <cover-image src="/static/image/renzheng_zz.png" class="zhezhao"></cover-image>
 <cover-view class="wenzi fint34">請將正面人臉放在識別框中,進行拍攝</cover-view>
 <cover-image class="paizhao" src="/static/image/renzheng_pz.png" @click="takePhoto"></cover-image>
 </view>
</template>
 
<script>
 export default {
 data() {
  return {
  openCamera:true
  }
 },methods: {
  takePhoto() {
  const ctx = wx.createCameraContext()
  ctx.takePhoto({
   quality: 'high',success: (res) => {
   let tempFilePath = res.tempImagePath
   uni.navigateTo({
    url:'/pages/renzhengwxtu/renzhengwxtu?src='+tempFilePath
   })
   }
  })
  },//使用者拒絕授權攝像頭
  error(e) {
  this.openCamera=false
  wx.showModal({
   title: '警告',content: '若不授權使用攝像頭,將無法使用拍照功能!',cancelText: '不授權',cancelColor: '#1ba9ba',confirmText: '授權',confirmColor: '#1ba9ba',success:(res)=> {
   if (res.confirm) {//允許開啟授權頁面
    //調起客戶端小程式設定介面,返回使用者設定的操作結果
    wx.openSetting({
    success:(res)=> {
     res.authSetting = {
     "scope.camera": true
     }
     this.openCamera=true
    },})
   } else if (res.cancel) {//拒絕開啟授權頁面
    wx.navigateBack({delta:1})
   }
   }
  })
  },}
 }
</script>

2、預覽圖片頁面:

<template>
 <view title="預覽圖片">
 <image mode="widthFix" :src="src" class="renlian"></image>
 <view class="btns">
  <text @click="takePhoto">重拍</text>
  <text @click="usePhoto">使用照片</text>
 </view>
 </view>
</template>
 
<script>
 export default {
 data() {
  return {
  src: '',timeId:null,}
 },onLoad(option) {
  this.src=option.src
 },onHide() {
  clearTimeout(this.timeId);
  this.timeId=null;
 },methods: {
  takePhoto() {
  uni.navigateBack({delta: 1});
  },usePhoto() {
  this.$request.uploadFileMinipro(this.src,this.retoRenzheng);
  },retoRenzheng(){
  this.timeId=setTimeout(()=>{
   var pages = getCurrentPages();
   var prevPage = pages[pages.length - 3]; //上一個頁面
   prevPage.fromTu= true;
   uni.navigateBack({delta: 2});
  },200);
  },}
 }
</script>

3、上傳圖片方法:

// uploadFileMinipro
function uploadFileMinipro(tempFilePath,callback){
 // 1.2 上傳頭像
 let uin =common.getGlobalUserInfo().id;
 let reurl=common.ip;
 uni.uploadFile({
 url: reurl,filePath: tempFilePath,name: "file",formData:{uin:uin},success:(res)=>{
  console.log("res=",res);
  // 注意,這裡獲得是一個string,需要轉換一下
  let resData = JSON.parse(res.data);
  if (resData.status == 1) {//<=0:人工返回的錯誤資訊
  setErrorMessage("上傳成功");
  if (typeof callback === "function"){
   callback();//重新整理當前頁面
  }
  
  } else if (resData.status < 1) {
   setErrorMessage(resData.msg)
  } else {
   setErrorMessage()
  }
 },fail:(res)=>{
  console.log("上傳失敗");
 },});
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。