将 RenderTexture 转换为 Texture2D [英] Convert RenderTexture to Texture2D
问题描述
我需要将一个 RenderTexture 对象保存到一个 .png 文件中,然后该文件将用作环绕 3D 对象的纹理.我的问题是现在我无法使用 EncodeToPNG() 保存 RenderTexture 对象,因为 RenderTexture 不包含该方法.如何将 RenderTexture 对象转换为 Texture2D 对象?谢谢!
I need to save a RenderTexture object to a .png file that will then be used as a texture to wrap about a 3D object. My problem is right now I can't save a RenderTexture object using EncodeToPNG() because RenderTexture doesn't include that method. How can I convert a RenderTexture object into a Texture2D object? Thank you!
// 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
读取像素code> 到新的 Texture2D
中.最后,调用 Texture2D.Apply();
来应用改变的像素.
Create new Texture2D
, use RenderTexture.ReadPixels
to read the pixels from RenderTexture
into the new Texture2D
. Finally, Call Texture2D.Apply();
to apply the changed pixels.
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);
可以做成扩展方法(恢复之前激活的RenderTexture,避免意外):
You can make it an extension method (restore the previous active RenderTexture to avoid surprises):
public static class ExtensionMethod
{
public static Texture2D toTexture2D(this RenderTexture rTex)
{
Texture2D tex = new Texture2D(rTex.width, rTex.height, TextureFormat.RGB24, false);
var old_rt = RenderTexture.active;
RenderTexture.active = rTex;
tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
tex.Apply();
RenderTexture.active = old_rt;
return tex;
}
}
用法:
public RenderTexture tex;
Texture2D myTexture = tex.toTexture2D();
这篇关于将 RenderTexture 转换为 Texture2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!