Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Take a photo with CrossMedia.Current.TakePhotoAsync

EnricoRossiniEnricoRossini USMember ✭✭✭✭

Hi guys,
I'm creating a project where I have to take a lot of pictures. In my previous project on iOS all are working fine. I'm using the same code for a new project for all platforms.

When I take a photo on Android the stream is empty.

        var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions());
        
        if (file == null)
            return;

        byte[] imageAsBytes = null;
        using (var memoryStream = new MemoryStream()) {
            file.GetStream().CopyTo(memoryStream);
            file.Dispose();
            imageAsBytes = memoryStream.ToArray();
        }

Any ideas?
Thank you in advance

Answers

  • LannyDeVaneyLannyDeVaney USMember ✭✭

    I've had this issue before and I had to add a check for camera before I tried to take the photo. Don't know why, but I assume that call initializes something. I just add something like the following block around your code:

    if (CrossMedia.Current.IsCameraAvailable && CrossMedia.Current.IsTakePhotoSupported)
    {
    ...
    }

  • EnricoRossiniEnricoRossini USMember ✭✭✭✭

    Hi @LannyDeVaney
    Thank you for your idea. Tomorrow I'll try (today I'm on holiday :))

  • EnricoRossiniEnricoRossini USMember ✭✭✭✭

    HI @LannyDeVaney I'm calling

        /// <summary>
        /// Initializes the media.
        /// </summary>
        private async void InitMedia() {
            await CrossMedia.Current.Initialize();
        }
    

    before that method. I have a MVVM model and the code is like that

        /// <summary>
        /// Gets the camera command.
        /// </summary>
        /// <value>The camera command.</value>
        public ICommand CameraCommand
        {
            get { return _cameraCommand ?? new Command(async () => await ExecuteCameraCommand(), () => CanExecuteCameraCommand()); }
        }
    
        /// <summary>
        /// Determines whether this instance can execute camera command.
        /// </summary>
        /// <returns><c>true</c> if this instance can execute camera command; otherwise, <c>false</c>.</returns>
        public bool CanExecuteCameraCommand() {
            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) {
                return false;
            }
            return true;
        }
    
        /// <summary>
        /// Executes the camera command.
        /// </summary>
        /// <returns>The camera command.</returns>
        public async Task ExecuteCameraCommand() {
            InitMedia();
            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions());
    
            if (file == null)
                return;
    
            byte[] imageAsBytes = null;
            using (var memoryStream = new MemoryStream()) {
                file.GetStream().CopyTo(memoryStream);
                file.Dispose();
                imageAsBytes = memoryStream.ToArray();
            }
    
            if (imageAsBytes.Length > 0) {
                var resizer = DependencyService.Get<IImageResize>();
                imageAsBytes = resizer.ResizeImage(imageAsBytes, 1080, 1080);
    
                var imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
                _images.Add(new GalleryImage { Source = imageSource, OrgImage = imageAsBytes });
                OnPropertyChanged("Images");
            }
        }
    
  • AmjadAli.0364AmjadAli.0364 USMember ✭✭

    Hi use this code, hope it will help

    try
    {
    await CrossMedia.Current.Initialize();
    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
    await DisplayAlert("No Camera ", "No camera available. ", "OK");
    return;
    }

                file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    SaveToAlbum = true,
                    Name = "IMG.jpg"
                });
                if (file == null)
                    return;
    
                // image set to your image view====
                imageforUpload.Source = ImageSource.FromStream(() => file.GetStream());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error  == ", ex.Message);
            }
    
  • Is there any solutions that we can check that captured image comes from front camera or rear camera?

  • alexdieteralexdieter Member

    DiptejThakkar ... please ... I need your help ... look my code

    using Plugin.Media;
    using Plugin.Media.Abstractions;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Xamarin.Forms;
    namespace CameraVW
    {
    public partial class MainPage : ContentPage
    {
    public MainPage()
    {
    InitializeComponent();

            btnCamera.Clicked += async (sender, args) =>
            {
                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await DisplayAlert("No Camera", ":( No camera available.", "OK");
                    return;
                }
    
                var armazenamento = new StoreCameraMediaOptions()
                {
                    SaveToAlbum = true,
                    Name = "MinhaFoto.jpg"
                };
    
                var foto = await CrossMedia.Current.TakePhotoAsync(armazenamento);
    
                if (foto == null)
                    return;
    
                imgFoto.Source = ImageSource.FromStream(() =>
                {
                    var stream = foto.GetStream();
                    foto.Dispose();
                    return stream;
                });                              
            };
    
        }
    }
    

    }

    and my AndroidManifes.xml

    <?xml version="1.0" encoding="utf-8"?>




















    </application>
    

    but I have the same message every time ... when Run ... await CrossMedia.Current.TakePhotoAsync(armazenamento);

    System.ArgumentException: 'Unable to get file location. This most likely means that the file provider information is not set in your Android Manifest file. Please check documentation on how to set this up in your project.'

    Thank you ...

  • alexdieteralexdieter Member

    I simplified my Manifest to this

    <?xml version="1.0" encoding="utf-8"?>









    and this is my file_paths.xml





Sign In or Register to comment.