Awesome
MediaGallery for .NET Android and iOS
This plugin is designed for picking and saving photos and video files from the native gallery of Android and iOS devices and capture photo.
FAQ
Please read this file and see samples before creating an issue.
Q: Why does the plugin not support Xamarin?
A: Yes, it's funny. Initially, I made this plugin as a temporary solution to expand the functionality of Xamarin.Essentials. Xamarin is no longer supported by Microsoft and MAUI still has scant functionality for working with media files. For these reasons, this plugin will continue to exist and support .NET for iOS and Android.
Q: Why does a image have wrong orientation?
A: This is correct behavior. The plugin returns images without any changes, See metadata
Q: How do I get FilePath
?
A: It is not possible. But you can copy a file to a cache directory
Q: How does Xamarin.MediaGallery work on a PopupPage?
A: Fine! But you need to initialize the plugin on iOS. See taht sample code
Q: Why an error thrown when picking a image on a iOS simulator?
A: This issue is on Apple side
Available Platforms
Platform | Minimum OS Version |
---|---|
Android | 5.0 |
iOS | 13.6 |
TargetFrameworks
net8.0-ios
net8.0-android
Getting started
You can just watch the Video that @jfversluis published
Android
In the Android project's MainLauncher or any Activity that is launched, this plugin must be initialized in the OnCreate method:
protected override void OnCreate(Bundle savedInstanceState)
{
//...
base.OnCreate(savedInstanceState);
NativeMedia.Platform.Init(this, savedInstanceState);
//...
}
iOS (Optional)
In the iOS project's AppDelegate that is launched, this plugin can be initialized in the FinishedLaunching method:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
NativeMedia.Platform.Init(GetTopViewController);
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
public UIViewController GetTopViewController()
{
var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
if (vc is UINavigationController navController)
vc = navController.ViewControllers.Last();
return vc;
}
PickAsync
This method does not require requesting permissions from users
var cts = new CancellationTokenSource();
IMediaFile[] files = null;
try
{
var request = new MediaPickRequest(1, MediaFileType.Image, MediaFileType.Video)
{
PresentationSourceBounds = System.Drawing.Rectangle.Empty,
Title = "Select"
};
cts.CancelAfter(TimeSpan.FromMinutes(5));
var results = await MediaGallery.PickAsync(request, cts.Token);
files = results?.Files?.ToArray();
}
catch (OperationCanceledException)
{
// handling a cancellation request
}
catch (Exception)
{
// handling other exceptions
}
finally
{
cts.Dispose();
}
if (files == null)
return;
foreach (var file in files)
{
var fileName = file.NameWithoutExtension; //Can return an null or empty value
var extension = file.Extension;
var contentType = file.ContentType;
using var stream = await file.OpenReadAsync();
//...
file.Dispose();
}
This method has two overloads:
Task<MediaPickResult> PickAsync(int selectionLimit = 1, params MediaFileType[] types)
Task<MediaPickResult> PickAsync(MediaPickRequest request, CancellationToken token = default)
Android
To handle runtime results on Android, this plugin must receive any OnActivityResult
.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
if (NativeMedia.Platform.CheckCanProcessResult(requestCode, resultCode, intent))
NativeMedia.Platform.OnActivityResult(requestCode, resultCode, intent);
base.OnActivityResult(requestCode, resultCode, intent);
}
If an app has android:targetSdkVersion="33"
or greater new Photo picker will be used if possible.
Default behavior
- When using
PickAsync
methodselectionLimit
parameter just sets multiple pick allowed - A request to cancel
PickAsync
method will cancel a task, but the picker UI can remain open until it is closed by the user - The use of
Title
property depends on each device
Photo Picker behavior
selectionLimit
parameter limits the number of selected media filesTitle
property not used
iOS
- Multi picking is supported since iOS version 14.0+ On older versions, the plugin will prompt the user to select a single file
- The
NameWithoutExtension
property on iOS versions before 14 returns a null value if the permission to access photos was not granted Title
property not used
Presentation Location
When picking files on iPadOS you have the ability to present in a pop over control. This specifies where the pop over will appear and point an arrow directly to. You can specify the location using the PresentationSourceBounds
property. Setting this property has the same behavior as Launcher or Share in Xamarin.Essentials.
PresentationSourceBounds
property takes System.Drawing.Rectangle
for Xamarin
or Microsoft.Maui.Graphics.Rect
for .net6(MAUI)
Screenshots:
Сapture Photo with Metadata
//...
if (!MediaGallery.CheckCapturePhotoSupport())
return;
var status = await Permissions.RequestAsync<Permissions.Camera>();
if (status != PermissionStatus.Granted)
return;
using var file = await MediaGallery.CapturePhotoAsync()
NameWithoutExtension
will always return $"IMG_{DateTime.Now:yyyyMMdd_HHmmss}"
value.
Android
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
If Camera is not required in your application, you can specify false
.
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
iOS
In your Info.plist
add the following keys:
<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>
SaveAsync
//...
var status = await Permissions.RequestAsync<SaveMediaPermission>();
if (status != PermissionStatus.Granted)
return;
await MediaGallery.SaveAsync(MediaFileType.Video, filePath);
//OR Using a byte array or a stream
await MediaGallery.SaveAsync(MediaFileType.Image, stream, fileName);
//The name or the path to the saved file must contain the extension.
//...
Permission
Add Xamarin.MediaGallery.Permision
or Xamarin.MediaGallery.Permision.Maui
nuget package to use the SaveMediaPermission
Android
Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.
<!-- for saving photo/video -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- When saving media files, the date and time are appended to the file name
iOS
In your Info.plist
add the following keys:
<!-- for saving photo/video on iOS 14+ -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs access to the photo gallery for saving photos and videos</string>
<!-- for saving photo/video on older versions -->
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to the photo gallery for saving photos and videos</string>
Screenshots
iOS | Android - Defult | Android - Photo Picker |
---|---|---|