纳金网
标题: 调用外接摄像头并保存图片 [打印本页]
作者: 710960383 时间: 2017-2-8 09:09
标题: 调用外接摄像头并保存图片
有的项目要求调用摄像头,并且把图像保存下来,上传到服务器。这里有几个难点,调用摄像头是很简单的,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. //重启开始
18. if (GUI.Button(new Rect(0, 300, 100, 30), "restart"))
19. {
20. tex.Play();
21. }
22. if (GUI.Button(new Rect(100, 0, 100, 30), "摄像"))
23. {
24. //开始摄像,摄像就是一系列的图片集合
25. StartCoroutine(getTexture2dshexiang());
26. }
27. if(tex!=null)
28. GUI.DrawTexture(new Rect(200, 200, 200, 180), tex);
29. }
保存图片是一个难点,找了半天,才发现这个方法来实现
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. }
保存文件的路径需要自己来设置,要保存的区域大家自己可以来调。
转自:http://bbs.9ria.com/thread-170539-1-1.html
欢迎光临 纳金网 (http://go.narkii.com/club/) |
Powered by Discuz! X2.5 |