Skip to content

Instantly share code, notes, and snippets.

@MathiasYde
Created June 4, 2023 18:03
Show Gist options
  • Save MathiasYde/beb2da0762eb62b3e21c17edcec690bf to your computer and use it in GitHub Desktop.
Save MathiasYde/beb2da0762eb62b3e21c17edcec690bf to your computer and use it in GitHub Desktop.
Export RenderTexture to a file
using System;
using UnityEditor;
using UnityEngine;
public static class RenderTextureUtils {
public static TextureFormat DEFAULT_TEXTURE_FORMAT = TextureFormat.RGBA64;
public static String DEFAULT_FILE_FORMAT = "png";
/// <summary>
/// Export a RenderTexture asset to a file
/// </summary>
/// <param name="renderTexture">The RenderTexture asset to export</param>
/// <param name="filePath">The path the file should be located when saved</param>
/// <exception cref="ArgumentException"></exception>
public static void ExportRenderTexture(RenderTexture renderTexture, String filePath) {
if (renderTexture == null) {
throw new ArgumentException("RenderTexture value is null");
}
if (filePath == "") {
throw new ArgumentException("FilePath value is non-valid, empty string");
}
// infer the file format from the file extension
String fileExtension = filePath.Substring(filePath.LastIndexOf('.') + 1).ToLower();
// transfer image from rendertexture to regular texture
Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, DEFAULT_TEXTURE_FORMAT, false);
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
// write texture to file
byte[] imageBytes;
switch (fileExtension) {
case "png":
imageBytes = texture.EncodeToPNG();
break;
case "jpg":
imageBytes = texture.EncodeToJPG();
break;
case "exr":
imageBytes = texture.EncodeToEXR();
break;
case "tga":
imageBytes = texture.EncodeToTGA();
break;
default:
throw new ArgumentException($"Invalid file extension: {fileExtension}");
}
System.IO.File.WriteAllBytes(filePath, imageBytes);
}
#if UNITY_EDITOR
public static String DEFAULT_FILE_NAME = "RenderTexture";
[MenuItem("Assets/RenderTexture/Export currently selected")]
private static void ExportRenderTexture() {
RenderTexture renderTexture = Selection.activeObject as RenderTexture;
String filePath = EditorUtility.SaveFilePanel(
"Export RenderTexture",
"", renderTexture?.name ?? DEFAULT_FILE_NAME,
DEFAULT_FILE_FORMAT);
ExportRenderTexture(renderTexture, filePath);
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment