Forum Xamarin.Android

Camera access in Android nougat

Could you please share the sample code to access the camera and take camera pic and save to a location in xamarin Android nougat cross platform application?

Answers

  • BillyLiuBillyLiu Member, Xamarin Team Xamurai

    You could use a intent with MediaStore.ActionImageCapture action to take photo and save it.

    For example:
    In app class:

       public partial class App : Application
       {
    
       public static App Instance;
    
       readonly Image image = new Image();
    
        public App()
        {
            Instance = this;
    
            var button = new Button
    
            {
                Text = "Snap!",
                Command = new Command(o => ShouldTakePicture()),
            };
    
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                    button,
                    image,
                    },
                },
            };
        }
        public event Action ShouldTakePicture = () => { };
    
        public void ShowImage(string filepath)
        {
            image.Source = ImageSource.FromFile(filepath);
        }
    }
    

    In MainActivity:

       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
           {
        static readonly File file = new File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), "tmp.jpg");
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
    
            base.OnCreate(bundle);
    
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
    
            App.Instance.ShouldTakePicture += () => {
                var intent = new Intent(MediaStore.ActionImageCapture);
                intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(file));
                StartActivityForResult(intent, 0);
            };
    
        }
    
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            App.Instance.ShowImage(file.Path);
        }
    }
    

    And you this post in Stack Overflow:
    stackoverflow.com/questions/28207571/camera-access-with-xamarin-forms

  • When I make instance of File in MainActivity in Android, there is a problem saying Cannot create instance of File static class. Is there any solution for this?

Sign In or Register to comment.