在使用Unity3D这个引擎做科研或者工程的过程中,有时候需要获得某一个虚拟摄像机实时拍到的画面并保存为图片。
这里给出一种简单的实现方法。原理很简单,先将虚拟摄像机的图像转移到一个RenderTexture上,然后使用Texture2D的像素读取功能来将图像数据获取到Texture2D类型的数据中,最后保存到图片。
using UnityEngine;
using System.Collections;
using System.IO;
public class GetImage : MonoBehaviour {
public Camera mainCam; //待截图的目标摄像机
RenderTexture rt; //声明一个截图时候用的中间变量
Texture2D t2d ;
int num = 0; //截图计数
//public GameObject pl; //一个调试用的板子
void Start () {
t2d = new Texture2D(800,600,TextureFormat.RGB24,false);
rt = new RenderTexture(800, 600, 24);
mainCam.targetTexture = rt;
}
void Update () {
//按下空格键来截图
if (Input.GetKeyDown(KeyCode.Space))
{
//将目标摄像机的图像显示到一个板子上
//pl.GetComponent().material.mainTexture = rt;
//截图到t2d中
RenderTexture.active = rt;
t2d.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
t2d.Apply();
RenderTexture.active = null;
//将图片保存起来
byte[] byt = t2d.EncodeToJPG();
File.WriteAllBytes(Application.dataPath + "//"+ num.ToString() +".jpg", byt);
Debug.Log("当前截图序号为:"+num.ToString());
num++;
}
}
}
版权声明:本文为CSDN博主「鱼儿-1226」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_21743659/article/details/108095353





