获取相机画面,保存为JPG图片

指定一个相机,将相机画面保存为JPG图片。示例代码为截取800x800像素尺寸,可根据需求修改获取的画幅。

    /// 
    /// 获取相机画面,保存为JPG
    /// 
    /// 指定的相机
    /// 图片命名
    void CameraCapture(Camera m_Camera, string filename)
    {
        //获取相机纹理
        RenderTexture rt = new RenderTexture(800, 800, 16);
        m_Camera.targetTexture = rt;
        m_Camera.Render();
        RenderTexture.active = rt;
        Texture2D t = new Texture2D(800, 800);
        t.ReadPixels(new Rect(0, 0, t.width, t.height), 0, 0);
        t.Apply();

        //保存JPG图片
        string[] ss = Application.dataPath.Split("/");
        string path = "";
        for (int i = 0; i < ss.Length - 1; i++)
        {
            path += ss[i] + "/";
        }
        
        string filePath = path + "/RecMap/" + filename + ".jpg";
        System.IO.File.WriteAllBytes(filePath, t.EncodeToJPG());
        m_Camera.targetTexture = null;

    }

你可能感兴趣的:(unity)