“OpenCameraAndSaveImage”腳本具體内容如下:
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class OpenCameraAndSaveImage : MonoBehaviour {
// UI 相關參數
public RawImage rawImage;
public Button button_TakePhoto;
// 錄影機圖檔參數
private WebCamTexture webCamTexture;
// Use this for initialization
void Start() {
// 打開相機
StartCoroutine("OpenCamera");
// 按鈕綁定點選事件
button_TakePhoto.onClick.AddListener(TakePhotoAndSaveImage_Button);
}
///
/// 使用協程打開相機函數
///
///
IEnumerator OpenCamera() {
// 申請相機權限
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
// 判斷是否有相機權限
if (Application.HasUserAuthorization(UserAuthorization.WebCam)) {
// 擷取相機裝置
WebCamDevice[] webCamDevices = WebCamTexture.devices;
// 判斷是否有相機設别
if (webCamDevices != null && webCamDevices.Length > 0) {
// 把 0 号裝置(移動端後置攝像頭)名稱指派
string webCamName = webCamDevices[0].name;
// 設定相機渲染寬高,并運作相機
webCamTexture = new WebCamTexture(webCamName, Screen.width, Screen.height);
webCamTexture.Play();
// 把擷取的圖像渲染到畫布上
rawImage.texture = webCamTexture;
}
}
}
///
/// 拍照儲存函數的包裝接口
///
void TakePhotoAndSaveImage_Button()
{
// 調用拍照儲存函數
TakePhotoAndSaveImage(webCamTexture);
}
///
/// 儲存圖檔的接口函數
///
///
void TakePhotoAndSaveImage(WebCamTexture tex) {
// 建立一個 Texture2D 來擷取相機圖檔
// 然後 把圖檔轉成 JPG 格式的 bytes
Texture2D texture2D = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, true);
texture2D.SetPixels32(tex.GetPixels32());
texture2D.Apply();
byte[] imageBytes = texture2D.EncodeToJPG();
// 判斷圖檔 bytes 是否為空
if (imageBytes != null && imageBytes .Length > 0) {
// 判斷Android 平台,進行對應路徑設定
string savePath ;
string platformPath = Application.streamingAssetsPath + "/MyTempPhotos";
#if UNITY_ANDROID && !UNITY_EDITOR
platformPath = "/sdcard/DCIM/MyTempPhotos";
#endif
// 如果檔案夾不存在,就建立檔案夾
if (!Directory.Exists(platformPath)) {
Directory.CreateDirectory(platformPath);
}
// 儲存圖檔
savePath = platformPath + "/" + Time.deltaTime + ".jpg";
File.WriteAllBytes(savePath, imageBytes);
}
}
}