获取Unity3D虚拟摄像机的图像

在使用Unity3D这个引擎做科研或者工程的过程中,有时候需要获得某一个虚拟摄像机实时拍到的画面并保存为图片。这里给出一种简单的实现方法。原理很简单,先将虚拟摄像机的图像转移到一个RenderTexture上,然后使用Texture2D的像素读取功能来将图像数据获取到Texture2D类型的数据中,最后保存到图片。

 

 
  1. using UnityEngine;

  2. using System.Collections;

  3. using System.IO;

  4.  
  5.  
  6. public class GetImage : MonoBehaviour {

  7.  
  8. public Camera mainCam; //待截图的目标摄像机

  9. RenderTexture rt; //声明一个截图时候用的中间变量

  10. Texture2D t2d ;

  11. int num = 0; //截图计数

  12.  
  13. //public GameObject pl; //一个调试用的板子

  14.  
  15.  
  16.  
  17. void Start () {

  18. t2d = new Texture2D(800,600,TextureFormat.RGB24,false);

  19. rt = new RenderTexture(800, 600, 24);

  20. mainCam.targetTexture = rt;

  21.  
  22. }

  23.  
  24. void Update () {

  25. //按下空格键来截图

  26. if (Input.GetKeyDown(KeyCode.Space))

  27. {

  28. //将目标摄像机的图像显示到一个板子上

  29. //pl.GetComponent<Renderer>().material.mainTexture = rt;

  30.  
  31. //截图到t2d中

  32. RenderTexture.active = rt;

  33. t2d.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);

  34. t2d.Apply();

  35. RenderTexture.active = null;

  36.  
  37. //将图片保存起来

  38. byte[] byt = t2d.EncodeToJPG();

  39. File.WriteAllBytes(Application.dataPath + "//"+ num.ToString() +".jpg", byt);

  40.  
  41.  
  42. Debug.Log("当前截图序号为:"+num.ToString());

  43. num++;

  44. }

  45. }

  46. }

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值