Skip to content

Instantly share code, notes, and snippets.

@emilianavt
Created April 24, 2019 10:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emilianavt/e17f2c06141d2507cd77aa162ea676ff to your computer and use it in GitHub Desktop.
Save emilianavt/e17f2c06141d2507cd77aa162ea676ff to your computer and use it in GitHub Desktop.
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