Get Android camera snapshots without freezing preview
Hi,
I am trying to get snapshots from the Android Camera without having the preview video of the camera freezing every time a snapshot is taken. I implemented this approach to read the video stream from the Camera (https://www.youtube.com/watch?v=c6NXkZWXHnc) and my implementation to take snapshot can be found here below. I also tried to wrap the method Snap() inside an 'async' method using await and Task.Run(), but the app crashes.
Can someone suggest a way to have the camera preview running smoothly while taking snashots and processing them?
public class PhoneCamera : MonoBehaviour {
private bool cameraAvailable;
private WebCamTexture backCamera;
private Texture defaultBackground;
Texture2D snap;
public RawImage background;
public AspectRatioFitter fit; // functions as a layout controller that controls the size of its own layout element
void Start ()
{
defaultBackground = background.texture;
WebCamDevice[] devices = WebCamTexture.devices;
if (devices.Length == 0)
{
Debug.Log("No camera detected");
cameraAvailable = false;
return;
}
for (int i = 0; i <devices.Length; i++)
if (!devices[i].isFrontFacing)
backCamera = new WebCamTexture(devices[i].name, Screen.width, Screen.height);
if (backCamera == null)
{
Debug.Log("Unable to find back camera");
return;
}
backCamera.Play();
background.texture = backCamera;
cameraAvailable = true;
snap = new Texture2D(backCamera.width, backCamera.height);
InvokeRepeating(nameof(Snap), 1f, 1f);
}
void Update ()
{
if (!cameraAvailable) return;
float ratio = (float)backCamera.width / (float)backCamera.height;
fit.aspectRatio = ratio;
float scaleY = backCamera.videoVerticallyMirrored ? -1f : 1f;
background.rectTransform.localScale = new Vector3(1f, scaleY, 1f);
int orient = - backCamera.videoRotationAngle;
background.rectTransform.localEulerAngles = new Vector3(0, 0, orient);
}
private void Snap()
{
snap.SetPixels(backCamera.GetPixels());
snap.Apply();
}
}
Have you tried ScreenCapture.CaptureScreenshot? It's an async method on Android.
Your answer
![](https://koobas.hobune.stream/wayback/20220612185258im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Android how to wake up the screen when in stand by 1 Answer
How can I get all cameras enabled true false states ? 0 Answers
Multi-display Mac Big Sur and Android Touch display 0 Answers
2.5D Camera follow script 0 Answers
Hello.I use the Region Capture to create the coloring of augmented reality. 0 Answers