【问题标题】:Converting RenderTexture to Texture2D in Unity 2019在 Unity 2019 中将 RenderTexture 转换为 Texture2D
【发布时间】:2019-11-13 19:34:50
【问题描述】:

我正在使用 Intel Real Sense 作为相机设备来捕捉图片。捕获结果显示为RenderTexture。由于我需要通过UDP发送它,我需要将它转换为byte[],但它只适用于Texture2D。是否可以在统一 2019 中将 RenderTexture 转换为 Texture2D

编辑: 现在,我正在使用此代码将 RenderTexture 转换为 Texture2D:

Texture2D toTexture2D(RenderTexture rTex)
{
    Texture2D tex = new Texture2D(rTex.width, rTex.width, TextureFormat.ARGB32, false);
    RenderTexture.active = rTex;
    tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
    tex.Apply();

    return tex;
}

我从here 获得了这段代码,它不再适用于 unity 2019,因为如果我显示纹理它只会给我白色纹理。

编辑 2: 这里我是如何调用该函数的:

//sender side
Texture2D WebCam;
public RawImage WebCamSender;
public RenderTexture tex;
Texture2D CurrentTexture;

//receiver side
public RawImage WebCamReceiver;
Texture2D Textur;
IEnumerator InitAndWaitForWebCamTexture()
{

    WebCamSender.texture = tex;
    CurrentTexture = new Texture2D(WebCamSender.texture.width, 
    WebCamSender.texture.height, TextureFormat.RGB24, false, false);
    WebCam = toTexture2D(tex);

    while (WebCamSender.texture.width < 100) //WebCam
    {
        yield return null;
    }

    StartCoroutine(SendUdpPacketVideo());
}

然后我会像这样通过网络发送它:

IEnumerator SendUdpPacketVideo()
{
        ...
        CurrentTexture.SetPixels(WebCam.GetPixels());
        byte[] PNGBytes = CurrentTexture.EncodeToPNG();
        ...
}

在接收端,我将对其进行解码并显示在原始图像上:

....
Textur.LoadImage(ReceivedVideo);
WebCamReceiver.texture = Textur;
...

【问题讨论】:

  • 你的设备是什么?
  • 你能添加你的代码吗?
  • @0xBFE1A8 我打算创建一个windows程序。
  • @derHugo 我还没有找到将rendertexture 转换为texture2D 的工作代码。我会发布非工作的,等等。

标签: unity3d textures texture2d realsense


【解决方案1】:

最优化的方法是:

public Texture2D toTexture2D(RenderTexture rTex)
{
    Texture2D dest = new Texture2D(rTex.width, rTex.height, TextureFormat.RGBA32, false);
    dest.Apply(false);
    Graphics.CopyTexture(rTex, dest);
    return dest;
}

【讨论】:

  • 感谢您的帮助。该代码比以前工作得更好,但它仍然没有显示纹理。只有这样的灰色显示:i.imgur.com/2DUDMHy.jpg
  • 这个方法具体怎么称呼?
  • 我正在使用 IEnumerator 逐帧生成并在 RawImage 上将其设置为纹理。
  • 我已经在帖子中添加了。
  • @0xBFE1A8 你可能不需要Apply 之后 Graphics.Copy吗?为什么以前做?文档还说数据格式必须匹配..但默认情况下,afaik RenderTexture 是 24 位 RGB 并且没有 alpha 通道,除非 OP 改变了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多