C# 将RenderTexture转换为Texture2D
我需要将RenderTexture对象保存到一个.png文件中,然后该文件将用作一个纹理来环绕3D对象。我的问题是现在无法使用EncodeToPNG()保存RenderTexture对象,因为RenderTexture不包含该方法。如何将RenderTexture对象转换为Texture2D对象?谢谢大家!C# 将RenderTexture转换为Texture2D,c#,unity3d,io,export,C#,Unity3d,Io,Export,我需要将RenderTexture对象保存到一个.png文件中,然后该文件将用作一个纹理来环绕3D对象。我的问题是现在无法使用EncodeToPNG()保存RenderTexture对象,因为RenderTexture不包含该方法。如何将RenderTexture对象转换为Texture2D对象?谢谢大家! // Saves texture as PNG file. using UnityEngine; using System.Collections; using System.IO; pu
// Saves texture as PNG file.
using UnityEngine;
using System.Collections;
using System.IO;
public class SaveTexture : MonoBehaviour {
public RenderTexture tex;
// Save Texture as PNG
void SaveTexturePNG()
{
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);
// For testing purposes, also write to a file in the project folder
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
}
}
创建新的
Texture2D
,使用RenderTexture.ReadPixels
将像素从RenderTexture
读取到新的Texture2D
中。最后,调用Texture2D.Apply()
以应用更改的像素
Texture2D toTexture2D(RenderTexture rTex)
{
Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
// ReadPixels looks at the active RenderTexture.
RenderTexture.active = rTex;
tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
tex.Apply();
return tex;
}
用法:
public RenderTexture tex;
Texture2D myTexture = toTexture2D(tex);
public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();
您可以将其作为扩展方法(还原以前的活动渲染器以避免意外): 用法:
public RenderTexture tex;
Texture2D myTexture = toTexture2D(tex);
public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();
为什么需要将rTex设置为RenderTexture.active?@ErayTuncer
Texture2D。ReadPixels
将从当前活动的RenderTexture
复制一个矩形像素区域,并将其存储在Texture2D/tex
中。最好阅读此答案中使用的每个属性函数的文档。您可能需要存储现有的RenderTexture
,然后将其还原。