unity3D调用外接摄像头,并保持为图片

来源:互联网 发布:网络文明宣传语 编辑:程序博客网 时间:2024/05/16 14:46
项目要求调用摄像头,并且把图像保存下来,上传到服务器。 
这里有几个难点,调用摄像头是很简单的,unity已经提供好了接口,我们只需要调用就行。
问题就是怎么把图片保存下来。我们来看下代码。
   
  1. public string deviceName;
  2. WebCamTexture tex;//接收返回的图片数据
  3. /// <summary>
  4. /// 实现IEnumerator接口,这里使用了一个协程,相当于多线程。
  5. /// 这里是调用摄像头的方法。
  6. /// </summary>
  7. /// <returns></returns>
  8. IEnumerator test()
  9. {
  10. yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授权
  11. if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  12. {
  13. WebCamDevice[] devices = WebCamTexture.devices;
  14. deviceName = devices[0].name;
  15. //设置摄像机摄像的区域
  16. tex = new WebCamTexture(deviceName, 400, 300, 12);
  17. tex.Play();//开始摄像
  18. }
  19. }
复制代码



这段代码就是Unity调用摄像头的方法,图片数据就保存在tex中。 
下面看这段怎么使用上面的那段代码。




   
  1. void OnGUI()
  2. {
  3. //开始按钮
  4. if (GUI.Button(new Rect(0, 0, 100, 100), "click"))
  5. {
  6. //调用启动那个协程,开启摄像头
  7. StartCoroutine(test());
  8. }
  9. //暂停
  10. if(GUI.Button(new Rect(0,200,100,30),"pause"))
  11. {
  12. tex.Pause();
  13. //这个方法就是保存图片
  14. StartCoroutine(getTexture2d());
  15. }

  16. //重启开始
  17. if (GUI.Button(new Rect(0, 300, 100, 30), "restart"))
  18. {
  19. tex.Play();
  20. }
  21. if (GUI.Button(new Rect(100, 0, 100, 30), "摄像"))
  22. {
  23. //开始摄像,摄像就是一系列的图片集合
  24. StartCoroutine(getTexture2dshexiang());
  25. }
  26. if(tex!=null)
  27. GUI.DrawTexture(new Rect(200, 200, 200, 180), tex);
  28. }
复制代码

保存图片是一个难点,找了半天,才发现这个方法来实现   
  1. /// <summary>
  2. /// 获取摄像头截取的图片,这里也是一个协程
  3. /// </summary>
  4. /// <returns></returns>
  5. IEnumerator getTexture2d()
  6. {
  7. yield return new WaitForEndOfFrame();
  8. Texture2D t = new Texture2D(200, 180);//要保存图片的大小
  9. //截取的区域
  10. t.ReadPixels(new Rect(200, 320, 200, 180), 0, 0, false);
  11. t.Apply();
  12. //把图片数据转换为byte数组
  13. byte[] byt = t.EncodeToPNG();
  14. //然后保存为图片
  15. File.WriteAllBytes(Application.dataPath + "/shexiang/" + Time.time + ".jpg", byt);
  16. }
复制代码



保存文件的路径需要自己来设置,要保存的区域大家自己可以来调。