Prendre une photo avec Xamarin

Ajouté par Alexandre Journaux il y a plus de 2 ans

Dans ce tuto, nous allons voir comment prendre une photo et l'afficher à l'écran.
Pour cela, on va commencer par créer, dans la vue Xaml, une balise Button et une balise Image :

<Button Text="Photo" Command="{Binding PhotoCommand}" />
<Image Source="{Binding ResultImage}" />

Dans le ViewModel, nous aurons donc deux attributs et leurs propriétés en binding avec ces 2 balises :
private ImageSource resultImage;
public ICommand PhotoCommand { get; private set; }
public ImageSource ResultImage
{
    get
    {
        return resultImage;
    }
    set
    {
        if (resultImage != value)
        {
            resultImage = value;
            OnPropertyChanged();
        }
    }
}

Dans le constructeur du ViewMdel, on instancie la commande :
PhotoCommand = new Command(Photo);

Pour finir, il ne reste plus qu'à coder la commande :
private async void Photo()
{
    try
    {
        //Création du répertoire "photos" s'il n'existe pas
        string photoPath = Path.Combine(FileSystem.AppDataDirectory, "photos");
        if (!Directory.Exists(photoPath))
        {
            Directory.CreateDirectory(photoPath);
        }
        //Création du FileStream qui contiendra la photo
        string filePhoto = Path.Combine(photoPath, "TestPhoto" + DateTime.Now.Ticks + ".jpg"); //Ceci permet d'avoir un nom unique à la photo
        FileStream fileStream = File.OpenWrite(filePhoto);

        //Lancement de l'application photo de l'apparail et attente du retour
        FileResult photo = await MediaPicker.CapturePhotoAsync();

        // Si la photo n'est pas validé par l'utilisateur => ne rien faire
        if (photo != null)
        {
            // La photo est validée => Récupération de la photo dans un stream
            Stream streamPhoto = await photo.OpenReadAsync();

            //Enregistrement dans un fichier
            await streamPhoto.CopyToAsync(fileStream);

            //Fermeture du stream
            streamPhoto.Close();

            //Affichage de la photo sur l'écran : Mise à jour de Source dans la balise Image
            this.ResultImage = ImageSource.FromFile(photo.FullPath);
        }

        //Fermeture du fileStream
        fileStream.Close();

    }
    catch (FeatureNotSupportedException fnsEx)
    {
        // Feature is not supported on the device
    }
    catch (PermissionException pEx)
    {
        // Permissions not granted
    }
    catch (Exception ex)
    {
        // Autre problème
    }
}