微信小程序相機組件wx.createCameraContext()的使用模擬微信拍照-后端為nodejs

在本文 微信小程序相機組件wx.createCameraContext()的使用模擬微信拍照之前需要看看

微信小程序-獲取用戶session_key,openid,unionid - 后端為nodejs

代碼封裝是在上文添加的。

本文知識點:

1撵溃、微信小程序相機組件wx.createCameraContext()使用

2挑势、微信小程序拍照逻翁,錄視頻實現(xiàn)

3、微信小程序上傳文件接口wx.uploadFile()的使用

4、微信小程序wx:if的使用

5掀序、nodejs上傳文件multer模塊的使用

6、camera組件使用

效果

image

在筆記本上惭婿,沒有前后置翻轉(zhuǎn)效果不恭,真機上是有的;

在微信開發(fā)工具里camera組件是透明的财饥,真機上沒問題;

在微信開發(fā)工具里上傳的視頻格式為webm换吧,真機上為mp4。

小程序代碼

1钥星、在utils下的wechat.js文件里添加代碼

  /** 
  * 將本地資源上傳到開發(fā)者服務(wù)器沾瓦,客戶端發(fā)起一個 HTTPS POST 請求 
  * @param {string} url 開發(fā)者服務(wù)器 url 
  * @param {string} filePath 要上傳文件資源的路徑 
  * @param {string} name  
  * @param {object} formData HTTP 請求中其他額外的 form data 
  */  
  static uploadFile(url, filePath, name, formData = { openid: "test" }) {  
  return new Promise((resolve, reject) => {  
  let opts = { url, filePath, name, formData, header: { 'Content-Type': "multipart/form-data" }, success: resolve, fail: reject };  
  wx.uploadFile(opts);  
  });  
  }  

js

  //index.js  
  //獲取應(yīng)用實例  
  let app = getApp();  
  let wechat = require("../../utils/wechat");  
  Page({  
  data: {  
  device: true,  
  tempImagePath: "", // 拍照的臨時圖片地址  
  tempThumbPath: "", // 錄制視頻的臨時縮略圖地址  
  tempVideoPath: "", // 錄制視頻的臨時視頻地址  
  camera: false,  
  ctx: {},  
  type: "takePhoto",  
  startRecord: false,  
  time: 0,  
  timeLoop: "",  
  },  
  onLoad() {  
  this.setData({  
  ctx: wx.createCameraContext()  
  })  
  },  
  // 切換相機前后置攝像頭  
  devicePosition() {  
  this.setData({  
  device: !this.data.device,  
  })  
  console.log("當(dāng)前相機攝像頭為:", this.data.device ? "后置" : "前置");  
  },  
  camera() {  
  let { ctx, type, startRecord } = this.data;  
  // 拍照  
  if (type == "takePhoto") {  
  console.log("拍照");  
  ctx.takePhoto({  
  quality: "normal",  
  success: (res) => {  
  // console.log(res);  
  this.setData({  
  tempImagePath: res.tempImagePath,  
  camera: false,  
  });  
  wechat.uploadFile("https://xx.xxxxxx.cn/api/upload", res.tempImagePath, "upload")  
  .then(d => {  
  console.log(d);  
  })  
  .catch(e => {  
  console.log(e);  
  })  
  },  
  fail: (e) => {  
  console.log(e);  
  }  
  })  
  }  
  // 錄視頻  
  else if (type == "startRecord") {  
  if (!startRecord) {  
  console.log("開始錄視頻");  
  this.setData({  
  startRecord: true  
  });  
  // 30秒倒計時  
  let t1 = 0;  
  let timeLoop = setInterval(() => {  
  t1++;  
  this.setData({  
  time: t1,  
  })  
  // 最長錄制30秒  
  if (t1 == 30) {  
  clearInterval(timeLoop);  
  this.stopRecord(ctx);  
  }  
  }, 1000);  
  this.setData({  
  timeLoop  
  })  
  // 開始錄制  
  ctx.startRecord({  
  success: (res) => {  
  console.log(res);  
  },  
  fail: (e) => {  
  console.log(e);  
  }  
  })  
  }  
  else {  
  this.stopRecord(ctx);  
  }  
  }  
  },  
  // 停止錄制  
  stopRecord(ctx) {  
  console.log("停止錄視頻");  
  clearInterval(this.data.timeLoop);  
  ctx.stopRecord({  
  success: (res) => {  
  this.setData({  
  tempThumbPath: res.tempThumbPath,  
  tempVideoPath: res.tempVideoPath,  
  camera: false,  
  startRecord: false,  
  time: 0  
  });  
  wechat.uploadFile("https://xx.xxxxxx.cn/api/upload", res.tempThumbPath, "tempThumbPath")  
  .then(d => {  
  console.log(d);  
  return wechat.uploadFile("https://xx.xxxxxx.cn/api/upload", res.tempVideoPath, "tempVideoPath")  
  })  
  .then(d => {  
  console.log(d);  
  })  
  .catch(e => {  
  console.log(e);  
  })  
  },  
  fail: (e) => {  
  console.log(e);  
  }  
  })  
  },  
  // 打開模擬的相機界面  
  open(e) {  
  let { type } = e.target.dataset;  
  console.log("開啟相機準備", type == "takePhoto" ? "拍照" : "錄視頻");  
  this.setData({  
  camera: true,  
  type  
  })  
  },  
  // 關(guān)閉模擬的相機界面  
  close() {  
  console.log("關(guān)閉相機");  
  this.setData({  
  camera: false  
  })  
  }  
  })  

html

  <view class="view">  
  <view class="window">  
  <image class="cover-9" src="{{tempImagePath}}" bindtap="img" wx:if="{{type=='takePhoto'}}"></image>  
  <video class="cover-9" src="{{tempVideoPath}}" poster="{{tempThumbPath}}" wx:if="{{type=='startRecord'}}"></video>  
  <view class="window-2">  
  <button bindtap="open" type="primary" data-type="takePhoto">拍照</button>  
  <button bindtap="open" type="primary" data-type="startRecord">錄制</button>  
  </view>  
  </view>  

  <camera class="camera" device-position="{{device?'back':'front'}}" wx:if="{{camera}}" flash="off">  
  <cover-view class="cover-1" bindtap="camera">  
  <cover-view class="cover-2">  
  <cover-view class="cover-5" wx:if="{{type=='startRecord'&&startRecord}}">{{time}}S</cover-view>  
  </cover-view>  
  </cover-view>  
  <cover-image class="cover-3" src="/images/xx2.png" style="width:60rpx;height:60rpx;" bindtap="close"></cover-image>  
  <cover-image class="cover-4" src="/images/zh.png" style="width:80rpx;height:60rpx;" bindtap="devicePosition"></cover-image>  
  </camera>  
  </view>  

css

  page{  
  height: 100%;  
  }  
  .view{  
  width: 100%;  
  height: 100%;  
  }  
  .window{  
  width: 100%;  
  height: 100%;  
  position: absolute;  
  }  
  .window-2{  
  display: flex;  
  flex-direction: row;  
  }  
  .camera{  
  width: 100%;  
  height: 100%;  
  }  

  .cover-1{  
  width: 150rpx;  
  height: 150rpx;  
  border-radius: 150rpx;  
  background-color: #dedcdc;  
  display: flex;  
  flex-direction: row;  
  align-items: center;  
  justify-content: center;  
  position: absolute;  
  bottom: 60rpx;  
  left: 300rpx;  
  }  
  .cover-3{  
  position: absolute;  
  bottom: 105rpx;  
  left:135rpx;  
  }  
  .cover-9{  
  width: 728rpx;  
  height: 80%;  
  margin: 0 10rpx;  
  border:2rpx solid;  
  border-radius:5px;    
  }  
  button{  
  margin: 0 10rpx;  
  width: 100%;  
  }  
  .cover-4{  
  position: absolute;  
  top: 60rpx;  
  right:40rpx;  
  }  
  .cover-2{  
  width: 110rpx;  
  height: 110rpx;  
  border-radius: 110rpx;  
  background-color: #ffffff;  
  display: flex;  
  flex-direction: row;  
  align-items: center;  
  justify-content: center;  
  color:#da2121;  
  font-size: 32rpx;  
  }  

nodejs代碼

文件上傳使用multer模塊,引入multer模塊后配置好并添加一個上傳處理的路由打颤,創(chuàng)建上傳的目錄暴拄,

本文是uploads/tmp目錄

  const multer = require('multer');  
  let path = require("path");  
  //上傳文件配置  
  const storage = multer.diskStorage({  
  //文件存儲位置  
  destination: (req, file, cb) => {  
  cb(null, path.resolve(__dirname, '../uploads/tmp/'));  
  },  
  //文件名  
  filename: (req, file, cb) => {  
  cb(null, `${Date.now()}_${Math.ceil(Math.random() * 1000)}_multer.${file.originalname.split('.').pop()}`);  
  }  
  });  
  const uploadCfg = {  
  storage: storage,  
  limits: {  
  //上傳文件的大小限制,單位bytes  
  fileSize: 1024 * 1024 * 20  
  }  
  };  
  router.post("/api/upload", async (req, res) => {  
  let upload = multer(uploadCfg).any();  
  upload(req, res, async (err) => {  
  if (err) {  
  res.json({ path: `//uploads/tmp/${uploadFile.filename}` });  
  console.log(err);  
  return;  
  };  
  console.log(req.files);  
  let uploadFile = req.files[0];  
  res.json({ path: `//uploads/tmp/${uploadFile.filename}` });  
  });  
  })  

后端打印

image

上傳的文件夾

image

素材

向下箭頭:https://img-blog.csdn.net/20180226111545178

翻轉(zhuǎn)圖片:https://img-blog.csdn.net/20180226111559273

參考地址:

https://mp.weixin.qq.com/debug/wxadoc/dev/component/camera.html

https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-camera.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市编饺,隨后出現(xiàn)的幾起案子乖篷,更是在濱河造成了極大的恐慌,老刑警劉巖透且,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件撕蔼,死亡現(xiàn)場離奇詭異,居然都是意外死亡秽誊,警方通過查閱死者的電腦和手機鲸沮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锅论,“玉大人讼溺,你說我怎么就攤上這事∽钜祝” “怎么了怒坯?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長藻懒。 經(jīng)常有香客問我剔猿,道長,這世上最難降的妖魔是什么嬉荆? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任归敬,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘汪茧。我一直安慰自己椅亚,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布舱污。 她就那樣靜靜地躺著什往,像睡著了一般。 火紅的嫁衣襯著肌膚如雪慌闭。 梳的紋絲不亂的頭發(fā)上别威,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天,我揣著相機與錄音驴剔,去河邊找鬼省古。 笑死,一個胖子當(dāng)著我的面吹牛丧失,可吹牛的內(nèi)容都是我干的豺妓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼布讹,長吁一口氣:“原來是場噩夢啊……” “哼琳拭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起描验,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤白嘁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后膘流,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體絮缅,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年呼股,在試婚紗的時候發(fā)現(xiàn)自己被綠了耕魄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡彭谁,死狀恐怖吸奴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情缠局,我是刑警寧澤则奥,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站甩鳄,受9級特大地震影響逞度,放射性物質(zhì)發(fā)生泄漏额划。R本人自食惡果不足惜妙啃,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧揖赴,春花似錦馆匿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至铭拧,卻和暖如春赃蛛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背搀菩。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工呕臂, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人肪跋。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓歧蒋,卻偏偏與公主長得像,于是被迫代替她去往敵國和親州既。 傳聞我的和親對象是個殘疾皇子谜洽,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載鏈接 注:本文轉(zhuǎn)載知乎上的回答 作者:初雪 鏈接:https://www.zhihu.com/question...
    pengshuangta閱讀 28,540評論 9 295
  • 給提問的開發(fā)者的建議:提問之前先查詢 文檔、通過社區(qū)右上角搜索搜索已經(jīng)存在的問題吴叶。 寫一個簡明扼要的標題阐虚,并且...
    極樂叔閱讀 13,437評論 0 3
  • 1:微信小程序官方工具: https://mp.weixin.qq.com/debug/w ... tml?t=1...
    黃海佳閱讀 9,421評論 1 56
  • 寶寶都有“內(nèi)熱”的狀況。 比如有的寶寶眼睛腫蚌卤,眼屎多敌呈,有的寶寶反復(fù)便秘,大便干結(jié)造寝,有的動不動口腔潰瘍磕洪、咽喉部分出狀...
    聽雨心依閱讀 454評論 0 0
  • 魔云山之巔一直是我最喜歡的地方疫向,每次我睡不著的時候就來這里看看魔月额港。魔月是紫色的,這正是我們魔眼的顏色肚豺,實在很美签赃。...
    南樓2504閱讀 468評論 0 0