• This repository has been archived on 05/Jul/2024
  • Stars
    star
    713
  • Rank 63,511 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created over 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Take & Pick Photos and Video Plugin for Xamarin and Windows

Update Novemeber 2020

Xamarin.Essentials 1.6 introduced official support for picking/taking photos and videos with the new Media Picker API.

This library has a lot of legacy code that is extremely hard to maintain and update to support the latest OSes without a major re-write. I will officially be archiving this library in December 2020 unless anyone from the community wants to adopt the project.

Media Plugin for Xamarin and Windows

Simple cross platform plugin to take photos and video or pick them from a gallery from shared code.

Please read through all of the setup directions below: https://github.com/jamesmontemagno/MediaPlugin#important-permission-information

Ported from Xamarin.Mobile to a cross platform API.

Setup

Build Status:

Platform Support

Platform Version
Xamarin.iOS iOS 7+
Xamarin.Android API 14+
Windows 10 UWP 10+
.NET for iOS iOS 10+
.NET for Android API 21+
Windows App SDK (WinUI3) 10+
.NET for Mac Catalyst All
Tizen 4+

API Usage

Call CrossMedia.Current from any project or PCL to gain access to APIs.

Before taking photos or videos you should check to see if a camera exists and if photos and videos are supported on the device. There are five properties that you can check:

/// <summary>
/// Initialize all camera components, must be called before checking properties below
/// </summary>
/// <returns>If success</returns>
Task<bool> Initialize();

/// <summary>
/// Gets if a camera is available on the device
/// </summary>
bool IsCameraAvailable { get; }

/// <summary>
/// Gets if ability to take photos supported on the device
/// </summary>
bool IsTakePhotoSupported { get; }

/// <summary>
/// Gets if the ability to pick photo is supported on the device
/// </summary>
bool IsPickPhotoSupported { get; }

/// <summary>
/// Gets if ability to take video is supported on the device
/// </summary>
bool IsTakeVideoSupported { get; }

/// <summary>
/// Gets if the ability to pick a video is supported on the device
/// </summary>
bool IsPickVideoSupported { get; }

Photos

/// <summary>
/// Picks a photo from the default gallery
/// </summary>
/// <param name="options">Pick Photo Media Options</param>
/// <returns>Media file or null if canceled</returns>
Task<MediaFile> PickPhotoAsync(PickMediaOptions options = null);

/// <summary>
/// Take a photo async with specified options
/// </summary>
/// <param name="options">Camera Media Options</param>
/// <returns>Media file of photo or null if canceled</returns>
Task<MediaFile> TakePhotoAsync(StoreCameraMediaOptions options);

Videos

/// <summary>
/// Picks a video from the default gallery
/// </summary>
/// <returns>Media file of video or null if canceled</returns>
Task<MediaFile> PickVideoAsync();

/// <summary>
/// Take a video with specified options
/// </summary>
/// <param name="options">Video Media Options</param>
/// <returns>Media file of new video or null if canceled</returns>
Task<MediaFile> TakeVideoAsync(StoreVideoOptions options);

Usage

Via a Xamarin.Forms project with a Button and Image to take a photo:

takePhoto.Clicked += async (sender, args) =>
{
    await CrossMedia.Current.Initialize();
    
    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
        DisplayAlert("No Camera", ":( No camera available.", "OK");
        return;
    }

    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
        Directory = "Sample",
        Name = "test.jpg"
    });

    if (file == null)
        return;

    await DisplayAlert("File Location", file.Path, "OK");

    image.Source = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        return stream;
    }); 
};

To see more examples of usage without Xamarin.Forms open up the test folder in this project.

Directories and File Names

Setting these properties are optional. Any illegal characters will be removed and if the name of the file is a duplicate then a number will be appended to the end. The default implementation is to specify a unique time code to each value.

Photo & Video Settings

Compressing Photos

When calling TakePhotoAsync or PickPhotoAsync you can specify multiple options to reduce the size and quality of the photo that is taken or picked. These are applied to the StoreCameraMediaOptions and PickMediaOptions.

Resize Photo Size

By default the photo that is taken/picked is the maxiumum size and quality available. For most applications this is not needed and can be Resized. This can be accomplished by adjusting the PhotoSize property on the options. The easiest is to adjust it to Small, Medium, or Large, which is 25%, 50%, or 75% or the original. This is only supported in Android & iOS. On UWP there is a different scale that is used based on these numbers to the respected resolutions UWP supports.

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    PhotoSize = PhotoSize.Medium,
});

Or you can set to a custom percentage:

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    PhotoSize = PhotoSize.Custom,
    CustomPhotoSize = 90 //Resize to 90% of original
});

Photo Quality

Set the CompressionQuality, which is a value from 0 the most compressed all the way to 100, which is no compression. A good setting from testing is around 92. This is only supported in Android & iOS

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    CompressionQuality = 92
});

Saving Photo/Video to Camera Roll/Gallery

You can now save a photo or video to the camera roll/gallery. When creating the StoreCameraMediaOptions or StoreVideoMediaOptions simply set SaveToAlbum to true. When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery (based on platform). In the MediaFile you will now see a AlbumPath that you can query as well.

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    SaveToAlbum = true
});

//Get the public album path
var aPpath = file.AlbumPath; 

//Get private path
var path = file.Path;

This will restult in 2 photos being saved for the photo. One in your private folder and one in a public directory that is shown. The value will be returned at AlbumPath.

Android: When you set SaveToAlbum this will make it so your photos are public in the Pictures/YourDirectory or Movies/YourDirectory. This is the only way Android can detect the photos.

Allow Cropping

Both iOS and UWP have crop controls built into the the camera control when taking a photo. On iOS the default is false and UWP the default is true. You can adjust the AllowCropping property when taking a photo to allow your user to crop.

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    AllowCropping = true
});

Default Camera

By default when you take a photo or video the default system camera will be selected. Simply set the DefaultCamera on StoreCameraMediaOptions. This option does not guarantee that the actual camera will be selected because each platform is different. It seems to work extremely well on iOS, but not so much on Android. Your mileage may vary.

var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Front
});

Take Photo Overlay (iOS Only)

On iOS you are able to specify an overlay on top of the camera. It will show up on the live camera and on the final preview, but it is not saved as part of the photo, which means it is not a filter.

//Load an image as an overlay (this is in the iOS Project)
Func<object> func = () =>
{
    var imageView = new UIImageView(UIImage.FromBundle("face-template.png"));
    imageView.ContentMode = UIViewContentMode.ScaleAspectFit;

    var screen = UIScreen.MainScreen.Bounds;
    imageView.Frame = screen;

    return imageView;
};

//Take Photo, could be in iOS Project, or in shared code where there function is passed up via Dependency Services.
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
    OverlayViewProvider = func
});

Important Permission Information

Please read these as they must be implemented for all platforms.

Android

The WRITE_EXTERNAL_STORAGE & READ_EXTERNAL_STORAGE permissions are required, but the library will automatically add this for you. Additionally, if your users are running Marshmallow the Plugin will automatically prompt them for runtime permissions. You must add Xamarin.Essentials.Platform.OnRequestPermissionsResult code into your Main or Base Activities:

Add to Activity:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

Android Required Setup

This plugin uses the Xamarin.Essentials, please follow the setup guide: http://aka.ms/essentials-getstarted

Android File Provider Setup

You must also add a few additional configuration files to adhere to the new strict mode:

1a.) (Non AndroidX) Add the following to your AndroidManifest.xml inside the <application> tags:

<provider android:name="android.support.v4.content.FileProvider" 
          android:authorities="${applicationId}.fileprovider" 
          android:exported="false" 
          android:grantUriPermissions="true">
          
	  <meta-data android:name="android.support.FILE_PROVIDER_PATHS" 
                     android:resource="@xml/file_paths"></meta-data>
</provider>

Note: If you receive the following error, it is because you are using AndroidX. To resolve this error, follow the instructions in Step 1b.).

Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList

1b.) (AndroidX) Add the following to your AndroidManifest.xml inside the <application> tags:

<provider android:name="androidx.core.content.FileProvider" 
          android:authorities="${applicationId}.fileprovider" 
          android:exported="false" 
          android:grantUriPermissions="true">
          
	  <meta-data android:name="android.support.FILE_PROVIDER_PATHS" 
                     android:resource="@xml/file_paths"></meta-data>
</provider>

2.) Add a new folder called xml into your Resources folder and add a new XML file called file_paths.xml. Make sure that this XML file has a Build Action of: AndroidResource.

Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="my_images" path="Pictures" />
    <external-files-path name="my_movies" path="Movies" />
</paths>

You can read more at: https://developer.android.com/training/camera/photobasics.html

Android Optional Setup

By default, the library adds android.hardware.camera and android.hardware.camera.autofocus to your apps manifest as optional features. It is your responsbility to check whether your device supports the hardware before using it. If instead you'd like Google Play to filter out devices without the required hardware, add the following to your AssemblyInfo.cs file in your Android project:

[assembly: UsesFeature("android.hardware.camera", Required = true)]
[assembly: UsesFeature("android.hardware.camera.autofocus", Required = true)]

iOS

Your app is required to have keys in your Info.plist for NSCameraUsageDescription and NSPhotoLibraryUsageDescription in order to access the device's camera and photo/video library. If you are using the Video capabilities of the library then you must also add NSMicrophoneUsageDescription. If you want to "SaveToGallery" then you must add the NSPhotoLibraryAddUsageDescription key into your info.plist. The string that you provide for each of these keys will be displayed to the user when they are prompted to provide permission to access these device features. You can read me here: New iOS 10 Privacy Permission Settings

Such as:

<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs access to microphone.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs access to the photo gallery.</string>

If you want the dialogs to be translated you must support the specific languages in your app. Read the iOS Localization Guide

UWP

Set Webcam permission.

Permission Recommendations

By default, the Media Plugin will attempt to request multiple permissions, but each platform handles this a bit differently, such as iOS which will only pop up permissions once.

You can use Xamarin.Essentials to request and check permissions manually.

FAQ

Here are some common answers to questions:

On iOS how do I translate the text on the buttons on the camera?

You need CFBundleLocalizations in your Info.plist.

License

Licensed under MIT, see license file. This is a derivative to Xamarin.Mobile's Media with a cross platform API and other enhancements.

//
//  Copyright 2011-2013, Xamarin Inc.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

Want To Support This Project?

All I have ever asked is to be active by submitting bugs, features, and sending those pull requests down! Want to go further? Make sure to subscribe to my weekly development podcast Merge Conflict, where I talk all about awesome Xamarin goodies and you can optionally support the show by becoming a supporter on Patreon.

More Repositories

1

Xamarin.Plugins

Cross-platform Native API Access from Shared Code!
1,302
star
2

mvvm-helpers

Collection of MVVM helper classes for any application
C#
673
star
3

Hanselman.Forms

The most awesome Hanselman app
C#
671
star
4

InAppBillingPlugin

Cross-platform In App Billing Plugin for .NET
C#
630
star
5

monkey-cache

Easily cache any data structure for a specific amount of time in any .NET application.
C#
629
star
6

SettingsPlugin

Read and Write Settings Plugin for Xamarin and Windows
C#
325
star
7

GeolocatorPlugin

Geolocation plugin for Xamarin and Windows
C#
293
star
8

PermissionsPlugin

Check and Request Permissions Plugin for Xamarin and Windows
C#
282
star
9

ConnectivityPlugin

Connectivity Plugin for Xamarin and Windows
C#
262
star
10

ImageCirclePlugin

Circle Images for your Xamarin.Forms Applications
C#
240
star
11

Xamarin.Forms-PullToRefreshLayout

Pull To Refresh a ScrollView or ListView in Xamarin.Forms
C#
222
star
12

StoreReviewPlugin

Request app store reviews across Xamarin and Windows applications
C#
183
star
13

MyCoffeeApp

Sample Xamarin.Forms app built live on in 101 series on YouTube
C#
153
star
14

MeetupManager

Meetup.com app to track users at events
C#
149
star
15

DeviceInfoPlugin

Device Information Plugin for Xamarin and Windows
C#
143
star
16

app-ac-islandtracker

Animal Crossing Island Tracking Mobile App
C#
135
star
17

Xamarin-Templates

Xamarin.Android Templates Pack
C#
130
star
18

xamarin.forms-toolkit

Toolkit for Xamarin.Forms (Controls, Behaviors, and Converters)
C#
128
star
19

Xam.NavDrawer

Navigation Drawer Sample + MvvmCross Sample for Xamarin.Android
C#
123
star
20

Xamarin.Forms-Awesome-Controls

Awesome controls to add to your Xamarin.Forms apps
C#
121
star
21

XamChat

SignalR Chat Xamarin App
C#
120
star
22

CurrentActivityPlugin

Always grab the current Activity of your Xamarin.Android app!
C#
115
star
23

Xamarin.Forms-Monkeys

Simple list of monkeys (master/detail) in a xamarin.forms application
C#
115
star
24

MyWeather.Forms

Xamarin.Forms Weather Demo using OpenWeatherMap
C#
110
star
25

app-monkeychat

Monkey Chat application feature Twilio IP Messaging
C#
109
star
26

MyStreamTimer

A cool app to count up or down that writes text to file for streamers
C#
99
star
27

FloatingActionButton-for-Xamarin.Android

FAB material design for Xamarin.Android
C#
91
star
28

PagerSlidingTabStrip-for-Xamarin.Android

Port of Pager Sliding Tab Strip for Xamarin.Android Material Design
C#
85
star
29

app-coffeecups

Coffee Consumption App built with Xamarin.Forms and Azure Mobile Apps
C#
82
star
30

vsts-mobile-tasks

VSTS Tasks for Mobile!
TypeScript
79
star
31

MonoDroidToolkit

A toolkit for Xamarin.Android providing a lot of awesome helpers
C#
71
star
32

TextToSpeechPlugin

Text to Speech Plugin for Xamarin and Windows
C#
62
star
33

MotzCodesLive

Sample Resources for Motz Codes Live on Twitch
C#
60
star
34

AndroidStreamingAudio

Sample of streaming audio in background service in Xamarin.Android
C#
57
star
35

MyExpenses

My Expenses Cross Platform Demo - VSToolBox
C#
54
star
36

app-pretty-weather

A very pretty weather application built with Xamarin :)
C#
54
star
37

app-essentials

Sample project highlighting Xamarin.Essentials
C#
53
star
38

AllExtensions-DI-IoC

C#
52
star
39

xamarin.forms-workshop

Xamarin.Forms Full Day Workshop
C#
49
star
40

LaunchMapsPlugin

Launch External Maps Plugin for Xamarin and Windows
C#
48
star
41

MauiApp-DI

C#
46
star
42

VibratePlugin

Vibrate Plugin for Windows and Xamarin
C#
45
star
43

TheXamarinShow

All source code from my show on Channel 9, The Xamarin Show!
C#
45
star
44

app-imagesearch-cogs

Image Search and Cognitive Service Xamarin app!
C#
45
star
45

MVVMSourceGenerators

C#
44
star
46

Coffee-Filter

Find Coffee Fast with this Xamarin.Android App
C#
43
star
47

VS2019-FirstXamarinApp

C#
40
star
48

app-myconference

Conference App Build with .NET MAUI
C#
40
star
49

BikeNow

Bike Now is the best way to enjoy Seattle's bike sharing system on Android
C#
39
star
50

MonkeysApp-Workshop

Xamarn.Forms Workshop sample monkey app for iOS, Android, and Windows
C#
39
star
51

Censored

A .NET Profanity Censoring Library
C#
38
star
52

work-from-home-setup

Equipment and Setup recommended for Work From Home
37
star
53

app-peloton

Peloton app clone built with Xamarin.Forms
C#
35
star
54

dotnet-conferences

A comprehensive community built list of .NET Conferences around the world!
34
star
55

app-compass

Creating a simple compass application with Xamarin.Forms and Xamarin.Essentials.
C#
32
star
56

CircleImageView-Xamarin.Android

A fast circle image for Xamarin.Android
C#
32
star
57

Xamarin.Forms-PullToRefreshListView

Implementation of pull to refresh for Xamarin.Forms ListView
C#
31
star
58

Mvx.Plugins.Settings

Settings plug-in for MvvmCross.
C#
30
star
59

app-SimpleSignalR

Xamarin app to listen to new items from SignalR and ASP.NET Core
C#
30
star
60

mycadence-arduino

With this DIY project and a simple $18 ESP32 Arduino board you will have a budget Cadence display for your indoor cycling bike for Peloton or Apple Fitness+
C++
29
star
61

PlanetXamarin

Planet Xamarin
C#
28
star
62

BatteryPlugin

Battery Plugin for Xamarin and Windows
C#
27
star
63

iBeaconsEverywhere

iBeacon example on iOS and Android
C#
26
star
64

app-monkeys

C#
25
star
65

LocalizationSample

C#
25
star
66

GifImageView-Xamarin.Android

Animated ImageView for your Xamarin.Android apps
C#
25
star
67

ContactsPlugin

Contacts Plugin For Xamarin and Windows
C#
24
star
68

plugin-template

Plugin for .NET Template
C#
23
star
69

xamarin-workshop

Xamarin workshops for building a Xamarin.Android and Xamarin.Forms App
C#
19
star
70

app-ocr-functions

Cognitive Services, Azure Functions, Azure Mobile Apps, and Xamarin
C#
19
star
71

MyStocks.Forms

Xamarin.Forms example of querying stock quotes and using text to speech apis.
C#
18
star
72

AirQualityApps

C#
18
star
73

Xamarin.Forms-Android-CustomProgressBar

Using a custom renderer to display and bind to my custom progress bar
C#
18
star
74

build2017-future-of-mobile

Live Player Demos from Future of Mobile at Build 2017
C#
18
star
75

XamDroid.StickyListHeaders

Xamarin.Android Port of StickyListHeaders
C#
17
star
76

FiveLetters

A clone of a clone of Wordle built with .NET MAUI
C#
17
star
77

BetterTogether

Blazor, ASP.NET Core, Xamarin, .NET Standard <3
C#
16
star
78

XamarinDNR

Dot Net Rocks, PCL, Azure!
C#
16
star
79

FrenchPressTimer

Cross Platform timer that counts down from 4 minutes
C#
16
star
80

forms-native-embedding

Xamarin.Forms Native Embedding Sample
C#
16
star
81

embeddinator-weather

C#
15
star
82

Covid19Stats

Desktop app to retrieve COVID-19 Stats and download them to files on disk for OBS/SLOBS with a timer :)
C#
14
star
83

PuppyKittyOverflow

PuppyKittyOverflow
C#
14
star
84

Jeffsum.NET

Jeff Goldblum text placeholder generator of pure amazingness. (Unofficial .NET version of Jeffsum.com by @seanehalpin)
C#
13
star
85

MyFirstOouiApp

C#
13
star
86

MarshmallowSamples

Get ready for Android 6.0 with these Marshmallow Samples
C#
13
star
87

Xamarin.Android-AppCompat

App compat for android
C#
13
star
88

ToolkitMessenger

Esample of .NET Toolkit Messenger
C#
13
star
89

build2021-intro-csharp-python

C# and Python are two of the most popular programming languages for developers in all areas of tech. From making web apps to doing machine learning, you can't go wrong with either of them! James and Christopher are here to introduce you to these two powerful languages, explore some โ€œHello, Worldโ€ examples, and show you the docs, tools, and frameworks that can help students and beginners get started on coding today!
Jupyter Notebook
13
star
90

blog-samples

All code samples from http://motzcod.es and http://blog.xamarin.com
C#
12
star
91

jamesmontemagno

12
star
92

XamDroid.RobotoText

Roboto text everywhere!
C#
12
star
93

dotnet-maui-template

Default template idea for .NET MAUI
C#
12
star
94

app-tictactoe

A Xamarin.Forms Tic-Tac-Toe example
C#
12
star
95

embeddinator-hellosharedui

C#
11
star
96

OfficeLightControl

Workshop for building an office light switch app with IFTTT and Hues
C#
11
star
97

FormsAnimations

Sample application shown during the Xamarin.Forms webinar for animations.
C#
11
star
98

MonkeyFinder6000

C#
10
star
99

app-simplestocks

C#
10
star
100

MonkeyApi

C#
10
star