ScreenshotManager.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Runtime.InteropServices;
  5. namespace Imagine.WebAR
  6. {
  7. public class ScreenshotManager : MonoBehaviour
  8. {
  9. [DllImport("__Internal")] private static extern void ShowWebGLScreenshot(string dataUrl);
  10. private ARCamera arCamera;
  11. [SerializeField] private AudioClip shutterSound;
  12. [SerializeField] private AudioSource shutterSoundSource;
  13. public Texture2D screenShot;
  14. void Start(){
  15. arCamera = GameObject.FindObjectOfType<ARCamera>();
  16. }
  17. public void GetScreenShot()
  18. {
  19. if(arCamera.videoPlaneMode == ARCamera.VideoPlaneMode.NONE)
  20. {
  21. Debug.LogWarning("Your screenshot will not include the webcam image. Enable Video plane in your AR Camera to properly capture screenshots");
  22. }
  23. Debug.Log("Getting Screenshot...");
  24. // Delete old textures to avoid memory leaks
  25. if(screenShot != null){
  26. Destroy(screenShot);
  27. }
  28. // Create a RenderTexture to temporarily hold the camera image
  29. screenShot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);
  30. RenderTexture renderTexture = new RenderTexture(screenShot.width, screenShot.height, 24);
  31. Camera.main.targetTexture = renderTexture;
  32. Camera.main.Render();
  33. // Read the pixels from the RenderTexture into the Texture2D
  34. RenderTexture.active = renderTexture;
  35. screenShot.ReadPixels(new Rect(0, 0, screenShot.width, screenShot.height), 0, 0);
  36. screenShot.Apply();
  37. // Clean up by resetting the targetTexture and releasing the RenderTexture
  38. Camera.main.targetTexture = null;
  39. RenderTexture.active = null;
  40. Destroy(renderTexture);
  41. if(shutterSoundSource != null && shutterSound != null){
  42. shutterSoundSource.PlayOneShot(shutterSound);
  43. }
  44. #if UNITY_EDITOR
  45. Debug.Log("Screenshots are only displayed on WebGL builds");
  46. #else
  47. byte[] textureBytes = screenShot.EncodeToJPG();
  48. string dataUrlStr = "data:image/jpeg;base64," + System.Convert.ToBase64String(textureBytes);
  49. ShowWebGLScreenshot(dataUrlStr);
  50. #endif
  51. }
  52. }
  53. }