2017-05-30 84 views
2

我需要將RenderTexture對象保存到.png文件,該文件然後將用作包裝3D對象的紋理。我的問題是現在我無法使用EncodeToPNG()保存RenderTexture對象,因爲RenderTexture不包含該方法。我如何將RenderTexture對象轉換爲Texture2D對象?謝謝!將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); 
    } 
} 

回答

5

創建新Texture2D,使用RenderTexture.ReadPixelsRenderTexture像素讀入新Texture2D。最後,致電Texture2D.Apply();應用更改的像素。

Texture2D toTexture2D(RenderTexture rTex) 
{ 
    Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false); 
    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 static class ExtensionMethod 
{ 
    public static Texture2D toTexture2D(this RenderTexture rTex) 
    { 
     Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false); 
     RenderTexture.active = rTex; 
     tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0); 
     tex.Apply(); 
     return tex; 
    } 
} 

用法:

public RenderTexture tex; 
Texture2D myTexture = tex.toTexture2D();