zoukankan      html  css  js  c++  java
  • 获取Unity3D虚拟摄像机的图像

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

  • 相关阅读:
    Mybatis Generator 生成的mapper只有insert方法
    someone you loved 歌词翻译
    Illegal instant due to time zone offset transition (Asia/Shanghai)_夏令时问题
    React js ReactDOM.render 语句后面不能加分号
    node js 路由
    node -v node is not define
    怎样从gitHub上面拉项目
    工作3年java面试题整理(自用)
    状态模式
    代理模式
  • 原文地址:https://www.cnblogs.com/yanhuiqingkong/p/7770095.html
Copyright © 2011-2022 走看看