jerome
jerome

Reputation: 145

How to Display Camera Preview in .NET MAUI?

I accessed the camera and used it to take a picture, but this isn't exactly what I want to accomplish.

I want to activate and display front camera preview on my content page, and then take a picture by pressing a button control.

I've searched around and I can't seem to find any solution. In Xamarin, there's CameraView from Xamarin Community Toolkit that can be used for camera stream, but from the looks of it, CameraView hasn't been implemented in .NET MAUI Community Toolkit. Is there any other way to do this?

Upvotes: 7

Views: 5454

Answers (1)

Althea
Althea

Reputation: 1

This is the code for the button event

private async void takephoto(object sender, EventArgs e)
    {
        if (MediaPicker.Default.IsCaptureSupported)
        {
            FileResult photo = await MediaPicker.Default.CapturePhotoAsync();

            if (photo != null)
            {
                // save the file into local storage
                string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

                using Stream sourceStream = await photo.OpenReadAsync();
                Stream stream = await photo.OpenReadAsync();
                using FileStream localFileStream = File.OpenWrite(localFilePath);

                await sourceStream.CopyToAsync(localFileStream);

                DisplayPhoto.Source = ImageSource.FromStream(() =>
                {
                    return stream;
                });
            }
        }
    }

Upvotes: -2

Related Questions