unity 开启外部摄像头

在unity中建立一个image作为摄像头显示画面,然后通过命令render到image上即可。

    public WebCamTexture webTex;  
    public string deviceName;  
      
    void Start()  
    {  
          StartCoroutine(CallCamera())
    }  
    void Update()  
    {  
          
    }  ///  
///调用摄像头  
///  
    IEnumerator CallCamera()    
    {  
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);    
        if(Application.HasUserAuthorization(UserAuthorization.WebCam))    
        {    
            WebCamDevice[] devices = WebCamTexture.devices;        
            deviceName = devices[0].name;    
            //设置摄像机摄像的区域    
            webTex=new WebCamTexture(deviceName,10,10,10); 
GetComponent<MeshRenderer>().material.mainTexture = webTex; webTex.Play();
//开始摄像 }
}

 抓取当前画面

    public void Capture()
    {
        //WebCamTexture wc = new WebCamTexture(160, 120);
        //wc.play();
        Texture2D t = new Texture2D(webTex.width, webTex.height);
        t.SetPixels(webTex.GetPixels());
        t.Apply();
        byte[] byt = t.EncodeToPNG();
        File.WriteAllBytes(@"D:/test.jpg", byt);
    }

 

posted @ 2017-06-06 15:46  81192  阅读(1771)  评论(0编辑  收藏  举报