hjam40 / Camera.MAUI

A CameraView Control for preview, take photos and control the camera options
MIT License
449 stars 72 forks source link

`NullReferenceException` inside `cameraView.TakePhotoAsync` #170

Open ITaluone opened 1 month ago

ITaluone commented 1 month ago

Hi

We have an issue with this to take a photo, because it is throwing an NRE somewhere inside this method, but I cannot tell where exactly.

Platform: Android Framework: .NET8.0

This is our code in question:

private async Task<Stream> TakePhotoAsync()
{
    // ... pre-checks 

    var photoResult = await cameraView.TakePhotoAsync(Camera.MAUI.ImageFormat.PNG);

    if (photoResult == null)
    {
        Debug.WriteLine("Error: photoResult is null.");
        return null;
    }

    var stream = new MemoryStream();
    await photoResult.CopyToAsync(stream);
    stream.Position = 0;
    return stream;
}

I cannot give more information, unfortunately, because of lack of stack trace and such.

Can you give me a hint what this causes?

Edit:

The stack trace looks like this (not terribly helpful IMHO):

at Camera.MAUI.Platforms.Android.MauiCameraView.TakePhotoAsync(ImageFormat imageFormat)
at Camera.MAUI.CameraView.TakePhotoAsync(ImageFormat imageFormat)
at MyApp.MainPage.TakePhotoAsync() in MainPage.xaml.cs:line 211

If the cameraView.Camera from above is loaded with cameraView.Cameras.First() (meaning the back camera) this NRE occurs, but when loading the front camera cameraView.Cameras.Last() this works fine, but showing the back camera stream in the cameraView.

luresti commented 1 month ago

i suggest you select the camera using next code to assure to use the correct position camera

for (int i = 0; i < cameraView.Cameras.Count; i++) { if (cameraView.Cameras[i].Position == Camera.MAUI.CameraPosition.Front) {

    cameraView.Camera = cameraView.Cameras[i];
    break;
}

}

ITaluone commented 1 month ago

Ahm.. I only have two cameras back and front. I want to select the back camera (which is the first one) but when I select it, it crashes.

Edit: This makes no difference at all..

luresti commented 1 month ago

change CameraPosition.Front to CameraPosition.Back