Пример #1
0
        void OnAlertDismissed(object sender, UIButtonEventArgs 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;
            }
        }
Пример #2
0
        private async Task PickImageAsync()
        {
            try
            {
                var photo = await MediaPicker.PickPhotoAsync();

                if (photo == null)
                {
                    return;
                }
                Stream stream = await photo.OpenReadAsync();

                if (stream != null)
                {
                    using (MemoryStream memory = new MemoryStream())
                    {
                        stream.CopyTo(memory);
                        byte[] bytes = memory.ToArray();
                        ProjectImageSource = ImageSource.FromStream(() => new MemoryStream(bytes));
                        _base64            = Convert.ToBase64String(bytes);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CapturePhotoAsync THREW: {ex.Message}");
            }
        }
Пример #3
0
        async private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            string answer = await DisplayActionSheet("Đổi ảnh đại diện bằng ?", "Hủy", null, "Camera", "Chọn ảnh");

            if (answer == "Chọn ảnh")
            {
                var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
                {
                    Title = "Please pick a photo"
                });

                if (result != null)
                {
                    var stream = await result.OpenReadAsync();

                    resultImage.Source = ImageSource.FromStream(() => stream);
                }
            }
            else if (answer == "Camera")
            {
                var result = await MediaPicker.CapturePhotoAsync(new MediaPickerOptions
                {
                    Title = "Please pick a photo"
                });

                if (result != null)
                {
                    var stream = await result.OpenReadAsync();

                    resultImage.Source = ImageSource.FromStream(() => stream);
                }
            }
        }
Пример #4
0
        public static async Task <string> PickPhotoAsync()
        {
            string filePath = null;
            // Must run on MainThread for Xamarin.Essentials to handle permissions request
            await MainThread.InvokeOnMainThreadAsync(async() =>
            {
                try
                {
                    var photo        = await MediaPicker.PickPhotoAsync();
                    string photoPath = await LoadPhotoAsync(photo);

                    if (photoPath != null)
                    {
                        filePath = photoPath;
                    }
                    // if null, operation was cancelled
                }
                catch (PermissionException)
                {
                    throw new Exception("Permission was not granted. Please grant the app permission to access your photos.");
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            });

            return(await Task.FromResult(filePath));
        }
        async void PickPhotoAsync()
        {
            try
            {
                var photo = await MediaPicker.PickPhotoAsync();

                var stream = await photo.OpenReadAsync();

                avatar.Source = ImageSource.FromStream(() => stream);

                var img = App.firebase.storage.Child("images").Child(App.firebase.currentUser.LocalId + ".png").PutAsync(await photo.OpenReadAsync());
                img.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");
                var img_url = await img;

                var res = await App.firebase.auth.UpdateProfileAsync(App.firebase.userLink.FirebaseToken, App.firebase.userLink.User.DisplayName, img_url);

                App.firebase.currentUser = res.User;

                var page = Application.Current.MainPage.Navigation.NavigationStack.Last() as SlideMenu.SlideMenu;
                page.refresh();

                Console.WriteLine($"CapturePhotoAsync COMPLETED: {img_url}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CapturePhotoAsync THREW: {ex}");
            }
        }
Пример #6
0
        public async void SnapPic()
        {
            var picker    = new MediaPicker();
            var mediafile = await picker.PickPhotoAsync();

            System.Diagnostics.Debug.WriteLine(mediafile.Path);
        }
        /// <summary>
        /// Event handler when the user clicks the Pick a Photo button
        /// </summary>
        /// <param name='sender'>
        /// Sender
        /// </param>
        partial void pickPhotoBtnClicked(MonoTouch.Foundation.NSObject sender)
        {
            Console.WriteLine("pickPhotoBtnClicked");

            picker = new MediaPicker();

            // Check if photos are supported on this device
            if (!picker.PhotosSupported)
            {
                ShowUnsupported();
                return;
            }

            // Call PickPhotoAsync, which gives us a Task<MediaFile>
            picker.PickPhotoAsync()
            .ContinueWith(t =>              // Continue when the user has picked a photo
            {
                if (t.IsCanceled)           // The user canceled
                {
                    return;
                }

                // Show the photo the user selected
                InvokeOnMainThread(delegate {
                    UIImage image        = UIImage.FromFile(t.Result.Path);
                    this.imageView.Image = image;
                });
            });
        }
        private async Task SendAttachmentsEmail(bool usePlatformApi = true)
        {
            var       mediaPicker = new MediaPicker();
            MediaFile mediaFile   = await mediaPicker.PickPhotoAsync();

            if (mediaFile != null)
            {
                IEmailMessage email;
                if (usePlatformApi)
                {
                    NSUrl url = new NSUrl(mediaFile.Path, false);
                    email = SamplesExtensions.BuildSampleEmail()
                            .WithAttachment(url)
                            .Build();
                }
                else
                {
                    // Hard coded mimetype for sample. Should query file to determine at run-time
                    email = SamplesExtensions.BuildSampleEmail()
                            .WithAttachment(mediaFile.Path, @"image/jpeg")
                            .Build();
                }

                CrossMessaging.Current.EmailMessenger.SendSampleEmail(email);
            }
        }
Пример #9
0
        public static async Task <Stream> ChoosePicture()
        {
            try
            {
                var picker = new MediaPicker();
                await picker.PickPhotoAsync().ContinueWith(t =>
                {
                    PhotoMediaFile = t.Result;
                    Console.WriteLine(PhotoMediaFile.Path);
                }, TaskScheduler.FromCurrentSynchronizationContext());

                var photoStream = PhotoMediaFile.GetStream();
                if (photoStream != null)
                {
                    return(photoStream);
                }
                else
                {
                    await UserDialogs.Instance.AlertAsync("No photos library accessible", "Photos Library missing", "OK");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("PhotoPickerService.ChoosePicture() error: {0} - {1}", e.Message, e.StackTrace);
            }

            return(null);
        }
Пример #10
0
        private async void ButtonSelectFile_Clicked(object sender, EventArgs e)
        {
            try
            {
                ButtonUploadFile.IsEnabled = false;

                FileResult photo;
                if (MediaPicker.IsCaptureSupported)
                {
                    photo = await MediaPicker.CapturePhotoAsync();
                }
                else
                {
                    photo = await MediaPicker.PickPhotoAsync();
                }

                if (photo == null)
                {
                    return;
                }

                _selectedFile = photo;

                LabelFileName.Text = $"{_selectedFile.FileName} file selected. Ready to upload!";

                ButtonUploadFile.IsEnabled = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ops something went wrong: {ex.Message}");
                ButtonUploadFile.IsEnabled = false;
            }
        }
Пример #11
0
        async void OnScanBarcodeFromImage(System.Object sender, System.EventArgs e)
        {
            var result = await MediaPicker.PickPhotoAsync();

            if (result != null)
            {
                var stream = await result.OpenReadAsync();

                var bytes = new byte[stream.Length];
                await stream.ReadAsync(bytes, 0, bytes.Length);

                stream.Seek(0, SeekOrigin.Begin);

                List <GoogleVisionBarCodeScanner.BarcodeResult> obj = await GoogleVisionBarCodeScanner.Methods.ScanFromImage(bytes);

                string ss = string.Empty;

                for (int i = 0; i < obj.Count; i++)
                {
                    ss += $"{i + 1}. BarcodeType : {obj[i].BarcodeType}, Barcode : {obj[i].DisplayValue}{Environment.NewLine}";
                }

                Device.BeginInvokeOnMainThread(async() =>
                {
                    LblBarcodeValue.Text = ss;

                    await DisplayAlert("Selected Barcode Detail", ss, "ok");
                });
            }
        }
Пример #12
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            var root = new RootElement("Xamarin.Social Sample");

            var section = new Section("Services");

            var facebookButton = new StringElement("Share with Facebook");

            facebookButton.Tapped += delegate { Share(Facebook, facebookButton); };
            section.Add(facebookButton);

            var twitterButton = new StringElement("Share with Twitter");

            twitterButton.Tapped += delegate { Share(Twitter, twitterButton); };
            section.Add(twitterButton);

            var twitter5Button = new StringElement("Share with built-in Twitter");

            twitter5Button.Tapped += delegate { Share(Twitter5, twitter5Button); };
            section.Add(twitter5Button);

            var flickr = new StringElement("Share with Flickr");

            flickr.Tapped += () => {
                var picker = new MediaPicker();                 // Set breakpoint here
                picker.PickPhotoAsync().ContinueWith(t =>
                {
                    if (t.IsCanceled)
                    {
                        return;
                    }

                    var item = new Item("I'm sharing great things using Xamarin!")
                    {
                        Images = new[] { new ImageData(t.Result.Path) }
                    };

                    Console.WriteLine("Picked image {0}", t.Result.Path);

                    UIViewController viewController = Flickr.GetShareUI(item, shareResult =>
                    {
                        dialog.DismissViewController(true, null);
                        flickr.GetActiveCell().TextLabel.Text = "Flickr shared: " + shareResult;
                    });

                    dialog.PresentViewController(viewController, true, null);
                }, TaskScheduler.FromCurrentSynchronizationContext());
            };
            section.Add(flickr);
            root.Add(section);

            dialog = new DialogViewController(root);

            window = new UIWindow(UIScreen.MainScreen.Bounds);
            window.RootViewController = new UINavigationController(dialog);
            window.MakeKeyAndVisible();

            return(true);
        }
Пример #13
0
        /// <summary>
        /// Take Photo async
        /// </summary>
        /// <returns></returns>
        public async Task <PhotoItemModel> GetPhotoFromStorageAsync()
        {
            var photo = await MediaPicker.PickPhotoAsync().ConfigureAwait(false);

            var photoModel = await LoadPhotoAsync(photo).ConfigureAwait(false);

            return(photoModel);
        }
 /// <summary>
 /// pick the photo from gallery
 /// </summary>
 private async void executeGallery()
 {
     try {
         var photo = await MediaPicker.PickPhotoAsync();
         await SaveAndReturn(photo);
     }
     catch (Exception) { }
 }
Пример #15
0
        public async void SnapPic()
        {
            var picker    = new MediaPicker();
            var mediaFile = await picker.PickPhotoAsync();

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

            MessagingCenter.Send <IPictureTaker, string>(this, "pictureTaken", mediaFile.Path);
        }
Пример #16
0
        public async void SnapPic()
        {
            var piker = new MediaPicker();

            var mediafile = await piker.PickPhotoAsync();

            Debug.WriteLine(mediafile.Path);
            MessagingCenter.Send(this, "file", mediafile.Path);
        }
Пример #17
0
        public async Task PickPhoto()
        {
            FileResult result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
            {
                Title = "Wybierz zdjęcie"
            });

            await EmbedMedia(result, true);
        }
Пример #18
0
        private async void Image_Tapped(object sender, EventArgs e)
        {
            var image = await MediaPicker.PickPhotoAsync();

            if (image != null)
            {
                (BindingContext as SignUpViewModel).SelectedImage = image;
            }
        }
Пример #19
0
        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
            return(takeNew ? picker.TakePhotoAsync(new StoreCameraMediaOptions()) : picker.PickPhotoAsync());
        }
Пример #20
0
        public void SelecionarFoto()
        {
            var captura = new MediaPicker();

            captura.PickPhotoAsync().ContinueWith(e =>
            {
                MessagingCenter.Send <ICamera, string>(this, "cameraFoto", e.Result.Path);
            },
                                                  TaskScheduler.FromCurrentSynchronizationContext());
        }
 async Task PickPhotoAsync()
 {
     try
     {
         var photo = await MediaPicker.PickPhotoAsync();
         await LoadPhotoAsync(photo);
     }
     catch (Exception ex)
     {
     }
 }
Пример #22
0
        public async void SelecionarFoto()
        {
            var capturar = new MediaPicker();

            MediaFile mediaPath;

            if (capturar.IsCameraAvailable)
            {
                mediaPath = await capturar.PickPhotoAsync();
            }
        }
Пример #23
0
        public async Task <byte[]> GetFileContent()
        {
            var result = await MediaPicker.PickPhotoAsync();

            if (result == null)
            {
                return(null);
            }

            return(File.ReadAllBytes(result.FullPath));
        }
Пример #24
0
        private async void Image2_Clicked(object sender, EventArgs e)
        {
            if (compatibleMode)
            {
                photoFile2.Clear();
                FileResult file = await MediaPicker.PickPhotoAsync();

                if (file == null)
                {
                    Image2.Source = null;
                    return;
                }
                else
                {
                    photoFile2.Add(file);
                    Image2.Source = photoFile2[0].FullPath;
                }
            }
            else
            {
                photoFile2.Clear();
                IEnumerable <FileResult> files = await FilePicker.PickMultipleAsync();   //可选取其他文件作为里图

                if (files == null)
                {
                    Image2.Source = null;
                    return;
                }

                foreach (FileResult file in files)
                {
                    photoFile2.Add(file);
                }
                photoFile2.Reverse();   //选取器多选是先选的排在最后,我们要的是先选在前,所以颠倒排序一下
                if (photoFile2.Count == 1)
                {
                    string extension = photoFile2[0].FileName.Substring(photoFile2[0].FileName.LastIndexOf(".") + 1).ToLower();
                    if (extension == "png" || extension == "jpg" || extension == "jpeg" || extension == "bmp" || extension == "gif")
                    {
                        Image2.Source = photoFile2[0].FullPath;
                    }
                    else
                    {
                        Image2.Source = ImageSource.FromResource("WarFactory.Resources.File.png");
                    }
                }
                else
                {
                    Image2.Source = ImageSource.FromResource("WarFactory.Resources.Images.png");
                }
            }

            LabelTips2.Text = "";
        }
Пример #25
0
        public async Task <string> TakePhotoAsync(object context)
        {
            try {
                var mediaPicker = new MediaPicker();
                var mediaFile   = await mediaPicker.PickPhotoAsync();

                return(mediaFile.Path);
            }
            catch (TaskCanceledException) {
                return(null);
            }
        }
Пример #26
0
        public async void SelecionarFoto()
        {
            var capturar = new MediaPicker();

            MediaFile mediaPath;

            if (capturar.IsCameraAvailable)
            {
                mediaPath = await capturar.PickPhotoAsync();

                System.Diagnostics.Debug.WriteLine(mediaPath.Path);
            }
        }
Пример #27
0
        private async void SelectImage()
        {
            var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
            {
                Title = AppResource.please_pick_a_photo
            });

            if (result != null)
            {
                //var stream = await result.OpenReadAsync();
                PathPicture = result.FullPath;
            }
        }
Пример #28
0
        private void UploadFoto()
        {
            try {
                MediaPicker mediaPicker = new MediaPicker();

                mediaPicker.PickPhotoAsync().ContinueWith(t => {
                    MediaFile file = t.Result;
                    CallbackPhotoMade(t.Result);
                }, TaskScheduler.FromCurrentSynchronizationContext());
            } catch (Exception ex) {
                Insights.Report(ex);
            }
        }
Пример #29
0
        private async void GetAPhotoAsync(object sender, EventArgs e)
        {
            var photo = await MediaPicker.PickPhotoAsync();

            if (photo != null)
            {
                var stream = await photo.OpenReadAsync();

                image.Source = ImageSource.FromStream(() => { return(stream); });
                FilePath     = photo.FullPath;
                FileStream   = stream;
            }
        }
Пример #30
0
        async void GetPhotoAsync()
        {
            try
            {
                var photo = await MediaPicker.PickPhotoAsync();

                ImagePath = photo.FullPath;
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.Alert("Сообщение об ошибке", ex.Message, "OK");
            }
        }
		void MediaChooser (object sender, UIButtonEventArgs e)
		{
			if (e.ButtonIndex == 1)
			{
			
				System.Console.WriteLine ("Camera");

				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);
								imageView.Image = new UIImage(t.Result.Path);
								}
							, TaskScheduler.FromCurrentSynchronizationContext()
							);
				}

				image_bytes  = UIImageViewToByteArray(imageView.Image);

				image.Dispose ();

			} 
			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());
				}

			//MOKEEEEEEEEE UIImage To ByteArray
			image = imageView.Image;

			image_bytes = UIImageViewToByteArray(image);

			image.Dispose ();
		}