Home

Awesome

MediaGallery for .NET Android and iOS

header

NuGet Badge NuGet downloads license Xamarin.MediaGallery on fuget.org YouTube Video Views

This plugin is designed for picking and saving photos and video files from the native gallery of Android and iOS devices and capture photo.

"Buy Me A Coffee"

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

PlatformMinimum OS Version
Android5.0
iOS13.6

TargetFrameworks

Getting started

You can just watch the Video that @jfversluis published

Migration to 3.X.X version

Migration to 2.X.X version

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:

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

Photo Picker behavior

iOS

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" />

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

iOSAndroid - DefultAndroid - Photo Picker
iOSAndroidAndroid2