1,要想調用攝像頭首先要打開攝像頭驅動,如果用戶允許則可以使用。
2,定義WebCamTexture的變量用於捕獲單張照片。
3,連續捕獲須啟用線程。
實現代碼:
using UnityEngine; using System.Collections; using System.IO; using System.Runtime.Serialization; using System.Runtime .Serialization.Formatters.Binary; using System.Threading; public class takePhoto : MonoBehaviour { public string deviceName; //接收返回的圖片數據 WebCamTexture tex; void OnGUI() { if (GUI.Button(new Rect(10, 20, 100, 40), "開啟攝像頭")) { // 調用攝像頭 StartCoroutine(start()); } if(GUI.Button(new Rect(10,70,100,40),"捕獲照片")) { //捕獲照片 tex.Pause(); StartCoroutine(getTexture()); } if(GUI.Button(new Rect(10,120,100,40),"再次捕獲")) { //重新開始 tex.Play(); } if(GUI.Button(new Rect(120,20,80,40),"錄像")) { //錄像 StartCoroutine(SeriousPhotoes()); } if(GUI.Button(new Rect(10,170,100,40),"停止")) { //停止捕獲鏡頭 tex.Stop (); StopAllCoroutines(); } if(tex!=null) { // 捕獲截圖大小 —距X左屏距離 | 距Y上屏距離 GUI.DrawTexture(new Rect(Screen.width/2-150,Screen.height/2-190,280,200),tex); } } /// <summary> /// 捕獲窗口位置 /// </summary> public IEnumerator start() { yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); if (Application.HasUserAuthorization(UserAuthorization.WebCam)) { WebCamDevice[] devices = WebCamTexture.devices; deviceName= devices[0].name; tex=new WebCamTexture(deviceName,300,300,12); tex.Play(); } } /// <summary> /// 獲取截圖 /// </summary> /// <returns>The texture.</returns> public IEnumerator getTexture() { yield return new WaitForEndOfFrame(); Texture2D t=new Texture2D(400,300); t.ReadPixels( new Rect(Screen.width/2-200,Screen.height/2-50,360,300),0,0,false); //距X左的距離 距Y屏上的距離 // t.ReadPixels(new Rect(220, 180, 200, 180), 0, 0, false); t.Apply(); byte[] byt=t.EncodeToPNG(); File.WriteAllBytes(Application.dataPath+"/Photoes/"+Time.time+".jpg",byt); tex.Play(); } /// <summary> /// 連續捕獲照片 /// </summary> /// <returns>The photoes.</returns> public IEnumerator SeriousPhotoes() { while (true) { yield return new WaitForEndOfFrame(); Texture2D t = new Texture2D(400, 300, TextureFormat.RGB24, true); t.ReadPixels(new Rect(Screen.width/2-180,Screen.height/2-50,360,300), 0, 0, false); t.Apply(); print(t); byte[] byt = t.EncodeToPNG(); File.WriteAllBytes(Application.dataPath + "/MulPhotoes/" + Time.time.ToString().Split('.')[0] + "_" + Time.time.ToString().Split('.')[1] + ".png", byt); Thread.Sleep(300); } } }
將此腳本綁定到MainCamer上,運行效果如下:
其余也沒什么了,哦,對了,記得建個空文件夾用於儲存捕獲到的照片。
希望我們能夠共同學習!