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;
        }
Example #2
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);
            }
        }
Example #3
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;
        }
Example #4
0
 public override void OnActivityCreated(Bundle savedInstanceState)
 {
     base.OnActivityCreated(savedInstanceState);
     mFile                     = new File(Activity.GetExternalFilesDir(null), "pic.jpg");
     mCaptureCallback          = new CaptureListener(this);
     mOnImageAvailableListener = new ImageAvailableListener(activity, context, this);
 }
Example #5
0
        public override void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            _imagesDirectory          = Activity.GetExternalFilesDir(null).AbsolutePath;
            _onImageAvailableListener = new ImageAvailableListener(this);

            CaptureCallback = new CameraCaptureListener(this);
        }
Example #6
0
        private void SetUpCameraOutputs(int width, int height, LensFacing lensFacing)
        {
            _manager = (CameraManager)_context.GetSystemService(Context.CameraService);

            string[] cameraIds = _manager.GetCameraIdList();

            _cameraId = cameraIds[0];

            for (int i = 0; i < cameraIds.Length; i++)
            {
                CameraCharacteristics chararc = _manager.GetCameraCharacteristics(cameraIds[i]);

                var facing = (Integer)chararc.Get(CameraCharacteristics.LensFacing);
                if (facing != null && facing == (Integer.ValueOf((int)LensFacing.Front)))
                {
                    continue;
                }

                _cameraId = cameraIds[i];
            }

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

            if (_supportedJpegSizes == null && characteristics != null)
            {
                _supportedJpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg);
            }

            if (_supportedJpegSizes != null && _supportedJpegSizes.Length > 0)
            {
                _idealPhotoSize = GetOptimalSize(_supportedJpegSizes, 1050, 1400); //MAGIC NUMBER WHICH HAS PROVEN TO BE THE BEST
            }

            _imageReader = ImageReader.NewInstance(_idealPhotoSize.Width, _idealPhotoSize.Height, ImageFormatType.Jpeg, 1);

            var readerListener = new ImageAvailableListener();

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

            var available = (Java.Lang.Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable);

            if (available == null)
            {
                _flashSupported = false;
            }
            else
            {
                _flashSupported = (bool)available;
            }

            _imageReader.SetOnImageAvailableListener(readerListener, _backgroundHandler);

            _previewSize = GetOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))), width, height);
        }
Example #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);
        }
        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);
        }
Example #9
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);
            }
        }
Example #10
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);
        }
        protected override void OnElementChanged(ElementChangedEventArgs <CameraPreview> e)
        {
            if (Xamarin.Forms.DesignMode.IsDesignModeEnabled)
            {
                return;
            }

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

            this.element = e.NewElement;
            if (element == null)
            {
                return;
            }

            element.TakePicture = () => { return(TakePictureAsync()); };

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

            mFrameLayout = Control as FrameLayout;
            mTextureView = new AutoFitTextureView(Context);

            mFrameLayout.AddView(mTextureView);
            mStateCallback            = new CameraStateListener(this);
            mSurfaceTextureListener   = new CameraSurfaceTextureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener(this);

            if (element.EnableTensorflowAnalysis)
            {
                mOnImageAvailableListener.EnableTensorflowAnalysis();
            }

            StartTheCamera();

            base.OnElementChanged(e);
        }
        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);
        }
Example #14
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            surfaceTextureView = FindViewById <AutoFitTextureView>(Resource.Id.surface);
            switchCameraButton = FindViewById <ImageButton>(Resource.Id.reverse_camera_button);
            takePictureButton  = FindViewById <Button>(Resource.Id.take_picture_button);
            recordVideoButton  = FindViewById <Button>(Resource.Id.record_video_button);

            cameraStateCallback = new CameraStateCallback
            {
                Opened       = OnOpened,
                Disconnected = OnDisconnected,
                Error        = OnError,
            };
            captureStateSessionCallback = new CaptureStateSessionCallback
            {
                Configured = OnPreviewSessionConfigured,
            };
            videoSessionStateCallback = new CaptureStateSessionCallback
            {
                Configured = OnVideoSessionConfigured,
            };
            cameraCaptureCallback = new CameraCaptureCallback
            {
                CaptureCompleted  = (session, request, result) => ProcessImageCapture(result),
                CaptureProgressed = (session, request, result) => ProcessImageCapture(result),
            };
            manager                  = GetSystemService(CameraService) as CameraManager;
            windowManager            = GetSystemService(WindowService).JavaCast <IWindowManager>();
            onImageAvailableListener = new ImageAvailableListener
            {
                ImageAvailable = HandleImageCaptured,
            };
            orientations.Append((int)SurfaceOrientation.Rotation0, 90);
            orientations.Append((int)SurfaceOrientation.Rotation90, 0);
            orientations.Append((int)SurfaceOrientation.Rotation180, 270);
            orientations.Append((int)SurfaceOrientation.Rotation270, 180);
        }
Example #15
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);
        }
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            mStateCallback = new CameraStateListener()
            {
                owner = 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);

            var file = new File(Activity.GetExternalFilesDir(null), "pic.jpg");

            this.mOnImageAvailableListener = new ImageAvailableListener(scanModule)
            {
                Owner = this, File = file
            };
            //this.mCaptureCallback = new CameraCaptureListener() { Owner = this, File = file};
        }
Example #17
0
        // Sets up member variables related to camera.
        private void SetUpCameraOutputs(int width, int height)
        {
            var activity = Activity;
            var manager  = (CameraManager)activity.GetSystemService(Context.CameraService);

            try
            {
                for (var i = 0; i < manager.GetCameraIdList().Length; i++)
                {
                    var cameraId = manager.GetCameraIdList()[i];
                    CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId);

                    // We don't use a front facing camera in this sample.
                    var facing = (Integer)characteristics.Get(CameraCharacteristics.LensFacing);
                    if (facing != null)
                    {
                        if (facing == (Integer.ValueOf((int)LensFacing.Back)))
                        {
                            minimumLens = (float?)characteristics.Get(CameraCharacteristics.LensInfoMinimumFocusDistance);

                            CameraExposureRange = (Range)characteristics.Get(CameraCharacteristics.SensorInfoSensitivityRange);

                            ExposureTime = (Range)characteristics.Get(CameraCharacteristics.SensorInfoExposureTimeRange);

                            FrameDuration = (long)characteristics.Get(CameraCharacteristics.SensorInfoMaxFrameDuration);


                            availableFocalLenths = (float[])characteristics.Get(CameraCharacteristics.LensInfoAvailableFocalLengths);

                            AERangeCompensation = (Range)characteristics.Get(CameraCharacteristics.ControlAeCompensationRange);
                        }

                        if (facing == (Integer.ValueOf((int)LensFacing.Front)))
                        {
                            continue;
                        }
                    }

                    var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                    if (map == null)
                    {
                        continue;
                    }

                    // For still image captures, we use the largest available size.
                    Size largest = (Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)),
                                                         new CompareSizesByArea());
                    mImageReader = ImageReader.NewInstance(largest.Width, largest.Height, ImageFormatType.Jpeg, /*maxImages*/ 2);
                    mImageReader.SetOnImageAvailableListener(mOnImageAvailableListener = new ImageAvailableListener()
                    {
                        File = mFile, Owner = this
                    }, mBackgroundHandler);

                    // Find out if we need to swap dimension to get the preview size relative to sensor
                    // coordinate.
                    var displayRotation = activity.WindowManager.DefaultDisplay.Rotation;
                    //noinspection ConstantConditions

                    //mSensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation);

                    bool swappedDimensions = false;

                    //switch (displayRotation)
                    //{
                    //    case SurfaceOrientation.Rotation0:
                    //    case SurfaceOrientation.Rotation180:
                    //        if (mSensorOrientation == 90 || mSensorOrientation == 270)
                    //        {
                    //            swappedDimensions = true;
                    //        }
                    //        break;
                    //    case SurfaceOrientation.Rotation90:
                    //    case SurfaceOrientation.Rotation270:
                    //        if (mSensorOrientation == 0 || mSensorOrientation == 180)
                    //        {
                    //            swappedDimensions = true;
                    //        }
                    //        break;
                    //    default:
                    //        Log.Error(TAG, "Display rotation is invalid: " + displayRotation);
                    //        break;
                    //}

                    Point displaySize = new Point();
                    activity.WindowManager.DefaultDisplay.GetSize(displaySize);
                    var rotatedPreviewWidth  = width;
                    var rotatedPreviewHeight = height;
                    var maxPreviewWidth      = displaySize.X;
                    var maxPreviewHeight     = displaySize.Y;

                    if (swappedDimensions)
                    {
                        rotatedPreviewWidth  = height;
                        rotatedPreviewHeight = width;
                        maxPreviewWidth      = displaySize.Y;
                        maxPreviewHeight     = displaySize.X;
                    }

                    if (maxPreviewWidth > MAX_PREVIEW_WIDTH)
                    {
                        maxPreviewWidth = MAX_PREVIEW_WIDTH;
                    }

                    if (maxPreviewHeight > MAX_PREVIEW_HEIGHT)
                    {
                        maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                    }

                    // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                    // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                    // garbage capture data.
                    mPreviewSize = ChooseOptimalSize(map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture))),
                                                     rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                                                     maxPreviewHeight, largest);

                    // We fit the aspect ratio of TextureView to the size of preview we picked.
                    var orientation = Resources.Configuration.Orientation;

                    if (orientation == Orientation.Landscape)
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
                    }
                    else
                    {
                        mTextureView.SetAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
                    }

                    // Check if the flash is supported.
                    var available = (Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable);
                    if (available == null)
                    {
                        mFlashSupported = false;
                    }
                    else
                    {
                        mFlashSupported = (bool)available;
                    }

                    mCameraId = cameraId;
                    return;
                }
            }
            catch (CameraAccessException e)
            {
                e.PrintStackTrace();
            }
            catch (NullPointerException e)
            {
                // Currently an NPE is thrown when the Camera2API is used but not supported on the
                // device this code runs.
            }
        }
Example #18
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);
            }
        }
        /// <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);
            }
        }
Example #20
0
        // 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();
            }
        }
Example #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            AppPreference appPreference = new AppPreference();

            CvInvoke.UseOpenCL = false;  //appPreference.UseOpenCL;
            string oclDeviceName = appPreference.OpenClDeviceName;

            if (!string.IsNullOrEmpty(oclDeviceName))
            {
                CvInvoke.OclSetDefaultDevice(oclDeviceName);
                Log.Error(TAG, "\t\t --OclSetDefaultDevice: " + oclDeviceName);
            }

            mFile = new Java.IO.File(GetExternalFilesDir(null), "derp.jpg");

            ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
            string             appVersion = PackageManager.GetPackageInfo(PackageName, Android.Content.PM.PackageInfoFlags.Activities).VersionName;

            if (!preference.Contains("cascade-data-version") || !preference.GetString("cascade-data-version", null).Equals(appVersion) ||
                !(preference.Contains("cascade-eye-data-path") || preference.Contains("cascade-face-data-path")))
            {
                AndroidFileAsset.OverwriteMethod overwriteMethod = AndroidFileAsset.OverwriteMethod.AlwaysOverwrite;

                FileInfo eyeFile  = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_eye.xml", "cascade", overwriteMethod);
                FileInfo faceFile = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_frontalface_alt_tree.xml", "cascade", overwriteMethod);

                Log.Error(TAG, "\t\t --eyeFile.FullName: " + eyeFile.FullName);
                Log.Error(TAG, "\t\t --faceFile.FullName: " + faceFile.FullName);

                //save tesseract data path
                ISharedPreferencesEditor editor = preference.Edit();
                editor.PutString("cascade-data-version", appVersion);
                editor.PutString("cascade-eye-data-path", eyeFile.FullName);
                editor.PutString("cascade-face-data-path", faceFile.FullName);
                editor.Commit();
            }

            eyeXml  = preference.GetString("cascade-eye-data-path", null);
            faceXml = preference.GetString("cascade-face-data-path", null);

            Log.Error(TAG, "\t\t --eyeXml: " + eyeXml);
            Log.Error(TAG, "\t\t --faceXml: " + faceXml);

            //face = new CascadeClassifier(faceXml);
            //eye = new CascadeClassifier(eyeXml);

            // Hide the window title and go fullscreen.
            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.Fullscreen);

            SetContentView(Resource.Layout.take_photo_surface_view);
            mTextureView     = (AutoFitTextureView)FindViewById(Resource.Id.CameraView);
            mTransparentView = (SurfaceView)FindViewById(Resource.Id.TransparentView);

            mTransparentView.SetZOrderOnTop(true);
            mTransparentView.BringToFront();

            mTransparentView.Holder.SetFormat(Android.Graphics.Format.Transparent);
            mTransparentView.Holder.AddCallback(this);

            var manager = GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            var size    = new Android.Graphics.Point();

            manager.DefaultDisplay.GetSize(size);

            screenX = size.X / 2;
            screenY = size.Y / 2;

            L = screenX - 200;
            T = screenY - 200;
            R = screenX + 200;
            B = screenY + 200;

            mStateCallback = new CameraStateListener()
            {
                owner = this
            };
            mSurfaceTextureListener   = new Camera2BasicSurfaceTextureListener(this);
            mOnImageAvailableListener = new ImageAvailableListener()
            {
                Owner = 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);
        }
Example #22
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);
        }
Example #23
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);
            }
        }
Example #24
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.");
            }
        }
Example #25
0
        public Task <byte[]> TakePicture()
        {
            if (Context == null || (Context as Activity).IsFinishing || ActiveCameraDevice == null)
            {
                return(Task.FromResult(Enumerable.Empty <byte>().ToArray()));
            }

            var file = new File(Context.GetExternalFilesDir(null), "pic.jpg");

            var tcs            = new TaskCompletionSource <byte[]>();
            var readerListener = new ImageAvailableListener(tcs, file);

            try
            {
                CameraManager manager = (CameraManager)Context.GetSystemService(Context.CameraService);

                CameraCharacteristics characteristics = manager.GetCameraCharacteristics(ActiveCameraDevice.Id);

                StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap);

                Size[] jpegSizes = map.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> {
                    reader.Surface,
                    new Surface(textureView.SurfaceTexture)
                };

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

                SetUpCaptureRequestBuilder(captureBuilder);

                captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(ORIENTATIONS.Get((int)SurfaceOrientation.Rotation180)));

                HandlerThread thread = new HandlerThread("CameraPicture");
                thread.Start();

                Handler backgroundHandler = new Handler(thread.Looper);

                reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                ActiveCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureSessionStateCallback(this)
                {
                    OnConfiguredAction = session =>
                    {
                        try
                        {
                            session.Capture(captureBuilder.Build(), null, backgroundHandler);
                        }
                        catch (CameraAccessException ex)
                        {
                            Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                            tcs.TrySetException(ex);
                        }
                    }
                }, backgroundHandler);
            }
            catch (CameraAccessException ex)
            {
                Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace);
                tcs.TrySetException(ex);
            }

            return(tcs.Task);
        }
		/// <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);
			}
		}
Example #27
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);
            }
        }