Skip to content

Instantly share code, notes, and snippets.

@ZackAkil
Last active April 14, 2023 07:54
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment