【问题标题】:Convert RenderTexture to Texture2D将 RenderTexture 转换为 Texture2D
【发布时间】:2017-05-30 14:03:37
【问题描述】:

我需要将 RenderTexture 对象保存到 .png 文件中,然后该文件将用作包裹 3D 对象的纹理。我的问题是现在我无法使用 EncodeToPNG() 保存 RenderTexture 对象,因为 RenderTexture 不包含该方法。如何将 RenderTexture 对象转换为 Texture2D 对象?谢谢!

// 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);
    }
}

【问题讨论】:

    标签: c# unity3d io export


    【解决方案1】:

    创建新的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);
    

    您可以将其设为扩展方法(恢复之前的活动 RenderTexture 以避免意外):

    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();
    

    【讨论】:

    • 为什么我需要将 rTex 设置为 RenderTexture .active?
    • @ErayTuncer Texture2D.ReadPixels 将从当前活动 RenderTexture 复制一个矩形像素区域并将其存储在Texture2D/tex 中。最好阅读此答案中使用的每个属性函数的文档。
    • 您可能需要存储现有的RenderTexture 并在之后恢复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多