- Xam.Plugin.Media
- An iOS or Android device to take the photo. This will not work on a simulator
- Provisioning for that device
-
Start a new Xamarin.Forms project
-
Download and install the Plugin.Media NuGet package
-
Inside of the shared project, add a button and image:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:testcamapp" x:Class="testcamapp.testcamappPage">
<StackLayout>
<Button x:Name="TakePicture_button" Clicked="TakePictureButton_Clicked" Text="TakePicture_button"/>
<Image x:Name="image" HeightRequest="340" />
</StackLayout>
</ContentPage>
- In the .cs page for that XAML, add the event handler to take a photo:
// Can access all images, to display them on screen at once
public List<Plugin.Media.Abstractions.MediaFile> imagesList = new List<Plugin.Media.Abstractions.MediaFile>();
async void TakePictureButton_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (CrossMedia.Current.IsCameraAvailable && CrossMedia.Current.IsTakePhotoSupported)
{
// Supply media options for saving our photo after it's taken.
var mediaOptions = new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Images",
Name = $"{DateTime.UtcNow}.jpg"
};
// Take a photo
var file = await CrossMedia.Current.TakePhotoAsync(mediaOptions);
if (file == null) { return; }
// Notify user that file is being saved and where it is located.
// Display image on screen.
await DisplayAlert("File Location", file.Path, "OK");
image.Source = ImageSource.FromStream(() =>
{
imagesList.Add(file);
var stream = file.GetStream();
file.Dispose();
Debug.WriteLine("New image: " + imagesList);
return stream;
});
}
else if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
DisplayAlert("no cam", "Camera not available", "OK");
return;
}
}
-
In the same page, add the using statement: using Plugin.Media;
-
Deploy to device
There's always something, right?
On UWP (Win 10), you must initialize the camera first, otherwise it may take up to 1 minute for the camera to load, and it appears the application froze.
That's why I have this line of code:
await CrossMedia.Current.Initialize();
I discovered the solution at this bug report from Xamarin.