[英]Convert RenderTexture to Texture2D
我需要將一個 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);
}
}
創建新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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.