unity - 保存camera组件图像

My project(1)

“CameraImage”

public class CameraImage : MonoBehaviour
{
    // 拍摄的相机对象
    public Camera captureCamera ;

    
    public void CaptureScreenshot()
    {
        // 图片保存根目录
        string dataPath = "D:/A/B";
        // 图片文件夹中对应的本项目文件夹
        string productname = Application.productName;
        // 保存图片
        string filePath = Path.Combine(dataPath, productname, "image.png");
        
        // 判断项目文件夹是否存在
        string root = Path.Combine(dataPath, productname);
        if (!Directory.Exists(root))
        {
            Directory.CreateDirectory(root);
        }
        
        // 如果图像文件已经存在就删除原有文件
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }

        // 创建一个RenderTexture对象,其大小与屏幕现实的图像尺寸相同,设置24位的渲染纹理的深度
        RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
        // 将captureCamera的目标纹理设置为上述渲染纹理
        captureCamera.targetTexture = renderTexture;
        // 使用Render()方法进行渲染
        captureCamera.Render();
        // 激活创建的渲染纹理,便于后续操作
        RenderTexture.active = renderTexture;

        // 创建一个Texture2D对象,大小和屏幕尺寸相同,格式为RGB24,不适用mipmap
        Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        // 调用ReadPixels()方法从渲染纹理中读取像素数据,并存在screenshot对象中。
        screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height),0 ,0);
        screenshot.Apply();

        // 将screenshot对象编码为PNG格式的字节数组,并将该数组写入到指定的文件路径中
        byte[] bytes = screenshot.EncodeToPNG();
        File.WriteAllBytes(filePath, bytes);

        // 将当前激活的渲染纹理设置为null,清除captureCamera的目标纹理,并释放renderTexture对象的资源
        RenderTexture.active = null;
        captureCamera.targetTexture = null;
        renderTexture.Release();
        
        Debug.Log("图像已保存至:"+ filePath);
    }
    void Start()
    {
        // 获取相机组件
        captureCamera = GetComponent<Camera>();
    }


    void Update()
    {
        // 按C键拍摄
        if (Input.GetKeyDown(KeyCode.C))
        {
            CaptureScreenshot();
        }
    }
}

你可能感兴趣的:(unity,unity)