Skip to content

Instantly share code, notes, and snippets.

@krzys-h
Last active December 22, 2023 10:33
Show Gist options
  • Star 51 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save krzys-h/76c518be0516fb1e94c7efbdcd028830 to your computer and use it in GitHub Desktop.
Save krzys-h/76c518be0516fb1e94c7efbdcd028830 to your computer and use it in GitHub Desktop.
[Unity] Save RenderTexture to image file
using UnityEngine;
using UnityEditor;
public class SaveRenderTextureToFile {
[MenuItem("Assets/Save RenderTexture to file")]
public static void SaveRTToFile()
{
RenderTexture rt = Selection.activeObject as RenderTexture;
RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
byte[] bytes;
bytes = tex.EncodeToPNG();
string path = AssetDatabase.GetAssetPath(rt) + ".png";
System.IO.File.WriteAllBytes(path, bytes);
AssetDatabase.ImportAsset(path);
Debug.Log("Saved to " + path);
}
[MenuItem("Assets/Save RenderTexture to file", true)]
public static bool SaveRTToFileValidation()
{
return Selection.activeObject is RenderTexture;
}
}
using UnityEngine;
using UnityEditor;
public class SaveScreenshotToFile {
[MenuItem("Custom/Render Camera to file")]
public static void RenderCameraToFile()
{
Camera camera = Selection.activeGameObject.GetComponent<Camera>();
RenderTexture rt = new RenderTexture(2560, 1440, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
RenderTexture oldRT = camera.targetTexture;
camera.targetTexture = rt;
camera.Render();
camera.targetTexture = oldRT;
RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
byte[] bytes = tex.EncodeToPNG();
string path = "Assets/screenshot.png";
System.IO.File.WriteAllBytes(path, bytes);
AssetDatabase.ImportAsset(path);
Debug.Log("Saved to " + path);
}
[MenuItem("Custom/Render Camera to file", true)]
public static bool RenderCameraToFileValidation()
{
return Selection.activeGameObject != null && Selection.activeGameObject.GetComponent<Camera>() != null;
}
}
@mateosss
Copy link

Remember to call Object.Destroy(tex) after you are done with the texture or it'll leak. See this example from unity docs

@jwvanderbeck
Copy link

jwvanderbeck commented Dec 9, 2022

This is very helpful, thanks. But is there a way to retain the alpha information that the RT has?
EDIT: Turns out it was a simple as changing the texture format to TextureFormat.RGBA32

@MrBelarus
Copy link

Thanks, helped a lot!

@Thaina
Copy link

Thaina commented Jul 30, 2023

Would like to suggest making this gist a general png saver

https://gist.github.com/Thaina/44730376d4ef58bb52496d851634a531

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment