unity截圖保存-RenderTexture轉Texture2D

unity截圖保存-RenderTexture轉Texture2D

使用unity項目開發過程中需要用到系統截圖功能時,其實主要的做法是將RenderTexture轉換為Texture2D,然後再轉為byte數組,最後創建圖片文件,寫入內存。下面是代碼演示:

public static bool SaveRenderTextureToPNG(RenderTexture rt, string contents, string pngName)

{

Debug.Log("正在保存PNG圖片...." + contents + "....." + pngName);

RenderTexture prev = RenderTexture.active;

RenderTexture.active = rt;

Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);

png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);

byte[] bytes = png.EncodeToPNG();

// if (!Directory.Exists(contents))

// Directory.CreateDirectory(contents);

string path = Path.Combine(Application.dataPath, pngName + ".jpeg");

FileStream file = File.Open(path, FileMode.Create);

BinaryWriter writer = new BinaryWriter(file);

writer.Write(bytes);

file.Close();

Texture2D.DestroyImmediate(png);

png = null;

RenderTexture.active = prev;

return true;

}

}


分享到:


相關文章: