我使用Intel Real Sense作为相机设备来捕捉图片。捕获结果显示为
RenderTexture
。由于我需要通过UDP
发送,因此我需要将其转换为byte[]
,但它仅适用于Texture2D
。是否可以在unity 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;
...
最优化的方法是:
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;
}