unity呼叫攝像頭拍照
阿新 • • 發佈:2018-11-07
我的unity呼叫攝像頭拍照
因為做的是pc端的,所以不知道手機上效果是怎樣的,據說程式碼是完全相同的。
廢話不說,上程式碼,
開啟攝像頭程式碼:
儲存圖片程式碼如下:/// <summary> /// Opens the camera /// </summary> /// <returns>The camera.</returns> IEnumerator OpenCamera() { yield return Application.RequestUserAuthorization (UserAuthorization.WebCam); if (Application.HasUserAuthorization (UserAuthorization.WebCam)) { WebCamDevice[] devices = WebCamTexture.devices; webCam = new WebCamTexture (devices [0].name, Screen.width, Screen.height, 12); image_userIcon.texture = webCam; webCam.Play (); } }
執行完這段效果大概是這樣滴:/// <summary> /// Gets the texture2d. /// </summary> /// <returns>The texture2d.</returns> IEnumerator GetTexture2d() { yield return new WaitForEndOfFrame(); RectTransform rt = image_userIcon.GetComponent<RectTransform> (); Vector2 v2Min = new Vector2( rt.anchorMin.x * Screen.width,rt.anchorMin.y * Screen.height); Vector2 v2Max = new Vector2( rt.anchorMax.x * Screen.width,rt.anchorMax.y * Screen.height); Texture2D t = new Texture2D((int)(v2Max.x-v2Min.x),(int)(v2Max.y-v2Min.y));//要儲存圖片的大小 //擷取的區域 t.ReadPixels(new Rect (v2Min.x,v2Min.y,(int)(v2Max.x-v2Min.x),(int)(v2Max.y-v2Min.y)),0,0,false); t.Apply(); image_userIcon.texture = t; //把圖片資料轉換為byte陣列 byte[] byt = t.EncodeToPNG(); //然後儲存為圖片 File.WriteAllBytes(Application.dataPath + "/StreamingAssets/shexiang/" + Time.time + ".jpg", byt); webCam.Pause (); }