示例#1
0
        private async Task <StorageFile> CaptureFile(CancellationToken ct, CameraCaptureUIMode mode)
        {
            await ValidateRequiredPermissions(ct);

            var mediaPickerActivity = await StartMediaPickerActivity(ct);

            // An intent to take a picture
            var takePictureIntent = new Intent(MediaStore.ActionImageCapture);

            // On some device (like nexus phone), we need to add extra to the intent to be able to get the Uri of the image
            // http://stackoverflow.com/questions/9890757/android-camera-data-intent-returns-null
            var photoUri = mediaPickerActivity.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, new ContentValues());

            takePictureIntent.PutExtra(MediaStore.ExtraOutput, photoUri);

            var result = await mediaPickerActivity.GetActivityResult(ct, takePictureIntent, CameraRequestCode);

            if (result.ResultCode != Result.Ok)
            {
                if (this.Log().IsEnabled(LogLevel.Information))
                {
                    this.Log().LogInformation($"Picture not taken. Result: {result.ResultCode}");
                }

                // No picture return null
                return(null);
            }

            return(await CreateTempImage(
                       ContextHelper.Current.ContentResolver.OpenInputStream(photoUri),
                       Path.GetExtension(new Uri(photoUri.Path, UriKind.RelativeOrAbsolute).LocalPath)
                       ));
        }
示例#2
0
        private Task <StorageFile> DoCaptureFileAsync(CameraCaptureUIMode mode)
        {
            return(Task.Run <StorageFile>(async() =>
            {
                UIApplication.SharedApplication.InvokeOnMainThread(() =>
                {
                    _pc.SourceType = UIImagePickerControllerSourceType.Camera;
                    switch (mode)
                    {
                    case CameraCaptureUIMode.Photo:
                        _pc.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
                        break;

                    case CameraCaptureUIMode.Video:
                        _pc.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
                        break;
                    }

                    UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_pc, true, null);
                });

                _handle.WaitOne();

                if (!string.IsNullOrEmpty(_filename))
                {
                    return await StorageFile.GetFileFromPathAsync(_filename);
                }
                return null;
            }));
        }
        /// <summary>
        /// This method takes a picture.
        /// Right now the parameter is not evaluated.
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <StorageFile> CaptureFileAsync(CameraCaptureUIMode mode, StoreCameraMediaOptions options)
        {
            var t = IsStopped();

            Mode = mode;
            if (Mode == CameraCaptureUIMode.Photo)
            {
                camerButton.Icon = new SymbolIcon(Symbol.Camera);
            }
            else if (Mode == CameraCaptureUIMode.Video)
            {
                camerButton.Icon = new SymbolIcon(Symbol.Video);
            }
            Options = options;
            // Create new MediaCapture
            MyMediaCapture = new MediaCapture();
            var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var backCamera = videoDevices.FirstOrDefault(
                item => item.EnclosureLocation != null &&
                item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            var frontCamera = videoDevices.FirstOrDefault(
                item => item.EnclosureLocation != null &&
                item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);

            var captureSettings = new MediaCaptureInitializationSettings();

            if (options.DefaultCamera == CameraDevice.Front && frontCamera != null)
            {
                captureSettings.VideoDeviceId = frontCamera.Id;
            }
            else if (options.DefaultCamera == CameraDevice.Rear && backCamera != null)
            {
                captureSettings.VideoDeviceId = backCamera.Id;;
            }
            await MyMediaCapture.InitializeAsync(captureSettings);

            // Assign to Xaml CaptureElement.Source and start preview
            myCaptureElement.Source = MyMediaCapture;

            // show preview
            await MyMediaCapture.StartPreviewAsync();

            // now wait until stopflag shows that someone took a picture
            await t;

            // picture has been taken
            // stop preview

            await CleanUpAsync();

            // go back
            CurrentWindow.Content = originalFrame;

            mainGrid.Children.Remove(this);

            return(file);
        }
示例#4
0
        /// <summary>
        /// Launches the CameraCaptureUI user interface.
        /// </summary>
        /// <param name="mode">Specifies whether the user interface that will be shown allows the user to capture a photo, capture a video, or capture both photos and videos.</param>
        /// <returns>When this operation completes, a StorageFile object is returned.</returns>
        public Task <StorageFile> CaptureFileAsync(CameraCaptureUIMode mode)
        {
#if __ANDROID__
            if (IsIntentAvailable())
            {
                Intent i = new Intent(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity, typeof(CameraActivity));
                Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.StartActivity(i);
                return(Task.Run <StorageFile>(async() =>
                {
                    _handle.WaitOne();
                    if (!string.IsNullOrEmpty(_path))
                    {
                        return await StorageFile.GetFileFromPathAsync(_path);
                    }

                    return null;
                }));
            }
            return(Task.FromResult <StorageFile>(null));
#elif __IOS__
            return(DoCaptureFileAsync(mode));
#elif WINDOWS_UWP || WINDOWS_APP
            return(Task.Run <StorageFile>(async() => {
                var f = await _cc.CaptureFileAsync((Windows.Media.Capture.CameraCaptureUIMode)((int)mode));
                return f == null ? null : f;
            }));
#elif WINDOWS_PHONE_APP
            if (_type10 != null)
            {
                return(Task.Run <StorageFile>(async() =>
                {
                    Type modeType = Type.GetType("Windows.Media.Capture.CameraCaptureUIMode, Windows, ContentType=WindowsRuntime");
                    object modeVal = Enum.ToObject(modeType, mode);
                    var f = await(Windows.Foundation.IAsyncOperation <Windows.Storage.StorageFile>) _type10.GetRuntimeMethod("CaptureFileAsync", new Type[] { modeType }).Invoke(ccu, new object[] { modeVal });
                    return f == null ? null : f;
                }));
            }

            return(Task.FromResult <StorageFile>(null));
#elif WINDOWS_PHONE
            _task.Show();
            return(Task.Run <StorageFile>(() =>
            {
                _handle.WaitOne();
                return (StorageFile)null;
            }));
#else
            return(Task.FromResult <StorageFile>(null));
#endif
        }
示例#5
0
        public static async Task <StorageFile> CameraCaptureAsync(bool CropEnabled, CameraCaptureUIMode cameraCaptureUIMode, Size size)
        {
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.PhotoSettings.Format        = CameraCaptureUIPhotoFormat.Jpeg;
            captureUI.VideoSettings.Format        = CameraCaptureUIVideoFormat.Mp4;
            captureUI.VideoSettings.AllowTrimming = true;
            captureUI.PhotoSettings.AllowCropping = CropEnabled;
            if (CropEnabled)
            {
                captureUI.PhotoSettings.CroppedSizeInPixels = size;
            }
            StorageFile imgFile = await captureUI.CaptureFileAsync(cameraCaptureUIMode);

            return(imgFile);
        }
示例#6
0
        public static async Task <IStorageFile> CaptureAsync
            (CameraCaptureUIMode captureMode)
        {
            var cameraUI      = new CameraCaptureUI();
            var capturedMedia = await cameraUI.CaptureFileAsync(captureMode);

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

            // Set the default save to location based on the content MIME type
            var contentType     = capturedMedia.ContentType;
            var defaultLocation = contentType.StartsWith("image")
                    ? PickerLocationId.PicturesLibrary
                    : PickerLocationId.VideosLibrary;

            // Save type options
            var fileSaveType = new KeyValuePair <String, IList <String> >(
                capturedMedia.DisplayType,
                new List <String> {
                capturedMedia.FileType
            });

            // Get the file to save the content to
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = defaultLocation,
                SuggestedFileName      = capturedMedia.Name
            };

            savePicker.FileTypeChoices.Add(fileSaveType);
            var fileToSaveTo = await savePicker.PickSaveFileAsync();

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

            // Move the file return the new file
            await capturedMedia.MoveAndReplaceAsync(fileToSaveTo);

            return(fileToSaveTo);
        }
示例#7
0
        private async Task <StorageFile> CaptureFile(CancellationToken ct, CameraCaptureUIMode mode)
        {
            UIImagePickerController picker = null;
            var cameraDelegate             = new CameraDelegate();

            if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
            {
                picker               = new UIImagePickerController();
                picker.Delegate      = cameraDelegate;
                picker.AllowsEditing = PhotoSettings.AllowCropping;

                picker.SourceType = UIImagePickerControllerSourceType.Camera;

                switch (mode)
                {
                case CameraCaptureUIMode.Photo:
                case CameraCaptureUIMode.PhotoOrVideo:
                    picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
                    break;

                case CameraCaptureUIMode.Video:
                    picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
                    break;
                }
            }
            else
            {
                // Probably running in the simulator
                if (this.Log().IsEnabled(LogLevel.Warning))
                {
                    this.Log().Warn($"'{UIImagePickerControllerSourceType.Camera}' not available - picking from albums");
                }

                picker = new LockedOrientationUIImagePickerController(DisplayInformation.AutoRotationPreferences.ToUIInterfaceOrientationMask())
                {
                    // Use the camera roll instead of crashing
                    SourceType = UIImagePickerControllerSourceType.PhotoLibrary
                };

                await ValidatePhotoLibraryAccess();
            }

            picker.Delegate = cameraDelegate;
            UIKit.UIApplication.SharedApplication.KeyWindow?.RootViewController.PresentModalViewController(picker, true);

            using (ct.Register(() => picker.DismissViewController(true, () => { }), useSynchronizationContext: true))
            {
                var result = await cameraDelegate.Task;

                if (result != null)
                {
                    var image    = result.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
                    var metadata = result.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;

                    var correctedImage = await FixOrientation(ct, image);

                    (Stream data, string extension) GetImageStream()
                    {
                        switch (PhotoSettings.Format)
                        {
                        case CameraCaptureUIPhotoFormat.Jpeg:
                            return(image.AsJPEG().AsStream(), ".jpg");

                        case CameraCaptureUIPhotoFormat.Png:
                            return(image.AsPNG().AsStream(), ".png");

                        default:
                            throw new NotSupportedException($"{PhotoSettings.Format} is not supported");
                        }
                    };

                    var(data, extension) = GetImageStream();
                    return(await CreateTempImage(data, extension));
                }
                else
                {
                    return(null);
                }
            }
        }
        /// <summary>
        /// This method takes a picture. 
        /// Right now the parameter is not evaluated.
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task<StorageFile> CaptureFileAsync(CameraCaptureUIMode mode, StoreCameraMediaOptions options)
        {
            var t = IsStopped();
            this.options = options;
            // Create new MediaCapture 
            MyMediaCapture = new MediaCapture();
            var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            var backCamera = videoDevices.FirstOrDefault(
                item => item.EnclosureLocation != null
                && item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            var frontCamera = videoDevices.FirstOrDefault(
                  item => item.EnclosureLocation != null
                  && item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);

            var captureSettings = new MediaCaptureInitializationSettings();
            if(options.DefaultCamera == CameraDevice.Front && frontCamera != null)
            {
              captureSettings.VideoDeviceId = frontCamera.Id;
            }
            else if(options.DefaultCamera == CameraDevice.Rear && backCamera != null)
            {
              captureSettings.VideoDeviceId = backCamera.Id; ;
            }
            await MyMediaCapture.InitializeAsync(captureSettings);

            // Assign to Xaml CaptureElement.Source and start preview
            myCaptureElement.Source = MyMediaCapture;

            // show preview
            await MyMediaCapture.StartPreviewAsync();

            // now wait until stopflag shows that someone took a picture
            await t;

            // picture has been taken
            // stop preview

            await CleanUpAsync();

            // go back
            CurrentWindow.Content = originalFrame;

            mainGrid.Children.Remove(this);

            return file;
        }
示例#9
0
        private async Task <StorageFile> CaptureFile(CancellationToken arg, CameraCaptureUIMode mode)

        {
            return(null);
        }