Reputation: 4872
C# .net9 Maui on Android. On both the phone and emulator, the MAUI Community Toolkit CameraView seems to work fine for viewing as I can see the preview, but when I attempt to take a photo I get an empty (but valid) PNG image - with no errors.
How do I take a photo and get the bytes?
XAML
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Color="Transparent">
<Border Stroke="Gray" StrokeThickness="2" Padding="20"
StrokeShape="RoundRectangle 15" BackgroundColor="white">
<VerticalStackLayout Spacing="15" WidthRequest="350" HorizontalOptions="Fill">
<toolkit:CameraView x:Name="Camera"
BackgroundColor="Transparent"
VerticalOptions="Fill"
HorizontalOptions="Fill"/>
<HorizontalStackLayout Spacing="10" HorizontalOptions="Center">
<Button Text="Capture" BackgroundColor="Green" TextColor="White" Clicked="OnCaptureClicked"/>
<Button Text="Cancel" BackgroundColor="Red" TextColor="White" Clicked="OnCancelClicked"/>
</HorizontalStackLayout>
</VerticalStackLayout>
</Border>
</toolkit:Popup>
CS
private readonly TaskCompletionSource<byte[]?> _completionSource = new();
public CapturePhotoPopup()
{
InitializeComponent();
Closed += (object? sender, PopupClosedEventArgs e) =>
{
Camera.StopCameraPreview();
_completionSource.TrySetResult(null);
};
}
private async void OnCaptureClicked(object sender, EventArgs e)
{
var photo = await Camera.CaptureAsync();
if (photo != null)
{
using var stream = await photo.OpenReadAsync();
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
//ms.ToArray() contains a valid empty PNG image.
_completionSource?.SetResult(ms.ToArray());
}
else
{
_completionSource?.SetResult(null);
}
Close();
}
Upvotes: 1
Views: 37