You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何获取主虚拟相机画面的byte[]数组?

获取Unity主相机画面的byte[]帧数据方法

这里给你一套直接可用的实现方案,针对新手做了简化:

核心逻辑

通过RenderTexture捕获主相机的帧画面,再将其转换为Texture2D,最后编码成你需要的byte[]格式。

步骤与代码示例

直接在Unity中新建一个C#脚本,挂在任意GameObject上(比如主相机):

using UnityEngine;

public class CameraCapture : MonoBehaviour
{
    private Camera mainCamera;
    private RenderTexture tempRenderTexture;
    private Texture2D captureTexture;

    void Start()
    {
        // 获取主相机
        mainCamera = Camera.main;
        if (mainCamera == null)
        {
            Debug.LogError("场景中没有标记为MainCamera的相机!");
            return;
        }

        // 初始化RenderTexture和Texture2D,尺寸和主相机一致
        int width = mainCamera.pixelWidth;
        int height = mainCamera.pixelHeight;
        tempRenderTexture = new RenderTexture(width, height, 24);
        captureTexture = new Texture2D(width, height, TextureFormat.RGB24, false);
    }

    /// <summary>
    /// 捕获当前主相机画面并返回byte[](PNG格式)
    /// </summary>
    public byte[] CaptureCameraFrame()
    {
        if (mainCamera == null || tempRenderTexture == null || captureTexture == null)
        {
            Debug.LogError("捕获前请确保相机和纹理已初始化!");
            return null;
        }

        // 临时替换相机的渲染目标,将画面渲染到RenderTexture
        RenderTexture originalTarget = mainCamera.targetTexture;
        mainCamera.targetTexture = tempRenderTexture;
        mainCamera.Render(); // 手动渲染一帧

        // 从RenderTexture读取像素到Texture2D
        RenderTexture.active = tempRenderTexture;
        captureTexture.ReadPixels(new Rect(0, 0, tempRenderTexture.width, tempRenderTexture.height), 0, 0);
        captureTexture.Apply();

        // 恢复相机原来的渲染目标,避免影响正常显示
        mainCamera.targetTexture = originalTarget;
        RenderTexture.active = null;

        // 编码为PNG格式的byte数组,要JPG的话用EncodeToJPG()
        return captureTexture.EncodeToPNG();
    }

    // 场景销毁时释放资源,避免内存泄漏
    void OnDestroy()
    {
        if (tempRenderTexture != null)
            Destroy(tempRenderTexture);
        if (captureTexture != null)
            Destroy(captureTexture);
    }
}

新手注意事项

  • 调用时机:可以在Update()里按需调用CaptureCameraFrame(),或者绑定到按钮点击事件。
  • 格式选择:如果需要原始像素数据(未压缩),可以用captureTexture.GetPixels32()获取Color32数组,再用System.BitConverter转成byte[],不过这种数据量会很大。
  • 分辨率问题:如果不想用相机的原生分辨率,可以手动设置RenderTexture的宽高,但要注意画面拉伸。
  • 线程限制:所有纹理操作必须在主线程执行,不要在后台线程调用捕获方法。

内容的提问来源于stack exchange,提问作者humble_pianist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:04:54