您当前的位置: 首页 >  unity

鱼儿-1226

暂无认证

  • 0浏览

    0关注

    1100博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

获取Unity3D虚拟摄像机的图像

鱼儿-1226 发布时间:2020-08-19 10:47:29 ,浏览量:0

在使用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().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. }

关注
打赏
1604459285
查看更多评论
立即登录/注册

微信扫码登录

0.0536s