Exemple #1
0
        private void ChangeCamera()
        {
            int currCamera = int.Parse(targetCamera);

            if (camerasCount > 1)
            {
                StopBackgroundThread();
                CloseCamera();


                if (currCamera + 1 != camerasCount)
                {
                    targetCamera = (currCamera + 1).ToString();
                }
                else
                {
                    targetCamera = "0";
                }

                mCaptureCallback          = new CameraCaptureListener(this);
                mOnImageAvailableListener = new ImageAvailableListener(this, mre);

                if (int.Parse(targetCamera) == 1)
                {
                    isFaceCamera = true;
                }
                else
                {
                    isFaceCamera = false;
                }
                StartBackgroundThread();
                OpenCamera(mTextureView.Width, mTextureView.Height);
            }
        }
        void OnConfigured(object sender, CameraCaptureSessionEventArgs e)
        {
            // The camera is already closed
            if (null == cameraDevice)
            {
                return;
            }

            // When the session is ready, we start displaying the preview.
            captureSession = e.Session;
            try
            {
                // Auto focus should be continuous for camera preview.
                previewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.Edof);
                // Flash is automatically enabled when necessary. For now, we skip this.
                // SetAutoFlash(previewRequestBuilder);

                // Finally, we start displaying the camera preview.
                previewRequest = previewRequestBuilder.Build();

                if (captureListener == null)
                {
                    captureListener = new CameraCaptureListener();
                    captureListener.CaptureCompleted  += OnCaptureCompleted;
                    captureListener.CaptureProgressed += OnCaptureProgressed;
                }
                captureSession.SetRepeatingRequest(previewRequest, captureListener, backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                ex.PrintStackTrace();
            }
        }
Exemple #3
0
        public override void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            _imagesDirectory = Activity.GetExternalFilesDir(null).AbsolutePath;

            CaptureCallback = new CameraCaptureListener(this);
        }
Exemple #4
0
 public override void OnActivityCreated(Bundle savedInstanceState)
 {
     base.OnActivityCreated(savedInstanceState);
     mFile                     = new File(Activity.GetExternalFilesDir(null), "pic.jpg");
     mCaptureCallback          = new CameraCaptureListener(this);
     mOnImageAvailableListener = new ImageAvailableListener(this, mFile);
 }
Exemple #5
0
        public CameraFragment(CameraPageRenderer cpr, View view, Activity activity)
        {
            mCPR = cpr;

            mStateCallback          = new CameraStateListener(this);
            mSurfaceTextureListener = new CameraSurfaceTextureListener(this);

            Activity = activity;

            // 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 = (AutoFitTextureView)view.FindViewById(Resource.Id.texture);
            view.FindViewById(Resource.Id.snap_button).SetOnClickListener(this);
            view.FindViewById(Resource.Id.gallery_button).SetOnClickListener(this);
            mFlashButton = view.FindViewById <ImageButton>(Resource.Id.flash_button);
            mFlashButton.SetOnClickListener(this);
            view.FindViewById(Resource.Id.back_button).SetOnClickListener(this);
            ImageDisplay = view.FindViewById <ImageView>(Resource.Id.img_display);
            roi          = view.FindViewById <ImageView>(Resource.Id.roiView);

            mCaptureCallback          = new CameraCaptureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this);
            flashMenuListner          = new FlashMenuListener(this);
            mFlashMode = 0;
        }
        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;
        }
Exemple #7
0
        protected async override void OnElementChanged(ElementChangedEventArgs <CameraPreview> e)
        {
            if (Xamarin.Forms.DesignMode.IsDesignModeEnabled)
            {
                return;
            }

            if (e.OldElement != null)             // Clear old element event
            {
            }

            if (e.NewElement != null)
            {
                await RequestCameraPermission.RequestPermissionsAsync();

                e.NewElement.StartRecording = (() => { TakePicture(); });
                e.NewElement.StopRecording  = (() => { CloseCamera(); });

                if (Control == null)
                {
                    Activity    = this.Context as Activity;
                    frameLayout = new FrameLayout(Context);
                    frameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent);

                    autoFitTextureView = new AutoFitTextureView(Context);
                    autoFitTextureView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent);

                    frameLayout.AddView(autoFitTextureView);
                    SetNativeControl(frameLayout);
                }

                mTextureView            = Control.GetChildAt(0) as AutoFitTextureView;
                mStateCallback          = new CameraStateListener(this);
                mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this, autoFitTextureView);


                //mFile = new File(Activity.GetExternalFilesDir(null), $"{Element.Filename}.jpg");
                //var path = System.IO.Path.Combine(
                //        System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
                //        $"{Element.Filename}"
                //);
                string pathyo = DependencyService.Get <IMediaFolder>().Path;
                var    path   = System.IO.Path.Combine(
                    pathyo,
                    Element.Filename);

                mFile = new File(
                    path
                    );
                mCaptureCallback          = new CameraCaptureListener(this);
                mOnImageAvailableListener = new ImageAvailableListener(this, mFile);

                StartTheCamera();
            }

            base.OnElementChanged(e);
        }
 public CameraFeedRenderer(Context context) : base(context)
 {
     cameraManager             = (CameraManager)Context.GetSystemService(Context.CameraService);
     windowManager             = Context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
     StateCallback             = new CameraStateCallback(this);
     SessionCallback           = new CameraCaptureSessionCallback(this);
     CaptureListener           = new CameraCaptureListener(this);
     CameraImageReaderListener = new CameraImageListener(this);
     OrientationEventListener  = new CameraPageOrientationEventListener(this, Context, global::Android.Hardware.SensorDelay.Normal);
 }
Exemple #9
0
        public override async void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            mCaptureCallback = new CameraCaptureListener(this);

            var meterSettings = new MeterReader.Xamarin.MeterReaderSettings(new Tesseract.Droid.TesseractApi(Context, Tesseract.Droid.AssetsDeployment.OncePerInitialization))
            {
                DarkSectors = mSectorsAreDark
            };

            mMeterReader = new MeterReader.Xamarin.MeterReader(meterSettings);
            await mMeterReader.Init();
        }
        protected override void OnElementChanged(ElementChangedEventArgs <CameraPreview> args)
        {
            if (DesignMode.IsDesignModeEnabled)
            {
                return;
            }

            if (args.OldElement != null) // Clear old element event
            {
            }

            if (args.NewElement != null)
            {
                args.NewElement.StartRecording = (() => { TakePicture(); });
                args.NewElement.StopRecording  = (() => { CloseCamera(); });

                if (Control == null)
                {
                    Activity = this.Context as Activity;
                    SetNativeControl(new AutoFitTextureView(Context));
                }

                _textureView            = Control as AutoFitTextureView;
                _stateCallback          = new CameraStateListener(this);
                _surfaceTextureListener = new Camera2SurfaceTextureListener(this);

                CaptureCallback = new CameraCaptureListener(this);

                _onImageAvailableListener = new ImageAvailableListener(this, Element.MediaOptions);

                _onImageAvailableListener.ImageAvailable += (s, e) =>
                {
                    Element.OnImageAvailable(e);
                };

                _orientationEventListener = new OrientationChangeListener(Context, (int rotation) => OnRotationChanged(rotation));
                _orientationEventListener.Enable();

                RotationChanged += (s, e) =>
                {
                    args.NewElement.OnRotationChanged(DeviceRotation);
                };

                StartTheCamera();
            }

            base.OnElementChanged(args);
        }
Exemple #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Intent intent = new Intent(MediaStore.ActionImageCapture);


            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) != (int)Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.Camera }, 200);
            }
            else
            {
                mStateCallback          = new CameraStateListener(this);
                mSurfaceTextureListener = new ClipperASurfaceTextureListener(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);

                SetContentView(Resource.Layout.TakingPicture);

                mTextureView = (AutoFitTextureView)FindViewById(Resource.Id.texture);
                mImageView   = FindViewById <ImageView>(Resource.Id.image);


                takePictureBtn = FindViewById <ImageButton>(Resource.Id.takePictureBtn);
                flashBtn       = FindViewById <ImageButton>(Resource.Id.flashBtn);
                rotateBtn      = FindViewById <ImageButton>(Resource.Id.rotateBtn);

                acceptBtn  = FindViewById <ImageButton>(Resource.Id.doneBtn);
                discardBtn = FindViewById <ImageButton>(Resource.Id.clearBtn);

                takePictureBtn.Click += (sender, e) => TakePicture();
                rotateBtn.Click      += (sender, e) => ChangeCamera();
                flashBtn.Click       += (sender, e) => ChandeFlashMode();
                FindViewById <ImageButton>(Resource.Id.closeBtn).Click += (sender, e) => Exit();

                acceptBtn.Click  += (sender, e) => ExitWithResult();
                discardBtn.Click += (sender, e) => DiscardChanges();

                mCaptureCallback          = new CameraCaptureListener(this);
                mOnImageAvailableListener = new ImageAvailableListener(this, mre);
                mOrientationListener      = new SensorOrientationListener(this);
            }
        }
Exemple #12
0
        public CameraWidget(Context Context, ObservableCollection <File> Photos) : base(Context)
        {
            context                             = Context;
            mTextureView                        = new AutoFitTextureView(Context);
            mSurfaceTextureListener             = new Camera2BasicSurfaceTextureListener(this);
            mTextureView.SurfaceTextureListener = mSurfaceTextureListener;

            mStateCallback = new CameraStateListener(this);
            StartBackgroundThread();

            // mTextureView.SetBackgroundColor(Color.Black);

            SetBackgroundColor(Color.Black);

            mCaptureCallback          = new CameraCaptureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this, Photos, Context);
        }
        protected override void OnElementChanged(ElementChangedEventArgs <Views.Renderers.CameraPreview> e)
        {
            if (Xamarin.Forms.DesignMode.IsDesignModeEnabled)
            {
                return;
            }

            if (e.OldElement != null)             // Clear old element event
            {
            }

            if (e.NewElement != null)
            {
                e.NewElement.StartRecording = (() => { TakePicture(); });
                e.NewElement.StopRecording  = (() => { CloseCamera(); });

                if (Control == null)
                {
                    Activity = this.Context as Activity;
                    SetNativeControl(new AutoFitTextureView(Context));
                }

                mTextureView            = Control as AutoFitTextureView;
                mStateCallback          = new CameraStateListener(this);
                mSurfaceTextureListener = new Camera2BasicSurfaceTextureListener(this);

                //mFile = new File(Activity.GetExternalFilesDir(null), $"{Element.Filename}.jpg");
                //var path = System.IO.Path.Combine(
                //        System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
                //        $"{Element.Filename}"
                //);
                var path = System.IO.Path.Combine(
                    DependencyService.Get <IMediaFolder>().Path,
                    Element.Filename);
                mFile = new File(
                    path
                    );
                mCaptureCallback          = new CameraCaptureListener(this);
                mOnImageAvailableListener = new ImageAvailableListener(this, mFile);

                StartTheCamera();
            }

            base.OnElementChanged(e);
        }
Exemple #14
0
        public async Task <Stream> TakePhotoAsync()
        {
            var shutterListener = new CameraShutterListener();
            var rawHandler      = new CameraCaptureListener();
            var jpegHandler     = new CameraCaptureListener();

            var frontCamera = Camera.Open(1);

            frontCamera.TakePicture(shutterListener, rawHandler, jpegHandler);

            var image = jpegHandler.ImageData;

            var stream = new MemoryStream(image)
            {
                Position = 0
            };

            return(stream);
        }
        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);
        }
Exemple #16
0
        // Lock the focus as the first step for a still image capture.
        private void LockFocus()
        {
            try
            {
                // This is how to tell the camera to lock focus.
                //mPreviewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
                // Tell #mCaptureCallback to wait for the lock.
                mState = STATE_WAITING_LOCK;

                mCaptureCallback = new CameraCaptureListener()
                {
                    Owner = this, File = mFile
                };

                mCaptureSession.Capture(mPreviewRequest, mCaptureCallback,
                                        mBackgroundHandler);
            }
            catch (CameraAccessException e)
            {
                e.PrintStackTrace();
            }
        }
Exemple #17
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);
        }
        /// <summary>
        /// Takes a picture.
        /// </summary>
        private void TakePicture()
        {
            try
            {
                Activity activity = Activity;
                if (activity == null || mCameraDevice == null)
                {
                    return;
                }
                CameraManager manager = (CameraManager)activity.GetSystemService(Context.CameraService);

                // Pick the best JPEG size that can be captures with this CameraDevice
                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id);
                Size[] jpegSizes = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }
                int width  = 640;
                int height = 480;
                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    width  = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;
                }

                // We use an ImageReader to get a JPEG from CameraDevice
                // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                ImageReader    reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface>(2);
                outputSurfaces.Add(reader.Surface);
                outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));

                CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                SetUpCaptureRequestBuilder(captureBuilder);
                // Orientation
                SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
                captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));

                // Output file
                File file = new File(activity.GetExternalFilesDir(null), "pic.jpg");

                // This listener is called when an image is ready in ImageReader
                // Right click on ImageAvailableListener in your IDE and go to its definition
                ImageAvailableListener readerListener = new ImageAvailableListener()
                {
                    File = file
                };

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                // Right click on CameraCaptureListener in your IDE and go to its definition
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    Fragment = this, File = file
                };

                mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                {
                    OnConfiguredAction = (CameraCaptureSession session) => {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException ex) {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
            }
        }
        // Capture a still picture. This method should be called when we get a response in
        // {@link #mCaptureCallback} from both {@link #lockFocus()}.
        public void CaptureStillPicture()
        {
            try
            {
                var activity = Activity;
                if (capturing || null == activity || null == MCameraDevice)
                {
                    return;
                }
                capturing = true;
                string id = null;

                if (((CameraActivity)Activity).activityId != -1)
                {
                    id = ((CameraActivity)Activity).activityId.ToString();
                }

                File mFile = new File(
                    Common.LocalData.Storage.GetCacheFolder(id),
                    DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss-fff", CultureInfo.InvariantCulture) + ".jpg");

                ImageReader    reader         = ImageReader.NewInstance(jpegSize.Width, jpegSize.Height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface> {
                    reader.Surface
                };

                CaptureRequest.Builder captureBuilder = MCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto));
                SetAutoFlash(captureBuilder);

                // Orientation
                int rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
                captureBuilder.Set(CaptureRequest.JpegOrientation, GetOrientation(rotation));

                // This listener is called when an image is ready in ImageReader
                ImageAvailableListener imageAvailableListener = new ImageAvailableListener(this, mFile);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    context = Activity
                };

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(imageAvailableListener, backgroundHandler);

                MCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener(
                                                       (session) => { System.Console.WriteLine("Failed to setup camera session:" + session); })
                {
                    OnConfiguredAction = (CameraCaptureSession session) =>
                    {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException e)
            {
                e.PrintStackTrace();
            }
        }
Exemple #20
0
        private void TakePhoto()
        {
            if (_context == null || CameraDevice == null)
            {
                return;
            }

            var characteristics = _manager.GetCameraCharacteristics(CameraDevice.Id);

            Size[] jpegSizes = null;
            if (characteristics != null)
            {
                jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
            }
            var width  = 480;
            var height = 640;

            if (jpegSizes != null && jpegSizes.Length > 0)
            {
                width  = jpegSizes[0].Width;
                height = jpegSizes[0].Height;
            }

            var reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
            var outputSurfaces = new List <Surface>(2)
            {
                reader.Surface, new Surface(_viewSurface)
            };

            var captureBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);

            captureBuilder.AddTarget(reader.Surface);
            captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto));

            var windowManager = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            var rotation      = windowManager.DefaultDisplay.Rotation;

            captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(Orientations.Get((int)rotation)));

            var readerListener = new ImageAvailableListener();

            readerListener.Photo += (sender, buffer) =>
            {
                Photo?.Invoke(this, ImageSource.FromStream(() => new MemoryStream(buffer)));
            };

            var thread = new HandlerThread("CameraPicture");

            thread.Start();
            var backgroundHandler = new Handler(thread.Looper);

            reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

            var captureListener = new CameraCaptureListener();

            captureListener.PhotoComplete += (sender, e) =>
            {
                StartPreview();
            };

            CameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener
            {
                OnConfiguredAction = session =>
                {
                    try
                    {
                        _previewSession = session;
                        session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                    }
                    catch (CameraAccessException ex)
                    {
                        Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                    }
                }
            }, backgroundHandler);
        }
Exemple #21
0
        private void TakePicture()
        {
            this.tracer.Debug("TakePicture");

            try
            {
                Activity activity = this.Activity;
                if (activity == null || this.cameraDevice == null)
                {
                    return;
                }

                var cameraManager = (CameraManager)activity.GetSystemService(Context.CameraService);

                // Pick the best JPEG size that can be captures with this CameraDevice
                var    characteristics = cameraManager.GetCameraCharacteristics(this.cameraDevice.Id);
                Size[] jpegSizes       = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }

                int width  = 640;
                int height = 480;
                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    width  = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;

                    this.tracer.Debug("TakePicture: Found {0} jpegSizes. Selected {1}x{2}px.", jpegSizes.Count(), width, height);
                }

                // We use an ImageReader to get a JPEG from CameraDevice
                // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                var reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                var outputSurfaces = new List <Surface>(2);
                outputSurfaces.Add(reader.Surface);
                outputSurfaces.Add(new Surface(this.autoFitTextureView.SurfaceTexture));

                var captureBuilder = this.cameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                this.SetUpCaptureRequestBuilder(captureBuilder);

                // Orientation
                var rotation = activity.WindowManager.DefaultDisplay.Rotation;
                captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(Orientations.Get((int)rotation)));

                // Output file
                var combined = System.IO.Path.Combine(activity.GetExternalFilesDir(null).AbsolutePath, this.path);
                var folder   = new File(combined);
                if (!folder.Exists())
                {
                    if (!folder.Mkdirs())
                    {
                        throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?");
                    }
                }

                this.tracer.Debug("TakePicture: Path.Combine={0}", combined);
                var file = new File(combined, this.targetFilename);
                this.tracer.Debug("TakePicture: File={0}", file.AbsolutePath);

                // This listener is called when an image is ready in ImageReader
                var readerListener = new ImageAvailableListener {
                    File = file
                };

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                var thread = new HandlerThread("CameraPicture");
                thread.Start();
                var backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                var captureListener = new CameraCaptureListener {
                    Fragment = this, File = file
                };

                this.cameraDevice.CreateCaptureSession(
                    outputSurfaces,
                    new CameraCaptureStateListener
                {
                    OnConfiguredAction = (CameraCaptureSession session) =>
                    {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            this.tracer.Exception(ex, "Capture session error.");
                        }
                    }
                },
                    backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                this.tracer.Exception(ex, "Failed to take picture.");
            }
        }
		/// <summary>
		/// Takes a picture.
		/// </summary>
		private void TakePicture()
		{
			try 
			{
				Activity activity = Activity;
				if (activity == null || mCameraDevice == null) {
					return;
				}
				CameraManager manager = (CameraManager) activity.GetSystemService(Context.CameraService);

				// Pick the best JPEG size that can be captures with this CameraDevice
				CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id);
				Size[] jpegSizes = null;
				if (characteristics != null)
				{
					jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
				}
				int width = 640;
				int height = 480;
				if (jpegSizes != null && jpegSizes.Length > 0)
				{
					width = jpegSizes[0].Width;
					height = jpegSizes[0].Height;
				}

				// We use an ImageReader to get a JPEG from CameraDevice
				// Here, we create a new ImageReader and prepare its Surface as an output from the camera
				ImageReader reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
				List<Surface> outputSurfaces = new List<Surface>(2);
				outputSurfaces.Add(reader.Surface);
				outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));

				CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
				captureBuilder.AddTarget(reader.Surface);
				SetUpCaptureRequestBuilder(captureBuilder);
				// Orientation
				SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
				captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));

				// Output file
				File file = new File(activity.GetExternalFilesDir(null), "pic.jpg");

				// This listener is called when an image is ready in ImageReader 
				// Right click on ImageAvailableListener in your IDE and go to its definition
				ImageAvailableListener readerListener = new ImageAvailableListener() { File = file };

				// We create a Handler since we want to handle the resulting JPEG in a background thread
				HandlerThread thread = new HandlerThread("CameraPicture");
				thread.Start();
				Handler backgroundHandler = new Handler(thread.Looper);
				reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

				//This listener is called when the capture is completed
				// Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
				// Right click on CameraCaptureListener in your IDE and go to its definition
				CameraCaptureListener captureListener = new CameraCaptureListener() { Fragment = this, File = file };

				mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
					{
						OnConfiguredAction = (CameraCaptureSession session) => {
							try 
							{
								session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
							}
							catch (Exception ex)
							{
								Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
							}
						}
					}, backgroundHandler );
			}
			catch (Exception ex) {
				Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
			}
		}
Exemple #23
0
        private void TakePicture()
        {
            try
            {
                Activity activity = Activity;
                if(activity == null|| mCameraDevice == null)
                    return;

                Size[] jpegSizes = null;
                if(cCharacteristics != null)
                    jpegSizes = ((StreamConfigurationMap) cCharacteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);

                int width = 640;
                int height = 480;

                if(jpegSizes != null && jpegSizes.Length > 0)
                {
                    width = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;
                }

                //ImageReader reader = ImageReader.NewInstance(width,height,ImageFormatType.Jpeg, 1);
                ImageReader multiReader = ImageReader.NewInstance(width,height,ImageFormatType.Jpeg, 1000);

                List<Surface> outputSurfaces = new List<Surface>(3);
                //outputSurfaces.Add(reader.Surface);
                outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));
                outputSurfaces.Add(multiReader.Surface);

                //just take each image and add it to a multiple image Image reader: new imageReader.newInstance(width, height, ImageFormatType.Jpeg, NumberOfImages)

                CaptureRequest.Builder crBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                crBuilder.AddTarget(outputSurfaces[0]);
                crBuilder.AddTarget(outputSurfaces[1]);
                //crBuilder.AddTarget(outputSurfaces[2]);

                SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
                crBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation)));

                File file = new File(activity.GetExternalFilesDir(null), count + ".jpg");
                count++;

                ImageAvailableListener readerListener = new ImageAvailableListener() { File = file };;

                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                multiReader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                CameraCaptureListener captureListener = new CameraCaptureListener() {Fragment = this, File = file};

                mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                    {
                        OnConfiguredAction = (CameraCaptureSession session) => {
                            try
                            {
                                List<CaptureRequest> requests = new List<CaptureRequest>();
                                float distance = (float)cCharacteristics.Get(CameraCharacteristics.LensInfoMinimumFocusDistance);
                                //for(float distance = (float)cCharacteristics.Get(CameraCharacteristics.LensInfoMinimumFocusDistance); distance > 0.00769230769; distance /= 2)
                                for(int i = 0; i < 10; i++)
                                {
                                    //crBuilder.Set(CaptureRequest.LensFocusDistance, distance);
                                    requests.Add(crBuilder.Build());
                                    Log.Debug("CaptureRequest", "Added new captureRequst");
                                }

                                session.CaptureBurst(requests, captureListener, backgroundHandler);

                                Toast.MakeText (activity, "BurstCapture Complete", ToastLength.Long).Show ();
                                //session.Capture(crBuilder.Build(), captureListener, backgroundHandler);
                            }
                            catch (CameraAccessException ex)
                            {
                                Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                            }
                        }
                    }, backgroundHandler );
            }
            catch (CameraAccessException ex)
            {
                Log.WriteLine (LogPriority.Info, "Taking Picture error: ", ex.StackTrace);
            }
        }
Exemple #24
0
 public override void OnActivityCreated(Bundle savedInstanceState)
 {
     MCaptureCallback = new CameraCaptureListener(this);
     base.OnActivityCreated(savedInstanceState);
 }
Exemple #25
0
        private void TakePicture()
        {
            try
            {
                if (cameraDevice == null)
                {
                    return;
                }
                CameraManager manager = (CameraManager)GetSystemService(Context.CameraService);

                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraDevice.Id);
                Size[] jpegSizes = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }
                int width  = 640;
                int height = 480;
                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    width  = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;
                }

                ImageReader    reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface>();
                outputSurfaces.Add(reader.Surface);

                CaptureRequest.Builder captureBuilder = cameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                SetUpCaptureRequestBuilder(captureBuilder);

                DateTime now      = DateTime.Now;
                string   filePath = sessionPath + "-" + now.Day.ToString() + "." + now.Month.ToString() + "." + now.Year.ToString() + "-"
                                    + now.Hour.ToString() + "_" + now.Minute.ToString() + "_" + now.Second.ToString() + ".jpg";
                File file = new File(filePath);

                ImageAvailableListener readerListener = new ImageAvailableListener()
                {
                    File = file
                };
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    Activity = this, File = file
                };

                cameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                {
                    OnConfiguredAction = (CameraCaptureSession session) => {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
            }
        }
Exemple #26
0
        public void TakePhoto(string filename)
        {
            thumbnailfilename = filename;
            try
            {
                Activity activity = Activity;
                if (activity == null || cameraDevice == null)
                {
                    return;
                }

                // Pick the best JPEG size that can be captures with this CameraDevice
                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraDevice.Id);
                Size[] jpegSizes = null;
                if (characteristics != null)
                {
                    jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
                }
                int width  = 640;
                int height = 480;
                if (jpegSizes != null && jpegSizes.Length > 0)
                {
                    width  = jpegSizes[0].Width;
                    height = jpegSizes[0].Height;
                }

                // We use an ImageReader to get a JPEG from CameraDevice
                // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                ImageReader    reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                List <Surface> outputSurfaces = new List <Surface>
                {
                    reader.Surface
                };
                //outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture));

                CaptureRequest.Builder captureBuilder = cameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                captureBuilder.AddTarget(reader.Surface);
                //SetUpCaptureRequestBuilder(captureBuilder);
                // Orientation
                SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation;
                var mSensorOrientation      = (int)characteristics.Get(CameraCharacteristics.SensorOrientation);
                int finalOrientation        = (ORIENTATIONS.Get((int)rotation) + mSensorOrientation + 270) % 360;

                captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(finalOrientation));

                if (flashon)
                {
                    captureBuilder.Set(CaptureRequest.FlashMode, (int)FlashMode.Torch);
                }

                Rect sensor_rect = max;
                int  left        = sensor_rect.Width() / 2;
                int  right       = left;
                int  top         = sensor_rect.Height() / 2;
                int  bottom      = top;
                int  hwidth      = (int)(sensor_rect.Width() / (2.0 * zoomlev));
                int  hheight     = (int)(sensor_rect.Height() / (2.0 * zoomlev));
                left   -= hwidth;
                right  += hwidth;
                top    -= hheight;
                bottom += hheight;
                captureBuilder.Set(CaptureRequest.ScalerCropRegion, new Rect(left, top, right, bottom));
                // Output file
                //File file = new File(activity.GetExternalFilesDir(null), DateTime.Now.ToString("MM-dd-yyyy-HH-mm-ss-fff", CultureInfo.InvariantCulture) + ".jpg"); //((CameraActivity)activity).learningTask.Id + ".jpg");

                // This listener is called when an image is ready in ImageReader
                // Right click on ImageAvailableListener in your IDE and go to its definition
                ImageAvailableListener readerListener = new ImageAvailableListener()
                {
                    File = new File(thumbnailfilename), fragment = this
                };

                // We create a Handler since we want to handle the resulting JPEG in a background thread
                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();
                Handler backgroundHandler = new Handler(thread.Looper);
                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                //This listener is called when the capture is completed
                // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above
                // Right click on CameraCaptureListener in your IDE and go to its definition
                CameraCaptureListener captureListener = new CameraCaptureListener()
                {
                    Fragment = this, File = new File(thumbnailfilename)
                };

                cameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                {
                    OnConfiguredAction = (CameraCaptureSession session) => {
                        try
                        {
                            session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                        }
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
            }
        }