public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            buttonLocation.TouchUpInside += (sender, e) => {
                var locator = new Geolocator { DesiredAccuracy = 50 };
                locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
                    var text = String.Format("Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude);
                    InvokeOnMainThread(() => LabelLocation.Text = text);
                });
            };

            buttonPicture.TouchUpInside += (sender, e) => {
                var camera = new MediaPicker ();

                if (!camera.IsCameraAvailable) {
                    Console.WriteLine("Camera unavailable!");
                    return;
                }

                var opts = new StoreCameraMediaOptions {
                    Name = "test.jpg",
                    Directory = "MiniHackDemo"
                };

                camera.TakePhotoAsync (opts).ContinueWith (t => {
                    if (t.IsCanceled)
                        return;

                    InvokeOnMainThread(() => imagePhoto.Image = UIImage.FromFile(t.Result.Path));
                });
            };
        }
Esempio n. 2
0
        public void TakeAndStorePhoto(Action<string> onPhotoTaken)
        {
            var picker = new MediaPicker();
            if (!picker.IsCameraAvailable || !picker.PhotosSupported)
            {
                MvxTrace.Trace(MvxTraceLevel.Diagnostic, "Photo taking not available");
                return;
            }

            var photoName = string.Format("Sphero{0:yyyyMMddHHmmss}.jpg", DateTime.Now);
            picker.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    Name = photoName,
                    Directory = PictureFolder
                })
                  .ContinueWith(t =>
                      {
                          if (t.IsCanceled)
                              return;

#warning Code to do...
                          //var file = this.GetService<IMvxSimpleFileStoreService>();
                          //file.WriteFile(t.Result.Path, stream => t.Result.GetStream().CopyTo(stream));
                          //file.WriteFile("Test.txt", "Some text");
                          onPhotoTaken(t.Result.Path);
                      });
        }
		public async System.Threading.Tasks.Task<CameraFile> TakePhotoAsync ()
		{
			CameraFile result = new CameraFile ();

			try {
				var picker = new MediaPicker (Platform_Android.MainActivity);
				if (!picker.IsCameraAvailable) {
					result.Exception = new ArgumentException ("No camera available.");
				} else {
					try {
						var file = await picker.TakePhotoAsync (new StoreCameraMediaOptions {
							Name = "test.jpg",
							Directory = "PoSDB"
						});
						File.WriteAllBytes (file.Path + "_small.jpg", ResizeImageAndroid (imageData: File.ReadAllBytes (file.Path)));
						result.Stream = () => new MemoryStream (File.ReadAllBytes (file.Path + "_small.jpg"));

					} catch (OperationCanceledException) {
						result.IsCancelled = true;
					}
				}
			} catch (Exception ex) {
				result.Exception = ex;
			}

			return result;
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var picker = new MediaPicker ();

			this.bntCamera.TouchUpInside += (sender, e) => {
				if (!picker.IsCameraAvailable)
					lblSuccess.Text = "No camera!";
				else {
					picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "MediaPickerSample"
					}).ContinueWith (t => {
						if (t.IsCanceled) {
							lblSuccess.Text = "User cancelled";
							return;
						}
						lblSuccess.Text = "Photo succeeded";
						Console.WriteLine(t.Result.Path);
					}, TaskScheduler.FromCurrentSynchronizationContext());
				}
			};

		}
Esempio n. 5
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button> (Resource.Id.myButton);
			TextView label = FindViewById<TextView> (Resource.Id.lblSuccess);
			
			button.Click += delegate {
				var picker = new MediaPicker (this);
				if (!picker.IsCameraAvailable)
					 label.Text = "No camera!";
				else {
					picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "MediaPickerSample"
					}).ContinueWith (t => {
						if (t.IsCanceled) {
							label.Text = "User canceled";
							return;
						}
						label.Text = "Photo succeeded";
						Console.WriteLine (t.Result.Path);
					}, TaskScheduler.FromCurrentSynchronizationContext());
				}
			};


		}
		/// <summary>
		/// Event handler when the user clicks the Take a Photo button
		/// </summary>
		/// <param name='sender'>
		/// Sender
		/// </param>
		partial void takePhotoBtnClicked (MonoTouch.Foundation.NSObject sender)
		{
			Console.WriteLine("takePhotoBtnClicked");
			
			picker = new MediaPicker ();
			
			// Check if a camera is available and photos are supported on this device
			if (!picker.IsCameraAvailable || !picker.PhotosSupported)
			{
				ShowUnsupported();
				return;
			}

			// Call TakePhotoAsync, which gives us a Task<MediaFile>
			picker.TakePhotoAsync (new StoreCameraMediaOptions
			{
				Name = "test.jpg",
				Directory = "MediaPickerSample"
			})
			.ContinueWith (t => // Continue when the user has taken a photo
			{
				if (t.IsCanceled) // The user canceled
					return;
					
				// Show the photo the user took
				InvokeOnMainThread( delegate {
					UIImage image = UIImage.FromFile(t.Result.Path);
					this.imageView.Image = image;	
				});
			});
		}
Esempio n. 7
0
        public void TakeAndStorePhoto(Action<string> onPhotoTaken)
        {
            var currentActivityService = this.GetService<IMvxAndroidCurrentTopActivity>();
            var currentActivity = currentActivityService.Activity;

            var picker = new MediaPicker(currentActivity);
            if (!picker.IsCameraAvailable || !picker.PhotosSupported)
            {
                MvxTrace.Trace(MvxTraceLevel.Diagnostic, "Photo taking not available");
                return;
            }

            var photoName = string.Format("Sphero{0:yyyyMMddHHmmss}.jpg", DateTime.Now);
            picker.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    Name = photoName,
                    Directory = PictureFolder
                })
                  .ContinueWith(t =>
                      {
                          if (t.IsCanceled)
                              return;

                          onPhotoTaken(t.Result.Path);
                      });
        }
Esempio n. 8
0
 private async Task<MediaFile> UseCamera(MediaPicker picker) {
     var fileName = DateTime.Now.Ticks + ".png";
     return await picker.TakePhotoAsync(new StoreCameraMediaOptions {
         Directory = "temp",
         Name = fileName
         //DefaultCamera = CameraDevice.Rear
     });
 }
		public async void TakePicture ()
		{
			var picker = new MediaPicker();

			var mediaFile = await picker.TakePhotoAsync (new StoreCameraMediaOptions () {
				DefaultCamera = CameraDevice.Front,
			});

			System.Diagnostics.Debug.WriteLine(mediaFile.Path);

			MessagingCenter.Send<IPhotoService, string>(this, "photoShot", mediaFile.Path);
		}
Esempio n. 10
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.buttonLocation);
            LabelLocation = FindViewById<TextView>(Resource.Id.locationLabel);
            image = FindViewById<ImageView>(Resource.Id.imagePhoto);

            button.Click += delegate {

                var locator = new Geolocator(this) { DesiredAccuracy = 50 };
                locator.GetPositionAsync(timeout: 10000).ContinueWith(t =>
                {
                    var text = String.Format("Location : Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude);
                    this.RunOnUiThread(() => LabelLocation.Text = text);
                });
            };

            Button getimge = FindViewById<Button>(Resource.Id.buttonCamera);
            getimge.Click += delegate
            {
                var camera = new MediaPicker(this);

                if (!camera.IsCameraAvailable)
                {
                    Console.WriteLine("Camera unavailable!");
                    return;
                }

                var opts = new StoreCameraMediaOptions
                {
                    Name = "test.jpg",
                    Directory = "MiniHackDemo"
                };

                camera.TakePhotoAsync(opts).ContinueWith(t =>
                {
                    if (t.IsCanceled)
                        return;

                    using (var bmp = Android.Graphics.BitmapFactory.DecodeFile(t.Result.Path))
                    {
                        this.RunOnUiThread(() => image.SetImageBitmap(bmp));
                    }
                });
                
            };
        }
Esempio n. 11
0
 void BtChooseImage_TouchUpInside(object sender, EventArgs e)
 {
     esStat.Reset ();
     var picker = new MediaPicker();
     picker.TakePhotoAsync(new StoreCameraMediaOptions {
         Name = "emo.jpg",
         Directory = "EmotionDetector"
     }).ContinueWith (async t => {
         MediaFile file = t.Result;
         ivImage.Image = MaxResizeImage(UIImage.FromFile(file.Path), 640, 640);
         await _vm.Load (ivImage.Image.AsPNG().AsStream());
         DrawRects (_vm.Emotions);
     }, TaskScheduler.FromCurrentSynchronizationContext());
 }
		public static async Task<string> PathToPictureFromCamera (MediaPicker mediaPicker)
		{
			try{
				if (!mediaPicker.IsCameraAvailable || !mediaPicker.PhotosSupported) {
					return null;
				}

				var mediaFile = await mediaPicker.TakePhotoAsync (new StoreCameraMediaOptions {});

				return mediaFile.Path;
			} catch {
				return null;
			}
		}
Esempio n. 13
0
		public static void PictureFromCamera (MediaPicker picker, Action<MediaFile> callback)
		{
			if (!picker.IsCameraAvailable || !picker.PhotosSupported) {
				//ToDo: How to handle unsupported
				return;
			}
			picker.TakePhotoAsync (new StoreCameraMediaOptions
			{
				Name = string.Format("photo{0}.jpg", Guid.NewGuid()),
				Directory = "LB"
			}).ContinueWith (t => {
				if(t.IsCanceled)
					return;

				callback(t.Result);
			});
		}
Esempio n. 14
0
		partial void PhotoButton_TouchUpInside (UIButton sender)
		{
			var picker = new MediaPicker ();
			//           new MediaPicker (this); on Android
			if (!picker.IsCameraAvailable)
				Console.WriteLine ("No camera!");
			else {
				picker.TakePhotoAsync (new StoreCameraMediaOptions {
					Name = "test.jpg",
					Directory = "MediaPickerSample"
				}).ContinueWith (t => {
					if (t.IsCanceled) {
						Console.WriteLine ("User canceled");
						return;
					}
					Console.WriteLine (t.Result.Path);
				});
			}
		}
Esempio n. 15
0
 public async Task<Stream> TakePhoto()
 {
     var picker = new MediaPicker();
     if (!picker.IsCameraAvailable)
     {
         return null;
     }
     MediaFile mf = null;
     try
     {
         mf = await picker.TakePhotoAsync(new StoreCameraMediaOptions());
     }
     catch (TaskCanceledException)
     {
         Debug.WriteLine("photo picker canceled");
     }
     if (mf == null)
     {
         return null;
     }
     return mf.GetStream();
 }
		async void PresentCamera ()
		{

			var picker = new MediaPicker (Context);
			if (!picker.IsCameraAvailable)
				System.Console.WriteLine ("No camera!");
			else {
				try {
					// TakePhotoAsync is deprecated?
					var file = await picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "CouchbaseConnect",
						DefaultCamera = CameraDevice.Rear
					});
					Console.WriteLine(file.Path);
					((CameraContentPage)this.Element).Captured = file.Path;
				} catch (Exception e) {
					Console.WriteLine ("Take Photo Cancelled.");
				}
				((CameraContentPage)this.Element).IsPresented = false;
			}
		}
Esempio n. 17
0
		async partial void OnTakePhoto()
		{
			var picker = new MediaPicker ();
			if (!picker.IsCameraAvailable)
				await DisplayAlert("Error", "No Camera Available!", "OK");
			else 
			{
				try 
				{
					MediaFile file = await picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "photos",
						DefaultCamera = CameraDevice.Rear,
					});

					Image image = new Image() { Source = new FileImageSource { File = file.Path } };
					this.Content = image;
				} 
				catch (OperationCanceledException) 
				{
					Console.WriteLine ("Canceled");
				}
			}
		}
Esempio n. 18
0
		public override async void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);

			if (fileName == "") {
				fileName = "in-progress";
				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android
				if (!picker.IsCameraAvailable || !picker.PhotosSupported)
					Console.WriteLine ("No camera!");
				else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};
#if !VISUALSTUDIO
					#region new style
					pickerController = picker.GetTakePhotoUI (options);
					PresentViewController (pickerController, true, null);

					var pickerTask = pickerController.GetResultAsync ();
					await pickerTask;

					// We need to dismiss the controller ourselves
					await DismissViewControllerAsync (true); // woot! async-ified iOS method

					// User canceled or something went wrong
					if (pickerTask.IsCanceled || pickerTask.IsFaulted)
						return;

					// We get back a MediaFile
					MediaFile media = pickerTask.Result;
					fileName = media.Path;
					PhotoImageView.Image = new UIImage (fileName);
					SavePicture(fileName);

					#endregion
#else
					#region old style (deprecated)
					var t = picker.TakePhotoAsync (options); //.ContinueWith (t => {
					await t;
					if (t.IsCanceled) {
						Console.WriteLine ("User canceled");
						fileName = "cancelled";
						//InvokeOnMainThread(() =>{
						NavigationController.PopToRootViewController(false);
						//});
						return;
					}
					Console.WriteLine (t.Result.Path);
					fileName = t.Result.Path;
					//InvokeOnMainThread(() =>{
					PhotoImageView.Image = new UIImage (fileName);
					//});
					SavePicture(fileName);
					//});
					#endregion
#endif
				}
			} else if (fileName == "cancelled") {
				NavigationController.PopToRootViewController (true);
			} else {
				// populate screen with existing item
				PhotoImageView.Image = new UIImage (fileName);
				LocationText.Text = location;
			}

			var locator = new Geolocator { DesiredAccuracy = 50 };
			//            new Geolocator (this) { ... }; on Android
			var position = await locator.GetPositionAsync (timeout: 10000); //.ContinueWith (p => {
			Console.WriteLine ("Position Latitude: {0}", position.Latitude);
			Console.WriteLine ("Position Longitude: {0}", position.Longitude);

			location = string.Format("{0},{1}", position.Latitude, position.Longitude);

			LocationText.Text = location;
		}
		async void OpenImagePicker(){
			//It works? Don't use gallery
			var robotImagePicker = new MediaPicker(Forms.Context);

			await robotImagePicker.TakePhotoAsync(new StoreCameraMediaOptions {
				Name = data["teamNumber"].ToString() + ".jpg",
				Directory = "Robot Images"
			}).ContinueWith(t=>{
				robotImageFile = t.Result;
				Console.WriteLine("Robot Image Path: " + robotImageFile.Path);
			},TaskScheduler.FromCurrentSynchronizationContext());
			robotImage.Source = robotImageFile.Path;
			try{
				ParseFile image = new ParseFile(data["teamNumber"].ToString()+".jpg", ImageToBinary(robotImageFile.Path));

				data["robotImage"] = image;
				await data.SaveAsync();
			}
			catch{
				Console.WriteLine ("Image Save Error");
			}
		}
        private async void AddImage(object obj)
        {
            var mediaPicker = new MediaPicker(App.UIContext);
            var photo = await mediaPicker.TakePhotoAsync(new StoreCameraMediaOptions());

            MobileServiceFile file = await this.itemManager.AddImage(this.todoItem, photo.Path);

            var image = new TodoItemImageViewModel(file, this.todoItem, DeleteImage);

            this.images.Add(image);
        }
Esempio n. 21
0
		protected override async void OnResume ()
		{
			base.OnResume ();

			int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0);
			if(itemId > 0) {
				shareItem = App.Database.GetItem(itemId);

				fileName = shareItem.ImagePath;
				System.Console.WriteLine("Image path: " + fileName);
				Bitmap b = BitmapFactory.DecodeFile (fileName);
				// Display the bitmap
				photoImageView.SetImageBitmap (b);
				locationText.Text = shareItem.Location;
				return;
			}

			if (fileName == "") {
				fileName = "in-progress";
				var picker = new MediaPicker (this);
				//           new MediaPicker (); on iOS
				if (!picker.IsCameraAvailable)
					System.Console.WriteLine ("No camera!");
				else {
					var options = new StoreCameraMediaOptions {
						Name = DateTime.Now.ToString("yyyyMMddHHmmss"),
						Directory = "MediaPickerSample"
					};
#if !VISUALSTUDIO
					#region new style
					if (!picker.IsCameraAvailable || !picker.PhotosSupported) {
						ShowUnsupported();
						return;
					}

					Intent intent = picker.GetTakePhotoUI (options);

					StartActivityForResult (intent, 1);
					#endregion
#else 
					#region old style (deprecated)
					var t = picker.TakePhotoAsync (options); 
					await t;
					if (t.IsCanceled) {
						System.Console.WriteLine ("User canceled");
						fileName = "cancelled";
						// TODO: return to main screen
						StartActivity(typeof(MainScreen));
						return;
					}
					System.Console.WriteLine (t.Result.Path);
					fileName = t.Result.Path;
					fileNameThumb = fileName.Replace(".jpg", "_thumb.jpg"); 

					Bitmap b = BitmapFactory.DecodeFile (fileName);
					RunOnUiThread (() =>
					               {
						// Display the bitmap
						photoImageView.SetImageBitmap (b);

						// Cleanup any resources held by the MediaFile instance
						t.Result.Dispose();
					});
					var boptions = new BitmapFactory.Options {OutHeight = 128, OutWidth = 128};
					var newBitmap = await BitmapFactory.DecodeFileAsync (fileName, boptions);
					var @out = new System.IO.FileStream(fileNameThumb, System.IO.FileMode.Create);
					newBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, @out);
					//});
					#endregion
#endif
				}
			} 

			try {
				var locator = new Geolocator (this) { DesiredAccuracy = 50 };
				//            new Geolocator () { ... }; on iOS
				var position = await locator.GetPositionAsync (timeout: 10000);
				System.Console.WriteLine ("Position Latitude: {0}", position.Latitude);
				System.Console.WriteLine ("Position Longitude: {0}", position.Longitude);

				location = string.Format("{0},{1}", position.Latitude, position.Longitude);
				locationText.Text = location;
			} catch (Exception e) {
				System.Console.WriteLine ("Position Exception: " + e.Message);
			}
		}
 private async void CameraIconPressed(object sender, EventArgs e)
 {
     //use the Xamarin.Media library to take the picture
     //it's cross platform and allows for quick access for taking picutres
     //would want to use native calls if you need customized solution
     var picturePicker = new MediaPicker();
     if (!picturePicker.IsCameraAvailable)
     {
         //show alert that no camera is available
         var alert = UIAlertController.Create("Error", "Sorry I tried to access the camera on your device, but your device told me you don't have one.  I can't take a picture without one.", UIAlertControllerStyle.Alert);
         //add in the ok button
         alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
         //show the alert dialog on the UI
         PresentViewController(alert, true, null);
     }
     else
     {
         try
         {
             var media = await picturePicker.TakePhotoAsync(new StoreCameraMediaOptions
             {
                 Name = string.Format("test_picture_{0}.jpg", DateTime.Now),
                 Directory = "CameraExample"
             });
             if (media != null)
             {
                 _files.Add(media.Path);
                 this.TableView.ReloadData();
             }
         }
         catch (OperationCanceledException operationCancelledException)
         {
             //TODO log they cancelled taking the picture
             System.Console.WriteLine(operationCancelledException);
         }
         catch (System.Exception ex)
         {
             System.Console.WriteLine(ex.StackTrace);
         }
     }
 }
		void MediaChooser (object sender, EventArgs e)
		{
			var builder = new AlertDialog.Builder(this);
			builder.SetTitle("Media Chooser");
			builder.SetMessage("Camera Or Library");
			builder.SetCancelable(false);

			builder.SetPositiveButton("Camera"
			                          , 
			                          delegate 
			                          { 
				var picker = new MediaPicker (this);

				if (!picker.IsCameraAvailable)
					Console.WriteLine ("No camera!");

				else 
				{
					picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "MediaPickerSample"
					}).ContinueWith (t => {

						if (t.IsCanceled) 
						{
							Console.WriteLine ("User canceled");
							return;
						}

						Console.WriteLine (t.Result.Path);

						//Load image to imageView
						b = BitmapFactory.DecodeFile(t.Result.Path);
						imageView.SetImageBitmap(b);

					}, TaskScheduler.FromCurrentSynchronizationContext());
				}

			}
			);

			builder.SetNeutralButton("Library"
			                         ,
			                         delegate 
			                         {
				var picker = new MediaPicker (this);


				picker.PickPhotoAsync()
					.ContinueWith (t => {

						if (t.IsCanceled) 
						{
							Console.WriteLine ("User canceled");
							return;
						}

						Console.WriteLine (t.Result.Path);
						b = BitmapFactory.DecodeFile(t.Result.Path);
						imageView.SetImageBitmap(b);

					}, TaskScheduler.FromCurrentSynchronizationContext());
			}

			);



			builder.SetNegativeButton("Cancel",delegate {});

			builder.Show();
		}
        void ActionSheetTapped(object sender, UIButtonEventArgs e)
        {
            MediaPicker picker = new MediaPicker ();

            if (e.ButtonIndex == 0)
            {
                Task<MediaFile> task = picker.TakePhotoAsync (new StoreCameraMediaOptions ()
                                                              {DefaultCamera= CameraDevice.Front});
                HandlePick (task);
            }
            else if (e.ButtonIndex == 1)
            {
                PickPhotoFromLibrary (picker);
            }
        }
Esempio n. 25
-1
 public Task<MediaFile> GetPhoto(bool takeNew)
 {
     #if MONOANDROID
     var activity = this.GetService<Cirrious.MvvmCross.Droid.Interfaces.IMvxAndroidCurrentTopActivity>();
     var picker = new MediaPicker(activity.Activity);
     #else
     var picker = new MediaPicker();
     #endif
     if (takeNew)
         return picker.TakePhotoAsync(new StoreCameraMediaOptions());
     else
         return picker.PickPhotoAsync();
 }
Esempio n. 26
-1
        public WelcomeViewModel(MediaPicker picker)
        {
            TakeNewPhoto = new ReactiveAsyncCommand();
            ChooseExistingPhoto = new ReactiveAsyncCommand();
            StartEdit = new ReactiveCommand();

            var defaultCamera = new StoreCameraMediaOptions() { DefaultCamera = CameraDevice.Rear, Directory = "LeeMe", Name = "turnt.jpg", };

            Observable.Merge(
                    TakeNewPhoto.RegisterAsyncTask(_ => picker.TakePhotoAsync(defaultCamera)),
                    ChooseExistingPhoto.RegisterAsyncTask(_ => picker.PickPhotoAsync()))
                .Select(x => x.Path)
                .InvokeCommand(StartEdit);

            // TODO: Write a proper UserError handler for this
            TakeNewPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
            ChooseExistingPhoto.ThrownExceptions.Subscribe(ex => Console.WriteLine(ex));
        }
		public PhotoAlertSheet ()
		{
			picker = new MediaPicker ();

			AddButton ("Photo Library");
			if (picker.IsCameraAvailable)
				AddButton ("Camera");

			Dismissed += (sender, e) => {
				switch (e.ButtonIndex) {
				case 0:
					picker.PickPhotoAsync ()
						.ContinueWith (t => {

							if (t.IsCanceled)
								return null;

							SetImage(t.Result.GetStream());
							return t.Result;
						});
					break;
				case 1:
					picker.TakePhotoAsync (new StoreCameraMediaOptions())
						.ContinueWith (t => {

							if (t.IsCanceled)
								return t.Result;

							SetImage(t.Result.GetStream());
							return t.Result;
						});
					break;
				default:
					break;
				}
			};
		}
Esempio n. 28
-1
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			SetContentView (Resource.Layout.Main);
			ImageView image = FindViewById<ImageView> (Resource.Id.image);
			VideoView videoView  = FindViewById<VideoView>(Resource.Id.surfacevideoview);
			
			
			//
			// Wire up the take a video button
			//
			Button videoButton = FindViewById<Button> (Resource.Id.takeVideoButton);
			videoButton.Click += delegate
			{
				//
				// The MediaPicker is the class used to 
				// invoke the camera and gallery picker
				// for selecting and taking photos
				// and videos
				//
				var picker = new MediaPicker (this);

				// We can check to make sure the device has a camera
				// and supports dealing with video.
				if (!picker.IsCameraAvailable || !picker.VideosSupported)
				{
					ShowUnsupported();
					return;
				}
				
				//
				// TakeVideoAsync is an async API that takes a 
				// StoreVideoOptions object with various 
				// properties, such as the name and folder to
				// store the resulting video. You can
				// also limit the length of the video
				//
				picker.TakeVideoAsync (new StoreVideoOptions
				{
					Name = "MyVideo",
					Directory = "MyVideos",
					DesiredLength = TimeSpan.FromSeconds (10)
				})
				.ContinueWith (t =>
				{
					if (t.IsCanceled)
						return;

					//
					// Because TakeVideoAsync returns a Task
					// we can use ContinueWith to run more code
					// after the user finishes recording the video
					//
					RunOnUiThread (() =>
					{
						//
						// Toggle the visibility of the image and videoviews
						//
						image.Visibility = Android.Views.ViewStates.Gone;	
						videoView.Visibility = Android.Views.ViewStates.Visible;
						
						//	
						// Load in the video file
						//
						videoView.SetVideoPath(t.Result.Path);
	        
						//
						// optional: Handle when the video finishes playing
						//
	        			//videoView.setOnCompletionListener(this);
	        
						//
						// Start playing the video
						//	
	        			videoView.Start();
					});
				});
			};
			
			//
			// Wire up the take a photo button
			//
			Button photoButton = FindViewById<Button> (Resource.Id.takePhotoButton);
			photoButton.Click += delegate
			{
				var picker = new MediaPicker (this);

				if (!picker.IsCameraAvailable || !picker.PhotosSupported)
				{
					ShowUnsupported();
					return;
				}

				picker.TakePhotoAsync (new StoreCameraMediaOptions
				{
					Name = "test.jpg",
					Directory = "MediaPickerSample"
				})
				.ContinueWith (t =>
				{
					if (t.IsCanceled)
						return;

					Bitmap b = BitmapFactory.DecodeFile (t.Result.Path);
					RunOnUiThread (() =>
					{
						//
						// Toggle the visibility of the image and video views
						//
						videoView.Visibility = Android.Views.ViewStates.Gone;
						image.Visibility = Android.Views.ViewStates.Visible;
							
						//
						// Display the bitmap
						//
						image.SetImageBitmap (b);

						// Cleanup any resources held by the MediaFile instance
						t.Result.Dispose();
					});
				});
			};
			
			//
			// Wire up the pick a video button
			//
			Button pickVideoButton = FindViewById<Button> (Resource.Id.pickVideoButton);
			pickVideoButton.Click += delegate
			{
				//
				// The MediaPicker is the class used to 
				// invoke the camera and gallery picker
				// for selecting and taking photos
				// and videos
				//
				var picker = new MediaPicker (this);
				
				if (!picker.VideosSupported)
				{
					ShowUnsupported();
					return;
				}

				//
				// PickVideoAsync is an async API that invokes
				// the native gallery
				//
				picker.PickVideoAsync ()
				.ContinueWith (t =>
				{
					if (t.IsCanceled)
						return;

					//
					// Because PickVideoAsync returns a Task
					// we can use ContinueWith to run more code
					// after the user finishes recording the video
					//
					RunOnUiThread (() =>
					{
						//
						// Toggle the visibility of the image and video views
						//
						image.Visibility = Android.Views.ViewStates.Gone;	
						videoView.Visibility = Android.Views.ViewStates.Visible;
						
						//	
						// Load in the video file
						//
						videoView.SetVideoPath(t.Result.Path);
	        
						//
						// Optional: Handle when the video finishes playing
						//
	        			//videoView.setOnCompletionListener(this);
	        
						//
						// Start playing the video
						//	
	        			videoView.Start();

						// Cleanup any resources held by the MediaFile instance
						t.Result.Dispose();
					});
				});
			};
			
			//
			// Wire up the pick a photo button
			//
			Button pickPhotoButton = FindViewById<Button> (Resource.Id.pickPhotoButton);
			pickPhotoButton.Click += delegate
			{
				var picker = new MediaPicker (this);

				if (!picker.PhotosSupported)
				{
					ShowUnsupported();
					return;
				}

				picker.PickPhotoAsync ()
				.ContinueWith (t =>
				{
					if (t.IsCanceled)
						return;

					Bitmap b = BitmapFactory.DecodeFile (t.Result.Path);
					RunOnUiThread (() =>
					{
						//
						// Toggle the visibility of the image and video views
						//
						videoView.Visibility = Android.Views.ViewStates.Gone;
						image.Visibility = Android.Views.ViewStates.Visible;
							
						//
						// Display the bitmap
						//
						image.SetImageBitmap (b);

						// Cleanup any resources held by the MediaFile instance
						t.Result.Dispose();
					});
				});
			};
		}
Esempio n. 29
-1
 private void TakePhoto()
 {
     var picker = new MediaPicker (this);
     if (picker.IsCameraAvailable) {
         picker.TakePhotoAsync (new StoreCameraMediaOptions ())
             .ContinueWith (r => ProcessImage (r));
     } else {
         picker.PickPhotoAsync ().ContinueWith (r => ProcessImage (r));
     }
 }
		void MediaChooser (object sender, UIButtonEventArgs e)
		{
			if (e.ButtonIndex == 1) {

				System.Console.WriteLine ("Camera");

				var picker = new MediaPicker ();

				if (!picker.IsCameraAvailable)
					Console.WriteLine ("No camera!");

				else 
				{
					picker.TakePhotoAsync (new StoreCameraMediaOptions {
						Name = "test.jpg",
						Directory = "MediaPickerSample"
					}).ContinueWith (t => {

						if (t.IsCanceled) 
						{
							Console.WriteLine ("User canceled");
							return;
						}

						Console.WriteLine (t.Result.Path);
						imageView.Image = new UIImage(t.Result.Path);

					}, TaskScheduler.FromCurrentSynchronizationContext());
				}



			} 
			else if (e.ButtonIndex == 2) 
			{

				System.Console.WriteLine ("Library");

				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android

				picker.PickPhotoAsync()
					.ContinueWith (t => {

						if (t.IsCanceled) 
						{
							Console.WriteLine ("User canceled");
							return;
						}

						Console.WriteLine (t.Result.Path);
						imageView.Image = new UIImage(t.Result.Path);

					}, TaskScheduler.FromCurrentSynchronizationContext());
			}

		}