Beispiel #1
0
        public void UpdateCameraOption(CameraOptions option)
        {
            var devices = AVCaptureDeviceDiscoverySession.Create(
                new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera, AVCaptureDeviceType.BuiltInDualCamera },
                AVMediaType.Video,
                AVCaptureDevicePosition.Unspecified
                );

            var cameraPosition = (option == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
            var device         = devices.Devices.FirstOrDefault(d => d.Position == cameraPosition);

            if (device != null)
            {
                var lVideoDeviceInput = AVCaptureDeviceInput.FromDevice(device);

                captureSession.BeginConfiguration();

                // Remove the existing device input first, since using the front and back camera simultaneously is not supported.
                captureSession.RemoveInput(videoDeviceInput);

                if (captureSession.CanAddInput(lVideoDeviceInput))
                {
                    captureSession.AddInput(lVideoDeviceInput);
                    videoDeviceInput = lVideoDeviceInput;
                }
                else
                {
                    captureSession.AddInput(videoDeviceInput);
                }

                captureSession.CommitConfiguration();
            }
        }
Beispiel #2
0
        protected override void OnElementChanged(ElementChangedEventArgs <ICMXamarin.Views.CameraPreview> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                app             = Application.Current;
                app.Suspending += OnAppSuspending;
                app.Resuming   += OnAppResuming;
                HardwareButtons.BackPressed += OnBackButtonPressed;

                cameraOptions          = e.NewElement.Camera;
                PreviewControl         = new CaptureElement();
                PreviewControl.Stretch = Stretch.UniformToFill;

                InitializeAsync();
                SetNativeControl(PreviewControl);
            }
            if (e.OldElement != null)
            {
                // Unsubscribe
                Tapped -= OnCameraPreviewTapped;
            }
            if (e.NewElement != null)
            {
                // Subscribe
                Tapped    += OnCameraPreviewTapped;
                CamPreview = e.NewElement;
            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs <CameraPreview> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                app             = Windows.UI.Xaml.Application.Current;
                app.Suspending += OnAppSuspending;
                app.Resuming   += OnAppResuming;

                element                = e.NewElement;
                cameraOptions          = element.Camera;
                captureElement         = new CaptureElement();
                captureElement.Stretch = Stretch.UniformToFill;

                SetupCamera();
                SetNativeControl(captureElement);
            }
            if (e.OldElement != null)
            {
                capturePathCallbackAction = null;
                element.Capture           = null;
                element.StartCamera       = null;
                element.StopCamera        = null;
                captureFilename           = "temp";
            }
            if (e.NewElement != null)
            {
                capturePathCallbackAction = element.CapturePathCallback;
                element.Capture           = new Command(() => CaptureToFile());
                element.StartCamera       = new Command(async() => await StartPreviewAsync());
                element.StopCamera        = new Command(async() => await StopPreviewAsync());
                captureFilename           = element.Filename;
            }
        }
Beispiel #4
0
        protected override void OnElementChanged(ElementChangedEventArgs <CameraPreview> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                app             = Application.Current;
                app.Suspending += OnAppSuspending;
                app.Resuming   += OnAppResuming;

                cameraOptions          = e.NewElement.Camera;
                captureElement         = new CaptureElement();
                captureElement.Stretch = Stretch.UniformToFill;

                SetupCamera();
                SetNativeControl(captureElement);
            }
            if (e.OldElement != null)
            {
                // Unsubscribe
                Tapped -= OnCameraPreviewTapped;
            }
            if (e.NewElement != null)
            {
                // Subscribe
                Tapped += OnCameraPreviewTapped;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Override to add all values from all options
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var optionValues = new List <string>
            {
                GeolocationOptions.ToString(),
                MidiOptions.ToString(),
                NotificationsOptions.ToString(),
                PushOptions.ToString(),
                SyncXhrOptions.ToString(),
                MicrophoneOptions.ToString(),
                CameraOptions.ToString(),
                MagnetometerOptions.ToString(),
                GyroscopeOptions.ToString(),
                SpeakerOptions.ToString(),
                VibrateOptions.ToString(),
                FullscreenOptions.ToString(),
                PaymentOptions.ToString(),
                AccelerometerOptions.ToString(),
                AmbientLightSensorOptions.ToString(),
                AutoplayOptions.ToString(),
                EncryptedMediaOptions.ToString(),
                PictureInPictureOptions.ToString(),
                UsbOptions.ToString(),
                VrOptions.ToString()
            };

            return(string.Join("; ", optionValues.Where(s => s.Length > 0)));
        }
        public UICameraPreview(CameraPreview camera)
        {
            cameraOptions = camera.Camera;
            _IsPreviewing = camera.IsPreviewing;
            Camera        = camera;

            CaptureSession = new AVCaptureSession();
            previewLayer   = new AVCaptureVideoPreviewLayer(CaptureSession)
            {
                Frame        = Bounds,
                VideoGravity = AVLayerVideoGravity.ResizeAspectFill
            };
            Layer.AddSublayer(previewLayer);

            Initialize();

            MessagingCenter.Subscribe <LifeCyclePayload>(this, "", (p) => {
                switch (p.Status)
                {
                case LifeCycle.OnSleep:
                    //Sleep状態になるときにリソース解放
                    Release();
                    break;

                case LifeCycle.OnResume:
                    //Resume状態になるときに初期化
                    Initialize();
                    break;
                }
            });
        }
        public UICameraPreview(CameraOptions options)
        {
            _cameraOptions = options;
            IsPreviewing   = false;

            Initialize();
        }
        public DroidCameraPreview(Context context, CameraOptions option) : base(context)
        {
            CameraOption = option;

            var path       = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var nativePath = Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments);

            // Camera Setup
            File                      = new Java.IO.File(path, "pic.jpg");
            CaptureCallback           = new CameraCaptureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this);
            mStateCallback            = new CameraStateListener(this);
            mSurfaceTextureListener   = new Camera2BasicSurfaceTextureListener(this);

            mTextureView = new Camera2Basic.AutoFitTextureView(context);
            AddView(mTextureView);

            // fill ORIENTATIONS list
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);

            State = CameraState.Stopped;
        }
Beispiel #9
0
        public UICameraPreviewAlt(CameraOptions options)
        {
            cameraOptions = options;
            IsPreviewing  = false;

            Initialise();
        }
        protected override void OnElementChanged(ElementChangedEventArgs <CameraView> e)
        {
            base.OnElementChanged(e);

            var permissions = CameraPermissions();

            _camera = new CameraDroid(Context);

            CameraOptions CameraOption = e.NewElement?.Camera ?? CameraOptions.Rear;

            if (Control == null)
            {
                if (permissions)
                {
                    _camera.OpenCamera(CameraOption);

                    SetNativeControl(_camera);
                }
                else
                {
                    MainActivity.CameraPermissionGranted += (sender, args) =>
                    {
                        _camera.OpenCamera(CameraOption);

                        SetNativeControl(_camera);
                    };
                }
            }

            if (e.NewElement != null && _camera != null)
            {
                _camera.Photo += OnPhoto;
            }
        }
Beispiel #11
0
 public UICameraPreview(CameraOptions options, SpeedOptions sOptions, string fileUrl, CameraModes mode)
 {
     cameraOptions = options;
     speedOptions  = sOptions;
     CameraMode    = mode;
     IsPreviewing  = false;
     fileUrl       = FileUrl;
     Initialize();
     //SetupUserInterface();
 }
Beispiel #12
0
        public UIAugmentedRealityView(CameraOptions options)
        {
            cameraOptions = options;
            IsPreviewing  = false;
            Initialize();

            projectionTransform = new float[16];
            MathHelpers.CreateProjectionMatrix(ref projectionTransform, (float)(UIScreen.MainScreen.Bounds.Size.Width * 1.0 / UIScreen.MainScreen.Bounds.Size.Height), 0.25f, 1000.0f);

            StartLocationListening();
            StartDeviceMotion();
        }
Beispiel #13
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindowViewModel()
        {
            _kinectManager            = new KinectManager();
            _cameraOptions            = new CameraOptions();
            _jointsOption             = new JointsOption();
            _blenderOptions           = new BlenderOptions();
            _originPositionAutoSetter = new OriginPositionAutoSetter(_jointsOption);
            _kinectDataManager        = new KinectDataManager(_cameraOptions, _blenderOptions, _jointsOption);
            _parameterFileManager     = new ParameterFileManager(this);

            _statusBarMessage = "";
        }
        public void UpdateCameraOption(CameraOptions option)
        {
            if (CameraOption == option)
            {
                return;
            }

            CameraOption = option;

            // TODO Implement Camera switching on Android
            Log.WriteLine(LogPriority.Warn, "CameraPreview", "Switching Cameras is not yet supported on Android");
        }
        public iOSVideoRecorder(VideoRecorder CrossPlatformRecorder, CameraOptions cameraOption, OrientationOptions orientationOption)
        {
            //Store references of recorder and options for later use
            XamRecorder       = CrossPlatformRecorder;
            CameraOption      = cameraOption;
            OrientationOption = orientationOption;

            //register for rotation events
            rotationNotifation = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, RotationCallback);

            //Init the camera
            InitCamera();
        }
        public void takePicture(string options)
        {
            try
            {
                string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                // ["quality", "destinationType", "sourceType", "targetWidth", "targetHeight", "encodingType",
                //     "mediaType", "allowEdit", "correctOrientation", "saveToPhotoAlbum" ]
                this.cameraOptions                    = new CameraOptions();
                this.cameraOptions.Quality            = int.Parse(args[0]);
                this.cameraOptions.DestinationType    = int.Parse(args[1]);
                this.cameraOptions.PictureSourceType  = int.Parse(args[2]);
                this.cameraOptions.TargetWidth        = int.Parse(args[3]);
                this.cameraOptions.TargetHeight       = int.Parse(args[4]);
                this.cameraOptions.EncodingType       = int.Parse(args[5]);
                this.cameraOptions.MediaType          = int.Parse(args[6]);
                this.cameraOptions.AllowEdit          = bool.Parse(args[7]);
                this.cameraOptions.CorrectOrientation = bool.Parse(args[8]);
                this.cameraOptions.SaveToPhotoAlbum   = bool.Parse(args[9]);

                //this.cameraOptions = String.IsNullOrEmpty(options) ?
                //        new CameraOptions() : JSON.JsonHelper.Deserialize<CameraOptions>(options);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            //TODO Check if all the options are acceptable


            if (cameraOptions.PictureSourceType == CAMERA)
            {
                cameraTask            = new CameraCaptureTask();
                cameraTask.Completed += onCameraTaskCompleted;
                cameraTask.Show();
            }
            else
            {
                if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
                {
                    photoChooserTask            = new PhotoChooserTask();
                    photoChooserTask.Completed += onPickerTaskCompleted;
                    photoChooserTask.Show();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
        }
        /// <summary>
        /// Get corresponding system camera id for the Camera Options
        /// </summary>
        /// <param name="cameraIds"></param>
        /// <param name="cameraOptions"></param>
        /// <returns></returns>
        private string GetCameraId(string[] cameraIds, CameraOptions cameraOptions)
        {
            if (cameraOptions == CameraOptions.Back && cameraIds.Length > 0)
            {
                return(cameraIds.First());
            }
            else if (cameraOptions == CameraOptions.Front && cameraIds.Length > 1)
            {
                // camera id for secondary camera is 2
                return(cameraIds.Skip(1).First());
            }

            throw new CameraViewException("Requested camera not available in the system");
        }
Beispiel #18
0
        public UICameraPreview(CameraPreview camera)
        {
            cameraOptions = camera.Camera;
            _IsPreviewing = true;
            Camera        = camera;

            CaptureSession = new AVCaptureSession();
            previewLayer   = new AVCaptureVideoPreviewLayer(CaptureSession)
            {
                Frame        = Bounds,
                VideoGravity = AVLayerVideoGravity.ResizeAspectFill
            };
            Layer.AddSublayer(previewLayer);

            Initialize();
        }
Beispiel #19
0
        public void OpenCamera(CameraOptions options)
        {
            if (_context == null || OpeningCamera)
            {
                return;
            }

            OpeningCamera = true;

            _manager = (CameraManager)_context.GetSystemService(Context.CameraService);

            var cameraId = _manager.GetCameraIdList()[(int)options];

            var characteristics = _manager.GetCameraCharacteristics(cameraId);
            var map             = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);

            _previewSize = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture)))[0];

            _manager.OpenCamera(cameraId, _mStateListener, null);
        }
        public void UpdateCameraOption(CameraOptions option)
        {
            if (CameraOption == option)
            {
                return;
            }

            CameraOption = option;

            var cameraPosition = (CameraOption == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
            var device         = GetCameraForOrientation(cameraPosition);

            ConfigureCameraForDevice(device);

            CaptureSession.BeginConfiguration();
            CaptureSession.RemoveInput(captureDeviceInput);
            captureDeviceInput = AVCaptureDeviceInput.FromDevice(device);
            CaptureSession.AddInput(captureDeviceInput);
            CaptureSession.CommitConfiguration();
        }
        public DroidCameraPreview(Context context, CameraOptions option) : base(context)
        {
            CameraOption = option;

            // Camera Setup
            File                      = new Java.IO.File(Context.GetExternalFilesDir(null), "pic.jpg");
            CaptureCallback           = new CameraCaptureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this, File);
            mStateCallback            = new CameraStateListener(this);
            mSurfaceTextureListener   = new Camera2BasicSurfaceTextureListener(this);

            mTextureView = new Camera2Basic.AutoFitTextureView(context);
            AddView(mTextureView);

            // fill ORIENTATIONS list
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);
        }
Beispiel #22
0
        public XCameraCaptureView(Context context, CameraOptions option) : base(context)
        {
            cameraOption = option;

            // TODO Move to Initialize
            mStateCallback          = new CameraStateListener(this);
            mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this);

            // fill ORIENTATIONS list
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270);
            ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180);

            mTextureView = new AutoFitTextureView(context);
            AddView(mTextureView);

            var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            File                      = new File(path, "pic.jpg");
            CaptureCallback           = new CameraCaptureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this);
        }
Beispiel #23
0
        public AndroidVideoRecorder(Context context, VideoRecorder CrossPlatformRecorder, CameraOptions cameraOption, OrientationOptions orientationOption)
            : base(context)
        {
            //Store references of recorder and options for later use
            XamRecorder       = CrossPlatformRecorder;
            CameraOption      = cameraOption;
            OrientationOption = orientationOption;

            if (IsCameraAvailable)
            {
                //Create the surface for drawing on
                surfaceView = new SurfaceView(context);
                AddView(surfaceView);
                holder = surfaceView.Holder;
                holder.AddCallback(this);

                windowManager = Context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();

                InitCamera();

                XamRecorder.IsPreviewing = false;
                XamRecorder.IsRecording  = false;
            }
        }
Beispiel #24
0
    private void ChangeCameraSettings()
    {
        switch (cameraOptions)
        {
        case CameraOptions.Custom:
            //positionOffset = new Vector2(0,0);
            //xRotation = -90f;
            //distance = 10f;
            ApplyCameraChanges();
            break;

        case CameraOptions.HalfAngle:
            cameraPosOffset = new Vector2(0, 0);
            cameraXRotation = 45f;
            cameraDistance  = 10f;
            ApplyCameraChanges();
            privateState = CameraOptions.HalfAngle;
            break;

        case CameraOptions.SideView:
            cameraPosOffset = new Vector2(0, 0);
            cameraXRotation = 0f;
            cameraDistance  = 10f;
            ApplyCameraChanges();
            privateState = CameraOptions.SideView;
            break;

        case CameraOptions.TopDown:
            cameraPosOffset = new Vector2(0, 0);
            cameraXRotation = 90f;
            cameraDistance  = 10f;
            ApplyCameraChanges();
            privateState = CameraOptions.TopDown;
            break;
        }
    }
Beispiel #25
0
        public void getPicture(string options)
        {
            try
            {
                this.cameraOptions = String.IsNullOrEmpty(options) ?
                                     new CameraOptions() : JSON.JsonHelper.Deserialize <CameraOptions>(options);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            //TODO Check if all the options are acceptable


            if (cameraOptions.PictureSourceType == CAMERA)
            {
                cameraTask            = new CameraCaptureTask();
                cameraTask.Completed += onTaskCompleted;
                cameraTask.Show();
            }
            else
            {
                if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
                {
                    photoChooserTask            = new PhotoChooserTask();
                    photoChooserTask.Completed += onTaskCompleted;
                    photoChooserTask.Show();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
        }
        public void getPicture(string options)
        {
            try
            {
                this.cameraOptions = String.IsNullOrEmpty(options) ?
                        new CameraOptions() : JSON.JsonHelper.Deserialize<CameraOptions>(options);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            // see if value is in range.
            //
            if (0 != (~(PHOTOLIBRARY | CAMERA | SAVEDPHOTOALBUM) & this.cameraOptions.PictureSourceType)) {
                DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                return;
            }

            bool showCamera = (cameraOptions.PictureSourceType & CAMERA) == CAMERA;

            if (0 != (this.cameraOptions.PictureSourceType & SAVEDPHOTOALBUM) || this.cameraOptions.PictureSourceType == PHOTOLIBRARY)
            {
                photoChooserTask = new PhotoChooserTask();
                photoChooserTask.ShowCamera = showCamera;
                photoChooserTask.Completed += onTaskCompleted;
                photoChooserTask.Show();
            }
            else if (showCamera)
            {
                cameraTask = new CameraCaptureTask();
                cameraTask.Completed += onTaskCompleted;
                cameraTask.Show();
            }
            else
            {
            }
        }
Beispiel #27
0
        public async void takePicture(string options)
        {
            try
            {
                string[] args = JSON.JsonHelper.Deserialize <string[]>(options);
                this.cameraOptions                    = new CameraOptions();
                this.cameraOptions.Quality            = int.Parse(args[0]);
                this.cameraOptions.DestinationType    = int.Parse(args[1]);
                this.cameraOptions.PictureSourceType  = int.Parse(args[2]);
                this.cameraOptions.TargetWidth        = int.Parse(args[3]);
                this.cameraOptions.TargetHeight       = int.Parse(args[4]);
                this.cameraOptions.EncodingType       = int.Parse(args[5]);
                this.cameraOptions.MediaType          = int.Parse(args[6]);
                this.cameraOptions.AllowEdit          = bool.Parse(args[7]);
                this.cameraOptions.CorrectOrientation = bool.Parse(args[8]);
                this.cameraOptions.SaveToPhotoAlbum   = bool.Parse(args[9]);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }
            if (cameraOptions.PictureSourceType == CAMERA)
            {
                cameraTask = new CameraCaptureUI();
                StorageFile picture = await cameraTask.CaptureFileAsync(CameraCaptureUIMode.Photo);

                if (picture != null)
                {
                    string imagePathOrContent = string.Empty;
                    //save image to picture library
                    if (cameraOptions.SaveToPhotoAlbum)
                    {
                        await picture.CopyAsync(Windows.Storage.KnownFolders.PicturesLibrary, picture.Name, Windows.Storage.NameCollisionOption.GenerateUniqueName);
                    }
                    try
                    {
                        var readStream = await picture.OpenAsync(FileAccessMode.Read);

                        var inputStream    = readStream.GetInputStreamAt(0);
                        var dataReaderFile = new DataReader(inputStream);
                        var numByteLoaded  = await dataReaderFile.LoadAsync((uint)readStream.Size);

                        var byteString        = new byte[numByteLoaded];
                        var imageBase64String = "";
                        dataReaderFile.ReadBytes(byteString);
                        imageBase64String  = Convert.ToBase64String(byteString);
                        imagePathOrContent = imageBase64String;
                        DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));
                    }
                    catch (Exception)
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image."));
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
            else
            {
                if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
                {
                    photoChooserTask = new FileOpenPicker();
                    //var picturesLib = Windows.Storage.KnownFolders.PicturesLibrary;
                    photoChooserTask.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                    photoChooserTask.FileTypeFilter.Add(".png");
                    photoChooserTask.FileTypeFilter.Add(".jpg");
                    photoChooserTask.FileTypeFilter.Add(".jpeg");
                    StorageFile selectedfile = await photoChooserTask.PickSingleFileAsync();

                    if (selectedfile != null)
                    {
                        try
                        {
                            string imagePathOrContent = string.Empty;
                            var    readStream         = await selectedfile.OpenAsync(FileAccessMode.Read);

                            var inputStream    = readStream.GetInputStreamAt(0);
                            var dataReaderFile = new DataReader(inputStream);
                            var numByteLoaded  = await dataReaderFile.LoadAsync((uint)readStream.Size);

                            var byteString        = new byte[numByteLoaded];
                            var imageBase64String = "";
                            dataReaderFile.ReadBytes(byteString);
                            imageBase64String  = Convert.ToBase64String(byteString);
                            imagePathOrContent = imageBase64String;
                            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));
                        }
                        catch (Exception)
                        {
                            DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image."));
                        }
                    }
                    else
                    {
                        DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                    }
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
        }
        public void takePicture(string options)
        {
            try
            {
                string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
                // ["quality", "destinationType", "sourceType", "targetWidth", "targetHeight", "encodingType",
                //     "mediaType", "allowEdit", "correctOrientation", "saveToPhotoAlbum" ]
                cameraOptions = new CameraOptions();
                cameraOptions.Quality = int.Parse(args[0]);
                cameraOptions.DestinationType = int.Parse(args[1]);
                cameraOptions.PictureSourceType = int.Parse(args[2]);
                cameraOptions.TargetWidth = int.Parse(args[3]);
                cameraOptions.TargetHeight = int.Parse(args[4]);
                cameraOptions.EncodingType = int.Parse(args[5]);
                cameraOptions.MediaType = int.Parse(args[6]);
                cameraOptions.AllowEdit = bool.Parse(args[7]);
                cameraOptions.CorrectOrientation = bool.Parse(args[8]);
                cameraOptions.SaveToPhotoAlbum = bool.Parse(args[9]);

                // a very large number will force the other value to be the bound
                if (cameraOptions.TargetWidth > -1 && cameraOptions.TargetHeight == -1)
                {
                    cameraOptions.TargetHeight = 100000;
                }
                else if (cameraOptions.TargetHeight > -1 && cameraOptions.TargetWidth == -1)
                {
                    cameraOptions.TargetWidth = 100000;
                }
            }
            catch (Exception ex)
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            if(cameraOptions.DestinationType != Camera.FILE_URI && cameraOptions.DestinationType != Camera.DATA_URL )
            {
                DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType"));
                return;
            }

            ChooserBase<PhotoResult> chooserTask = null;
            if (cameraOptions.PictureSourceType == CAMERA)
            {
                chooserTask = new CameraCaptureTask();
            }
            else if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
            {
                chooserTask = new PhotoChooserTask();
            }
            // if chooserTask is still null, then PictureSourceType was invalid
            if (chooserTask != null)
            {
                chooserTask.Completed += onTaskCompleted;
                chooserTask.Show();
            }
            else
            {
                Debug.WriteLine("Unrecognized PictureSourceType :: " + cameraOptions.PictureSourceType.ToString());
                DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
            }
        }
Beispiel #29
0
        public void getPicture(string options)
        {
            try
            {
                this.cameraOptions = String.IsNullOrEmpty(options) ?
                        new CameraOptions() : JSON.JsonHelper.Deserialize<CameraOptions>(options);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            //TODO Check if all the options are acceptable

            if (cameraOptions.PictureSourceType == CAMERA)
            {
                cameraTask = new CameraCaptureTask();
                cameraTask.Completed += onTaskCompleted;
                cameraTask.Show();
            }
            else
            {
                if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
                {
                    photoChooserTask = new PhotoChooserTask();
                    photoChooserTask.Completed += onTaskCompleted;
                    photoChooserTask.Show();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
        }
Beispiel #30
0
		public void GetPicture(CameraOptions options, Action<string> successCallback, Action errorCallback)
		{
			if(options == null)
				options = new CameraOptions();
		
			if(!UIImagePickerController.IsSourceTypeAvailable(options.SourceType))
			{
				Debug.WriteLine ("Source type {0} isn't available.", options.SourceType);
				return;
			}
			
			pickerController = new UIImagePickerController();
			
			pickerController.AllowsEditing = options.AllowEdit;
			pickerController.SourceType = options.SourceType;
			
			pickerController.FinishedPickingMedia += delegate(object sender, UIImagePickerMediaPickedEventArgs e) {
				
				pickerController.DismissModalViewControllerAnimated(true);
				
				float quality = options.Quality / 100.0f; 
				
				var mediaType = (NSString) e.Info[new NSString("UIImagePickerControllerMediaType")];
				if(mediaType == "public.image")
				{
					// Get the image
					UIImage image = null;
					if(pickerController.AllowsEditing && e.Info[new NSString("UIImagePickerControllerEditedImage")] != null)
						image = (UIImage) e.Info[new NSString("UIImagePickerControllerEditedImage")];
					else
						image = (UIImage) e.Info[new NSString("UIImagePickerControllerOriginalImage")];
						
					var data = image.AsJPEG(quality);
					
					if(options.Destination == DestinationType.FileUri)
					{
						var basedir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".."); 
						var tmpDirectory = Path.Combine(basedir, "tmp");
						
						if (!Directory.Exists(tmpDirectory))
							Directory.CreateDirectory(tmpDirectory);
						
						string filePath;
						int i = 1;
						do {
							filePath = String.Format("{0}/photo_{1}.jpg", tmpDirectory, i++);
						}
						while (File.Exists(filePath));
						
						NSError error = null;
						if(!data.Save(filePath, false, out error))
						{
							Debug.WriteLine ("Error {0}", error.LocalizedDescription);
							errorCallback();	
						}
						else 
							successCallback(filePath);	
					}
					else
					{
						var bytearray = new Byte[data.Length];
						Marshal.Copy(data.Bytes, bytearray, 0, Convert.ToInt32(data.Length));
						successCallback(Convert.ToBase64String(bytearray));	
					}
				}
			};
			
			pickerController.Canceled += delegate(object sender, EventArgs e) {
				pickerController.DismissModalViewControllerAnimated(true);
				errorCallback();
			};
			
			viewController.PresentModalViewController(pickerController, true);
			
		}
Beispiel #31
0
        public void takePicture(string options)
        {
            try
            {
                string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
                // ["quality", "destinationType", "sourceType", "targetWidth", "targetHeight", "encodingType",
                //     "mediaType", "allowEdit", "correctOrientation", "saveToPhotoAlbum" ]
                this.cameraOptions = new CameraOptions();
                this.cameraOptions.Quality = int.Parse(args[0]);
                this.cameraOptions.DestinationType = int.Parse(args[1]);
                this.cameraOptions.PictureSourceType = int.Parse(args[2]);
                this.cameraOptions.TargetWidth = int.Parse(args[3]);
                this.cameraOptions.TargetHeight = int.Parse(args[4]);
                this.cameraOptions.EncodingType = int.Parse(args[5]);
                this.cameraOptions.MediaType = int.Parse(args[6]);
                this.cameraOptions.AllowEdit = bool.Parse(args[7]);
                this.cameraOptions.CorrectOrientation = bool.Parse(args[8]);
                this.cameraOptions.SaveToPhotoAlbum = bool.Parse(args[9]);

                //this.cameraOptions = String.IsNullOrEmpty(options) ?
                //        new CameraOptions() : JSON.JsonHelper.Deserialize<CameraOptions>(options);
            }
            catch (Exception ex)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
                return;
            }

            //TODO Check if all the options are acceptable

            if (cameraOptions.PictureSourceType == CAMERA)
            {
                cameraTask = new CameraCaptureTask();
                cameraTask.Completed += onCameraTaskCompleted;
                cameraTask.Show();
            }
            else
            {
                if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
                {
                    photoChooserTask = new PhotoChooserTask();
                    photoChooserTask.Completed += onPickerTaskCompleted;
                    photoChooserTask.Show();
                }
                else
                {
                    DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
                }
            }
        }
		public UICameraPreview (CameraOptions options)
		{
			cameraOptions = options;
			IsPreviewing = false;
			Initialize ();
		}
 public void SetCameraOption(CameraOptions cameraOptions)
 {
     this.lensFacing = (cameraOptions == CameraOptions.Front) ? LensFacing.Front : LensFacing.Back;
 }
 public NativeCameraPreview(CameraOptions options)
 {
     cameraOptions = options;
     Initialize();
 }
Beispiel #35
0
        public void GetPicture(CameraOptions options, Action <string> successCallback, Action errorCallback)
        {
            if (options == null)
            {
                options = new CameraOptions();
            }

            if (!UIImagePickerController.IsSourceTypeAvailable(options.SourceType))
            {
                Debug.WriteLine("Source type {0} isn't available.", options.SourceType);
                return;
            }

            pickerController = new UIImagePickerController();

            pickerController.AllowsEditing = options.AllowEdit;
            pickerController.SourceType    = options.SourceType;

            pickerController.FinishedPickingMedia += delegate(object sender, UIImagePickerMediaPickedEventArgs e) {
                pickerController.DismissModalViewControllerAnimated(true);

                float quality = options.Quality / 100.0f;

                var mediaType = (NSString)e.Info[new NSString("UIImagePickerControllerMediaType")];
                if (mediaType == "public.image")
                {
                    // Get the image
                    UIImage image = null;
                    if (pickerController.AllowsEditing && e.Info[new NSString("UIImagePickerControllerEditedImage")] != null)
                    {
                        image = (UIImage)e.Info[new NSString("UIImagePickerControllerEditedImage")];
                    }
                    else
                    {
                        image = (UIImage)e.Info[new NSString("UIImagePickerControllerOriginalImage")];
                    }

                    var data = image.AsJPEG(quality);

                    if (options.Destination == DestinationType.FileUri)
                    {
                        var basedir      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "..");
                        var tmpDirectory = Path.Combine(basedir, "tmp");

                        if (!Directory.Exists(tmpDirectory))
                        {
                            Directory.CreateDirectory(tmpDirectory);
                        }

                        string filePath;
                        int    i = 1;
                        do
                        {
                            filePath = String.Format("{0}/photo_{1}.jpg", tmpDirectory, i++);
                        }while (File.Exists(filePath));

                        NSError error = null;
                        if (!data.Save(filePath, false, out error))
                        {
                            Debug.WriteLine("Error {0}", error.LocalizedDescription);
                            errorCallback();
                        }
                        else
                        {
                            successCallback(filePath);
                        }
                    }
                    else
                    {
                        var bytearray = new Byte[data.Length];
                        Marshal.Copy(data.Bytes, bytearray, 0, Convert.ToInt32(data.Length));
                        successCallback(Convert.ToBase64String(bytearray));
                    }
                }
            };

            pickerController.Canceled += delegate(object sender, EventArgs e) {
                pickerController.DismissModalViewControllerAnimated(true);
                errorCallback();
            };

            viewController.PresentModalViewController(pickerController, true);
        }
Beispiel #36
0
 public NativeCameraView(CameraOptions options)
 {
     cameraOptions = options;
     IsPreviewing  = false;
     Initialize();
 }