IMHOTEP Framework
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Pages
Screenshot.cs
1 using UnityEngine;
2 using System.Collections;
3 using System;
4 
5 public class Screenshot : MonoBehaviour
6 {
7  public GameObject OVcamera;
8  public string path = "";
9  private bool takeScreen = false;
10 
11  private SteamVR_TrackedController device;
12 
13  void Start()
14  {
15  //OVcamera = Camera.main.gameObject;
16  device = GetComponent<SteamVR_TrackedController>();
17  device.Gripped += Trigger;
18  }
19 
20  void Trigger(object sender, ClickedEventArgs e)
21  {
22  takeScreen = true;
23  }
24 
25  void LateUpdate()
26  {
27 
28  if (takeScreen)
29  {
30  takeScreen = false;
31  Debug.LogWarning ("Start Capture Screen");
32  StartCoroutine(TakeScreenShot());
33  }
34 
35  }
36 
37  // return file name
38  string fileName(int width, int height)
39  {
40  return string.Format("screen_{0}x{1}_{2}.png",
41  width, height,
42  System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
43  }
44 
45  public IEnumerator TakeScreenShot()
46  {
47  Debug.LogWarning ("Capture Screen");
48  yield return new WaitForEndOfFrame();
49 
50  Camera camOV = OVcamera.GetComponent<Camera>();
51 
52  RenderTexture currentRT = RenderTexture.active;
53 
54  RenderTexture.active = camOV.targetTexture;
55  camOV.Render();
56  Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
57  imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
58  imageOverview.Apply();
59  RenderTexture.active = currentRT;
60 
61 
62  // Encode texture into PNG
63  byte[] bytes = imageOverview.EncodeToPNG();
64 
65  // save in memory
66  string filename = fileName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height));
67  path = filename;
68 
69  System.IO.File.WriteAllBytes(path, bytes);
70  }
71 }