Unity3D使用C#腳本調用外置攝像頭拍攝照片,並轉化成byte數組


  TakePhoto.cs

  IEnumerator Start() 
  {
        
        //獲取攝像頭
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if(Application.HasUserAuthorization(UserAuthorization.WebCam))
        {

            WebCamDevice[] devices = WebCamTexture.devices;
            if(devices !=null)
            {
          //獲取設備名稱 deviceName
= devices[0].name; tex = new WebCamTexture(deviceName,400,300,12); tex.Play();//建議在需要拍攝照片的時候開啟攝像頭,不拍攝時將其關閉掉,這里可以使用tex.Pause()暫停攝像頭,tex.Stop()關閉攝像頭 } } } //獲取像素 private byte[] GetPhotoPixel(WebCamTexture ca) { Texture2D texture = new Texture2D (ca.width,ca.height); int y = 0; while (y < texture.height) { int x = 0; while (x < texture.width) { UnityEngine.Color color = ca.GetPixel(x,y); texture.SetPixel(x,y,color); ++x; } ++y; } texture.Apply (); // texture.name = name ; byte[] pngData = GetJpgData (texture); return pngData ; } //控制照片大小 private byte[] GetJpgData(Texture2D te) { byte[] data= null ; int quelity = 75 ; while(quelity > 20) { data = te.EncodeToJPG(quelity); int size = data.Length/1024; if( size > 30 ) { quelity -=5; } else { break ; } } return data ; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM