Skip to content

Instantly share code, notes, and snippets.

@Thaina
Forked from krzys-h/SaveRenderTextureToFile.cs
Created July 30, 2023 12:26
Show Gist options
  • Save Thaina/44730376d4ef58bb52496d851634a531 to your computer and use it in GitHub Desktop.
Save Thaina/44730376d4ef58bb52496d851634a531 to your computer and use it in GitHub Desktop.
[Unity] Save RenderTexture to image file
using UnityEngine;
using UnityEditor;
public class ConvertTextureToPng
{
const string MenuName = "Assets/Save Texture to png";
[MenuItem(MenuName)]
public static void SaveRTToFile()
{
var selected = Selection.activeObject;
if(!(selected is Texture2D tex))
{
if(selected is RenderTexture rt)
{
RenderTexture.active = rt;
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;
}
else throw new System.NotImplementedException("object type : " + Selection.activeObject);
}
var sourcePath = AssetDatabase.GetAssetPath(selected);
if(!tex.isReadable)
{
var source = tex;
tex = new Texture2D(source.width,source.height,source.format,true);
Graphics.CopyTexture(source,tex);
}
var bytes = tex.EncodeToPNG();
string path = AssetDatabase.IsMainAsset(selected) ? (sourcePath + ".png") : (sourcePath + "." + selected.name + ".png");
System.IO.File.WriteAllBytes(path, bytes);
AssetDatabase.ImportAsset(path);
Debug.Log("Saved to " + path);
}
[MenuItem(MenuName, true)]
public static bool SaveRTToFileValidation()
{
return Selection.activeObject is Texture2D or 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment