Unity场景相机图像抓取与保存
![](https://i-blog.csdnimg.cn/blog_migrate/728f335b18b38fc736b7c1cbeb7155ae.png)
using UnityEngine;
using UnityEditor;
public class IMGCapture : MonoBehaviour
{
public Camera _camera;
private int index = 0;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Texture2D tx = RendererTexToTexture2D(_camera.targetTexture);
SaveToPNG(tx);
AssetDatabase.Refresh();
}
}
private Texture2D RendererTexToTexture2D(RenderTexture rt)
{
int width = rt.width;
int height = rt.height;
Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false);
RenderTexture.active = rt;
texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
texture2D.Apply();
return texture2D;
}
private void SaveToPNG(Texture2D tx)
{
string path = Application.dataPath+"/Scenes/PoseEstimation/images/"+index+".png";
byte[] m_bytes = tx.EncodeToPNG();
System.IO.File.WriteAllBytes(path, m_bytes);
index++;
}
}