Skip to content

Instantly share code, notes, and snippets.

@ZackAkil
Last active May 28, 2024 09:28
Show Gist options
  • Save ZackAkil/b22471aefa05fac6ad46f7589081dffb to your computer and use it in GitHub Desktop.
Save ZackAkil/b22471aefa05fac6ad46f7589081dffb to your computer and use it in GitHub Desktop.
Unity code to save camera view to PNG image.
void Save_camera_image(Camera cam, string path){
// set render target to target texture
var currentRT = RenderTexture.active;
RenderTexture.active = cam.targetTexture;
// Make a new texture and read the active Render Texture into it.
Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
image.Apply();
// encode to PNG
byte[] _bytes = texture.EncodeToPNG();
// save file
System.IO.File.WriteAllBytes(path, _bytes);
// set render texture back to default
RenderTexture.active = currentRT;
}
@danieldownes
Copy link

danieldownes commented May 28, 2024

byte[] _bytes = texture.EncodeToPNG();

texture is null ref.

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