Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.IO;
using UnityEngine;
// Attach this to a camera and position it. You can use "Align With View" from the "Game Object" menu to help with this.
// Check the snap box to take a picture. It will log the path to the console.
// It works in Editor mode too, no need to play the scene.
[ExecuteInEditMode]
public class CameraSnap : MonoBehaviour {
public int resolutionX = 2048;
public int resolutionY = 2048;
public float fieldOfView = 23.9f;
public bool snap = false;
private byte[] texToPNG(Texture tex) {
if (tex == null) {
Debug.Log("No texture");
return null;
}
RenderTexture prev = RenderTexture.active;
RenderTexture.active = RenderTexture.GetTemporary(tex.width, tex.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
Graphics.Blit(tex, RenderTexture.active);
Texture2D readTex = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, false);
readTex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
readTex.Apply();
RenderTexture.ReleaseTemporary(RenderTexture.active);
RenderTexture.active = prev;
return readTex.EncodeToPNG();
}
public void Capture() {
Camera cam = GetComponent<Camera>();
cam.fieldOfView = fieldOfView;
cam.aspect = (float)resolutionX / (float)resolutionY;
cam.stereoTargetEye = StereoTargetEyeMask.None;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = new Color(0f, 0f, 0f, 0f);
cam.useOcclusionCulling = false;
cam.allowHDR = true;
cam.allowMSAA = true;
RenderTexture active = RenderTexture.active;
cam.targetTexture = RenderTexture.GetTemporary(resolutionX, resolutionY, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
RenderTexture.active = cam.targetTexture;
cam.Render();
string filename = Application.persistentDataPath + "/Photo-" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
byte[] png = texToPNG(cam.targetTexture);
if (png != null) {
File.WriteAllBytes(filename, png);
Debug.Log(filename);
}
RenderTexture.active = active;
active = cam.targetTexture;
cam.targetTexture = null;
RenderTexture.ReleaseTemporary(active);
}
public void Update() {
if (snap) {
snap = false;
Capture();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment