Unity 客製化相機(舊)

由於上一篇客製化相機已經是一年之前的事情了,現在大家都在用UGUI,於是重新寫了一篇新的,而上一篇就留著作紀念吧......

P.S.可直接用於電腦或手機(皆必須有鏡頭才可正常工作),差別在於儲存地點而已。

 

開一個新專案,由於相機是2D畫面,所以建立了2D的專案

 

放置好RawImage和Button (其中RawImage也可換成Panel或Image,只是用來方便得知影像要顯示的範圍而已)

以及新增一個C#腳本

 

RawImage和Button的Text設置如下(Button本身晚點再說)

RawImage的Color部分不管什麼顏色都沒差,到時候顯示的影像會覆蓋在上面

 

然後開啟Text.cs,並輸入以下程式碼~


using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    public GameObject rawImageObject;
    private RectTransform cameraSize;//拍攝和顯示的影像大小
    private RawImage showImage;//顯示圖片
    private WebCamTexture myCam;//接收攝影機讀取到的圖片數據
    private string filepath = @"D:\picture.jpg";//儲存照片的路徑

    private void Start ()
    {
        //取得RectTransform和RawImage元件
        cameraSize = rawImageObject.GetComponent<RectTransform>();
        showImage = rawImageObject.GetComponent<RawImage>();

        StartCoroutine(OpenCamera());//開啟攝影機鏡頭
    }
    
    private void OnGUI ()
    {
        //若有開啟鏡頭則將拍到的畫面顯示出來
        if (myCam != null)
        {
            /* (new Rect(影像起始x軸,影像起始y軸,要顯示出來的寬度,要顯示出來的高度), 顯示的影像或圖片) */
            GUI.DrawTexture(new Rect(0, 0, (int)cameraSize.rect.width, (int)cameraSize.rect.height), myCam);
        }
    }
    
    public void GetButton()
    {
        StartCoroutine(GetPicture());//拍照
    }

    private IEnumerator OpenCamera()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授權開啟鏡頭

        if (Application.HasUserAuthorization(UserAuthorization.WebCam))//若同意開啟攝影機
        {
            //設置攝影機截取到的影像範圍
            /* (攝影機名稱, 攝影機影像的寬度, 攝影機影像的高度, 攝影機的FPS) */
            myCam = new WebCamTexture(WebCamTexture.devices[0].name, (int)cameraSize.rect.width, (int)cameraSize.rect.height, 30);
            myCam.Play();//開啟攝影機
        }
    }

    private IEnumerator GetPicture()
    {
        yield return new WaitForEndOfFrame(); //攝影機讀取到的Frame繪製完畢後才進行拍照

        Texture2D t = new Texture2D((int)cameraSize.rect.width, (int)cameraSize.rect.height);//要保存的圖片大小
        t.ReadPixels(new Rect(0, Screen.height - (int)cameraSize.rect.height, (int)cameraSize.rect.width, (int)cameraSize.rect.height), 0, 0, true);//圖片截取的區域//圖片截取的區域

        using (FileStream fs = File.Open(filepath, FileMode.Create))
        {
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(t.EncodeToJPG());
        }

        Debug.Log("拍照完成!");
    }

    private void OnDisable()
    {
        myCam.Stop();//離開當前Scene後關閉攝影機
    }
}


 

我將此腳本拖曳到Main Camera上

 

最後就是設置Button了!

 

都完成後即可執行!按下Get可成功拍照。

arrow
arrow
    全站熱搜

    Yang 發表在 痞客邦 留言(10) 人氣()