Ejemplo n.º 1
1
 public void StartPreview()
 {
     try
     {
         var numberOfCameras = Camera.NumberOfCameras;
         int? rearFacingCameraId = null;
         // Find the ID of the default camera
         Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
         for (int i = 0; i < numberOfCameras; i++)
         {
             Camera.GetCameraInfo(i, cameraInfo);
             if (cameraInfo.Facing == CameraFacing.Back)
             {
                 rearFacingCameraId = i;
             }
         }
         if (rearFacingCameraId.HasValue)
         {
             camera = Camera.Open(rearFacingCameraId.Value);
             if (cameraPreview != null)
             {
                 cameraPreview.PreviewCamera = camera;
             }
         }
     }
     catch (CameraAccessException ex)
     {
     }
     catch (NullPointerException)
     {
     }
     catch (System.Exception ex)
     {
     }
 }
Ejemplo n.º 2
0
        private void UpdateCameraAspect()
        {
            try
            {
                Camera.Parameters camParams = camera.GetParameters();
                Camera.CameraInfo info      = new Camera.CameraInfo();
                Camera.GetCameraInfo((int)Android.Hardware.CameraFacing.Back, info);

                Camera.Size size = GetOptimalPreviewSize(camParams.SupportedPreviewSizes, width, height);

                camParams.SetPreviewSize(size.Width, size.Height);

                int rotation = (info.Orientation + 360) % 360;

                camParams.SetRotation(rotation);

                if (camParams.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
                {
                    camParams.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
                }

                camera.SetParameters(camParams);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public void OnSurfaceTextureAvailable (Android.Graphics.SurfaceTexture surface, int width, int height)
        {
			if (Camera.NumberOfCameras == 0) {
				Toast.MakeText (this, Resource.String.no_camera, ToastLength.Long).Show ();
				return;
			}
			_camera = Camera.Open();
			if (_camera == null)
				_camera = Camera.Open (0);
            
            var previewSize = _camera.GetParameters ().PreviewSize;
            _textureView.LayoutParameters = 
                new FrameLayout.LayoutParams (previewSize.Width, previewSize.Height, GravityFlags.Center);
            
            try {
                _camera.SetPreviewTexture (surface);
                _camera.StartPreview ();
            } catch (Java.IO.IOException ex) {
                Console.WriteLine (ex.Message);
            }
            
            // this is the sort of thing TextureView enables
            _textureView.Rotation = 45.0f;
            _textureView.Alpha = 0.5f;
        }
Ejemplo n.º 4
0
        protected sealed override void StartPreview()
        {
            _camera = Camera.Open((int)CurrentCamera);
            _camera.SetDisplayOrientation(90);

            var parameters = _camera.GetParameters();
            if (parameters.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
            }

            var optimalSize = GetOptimalPreviewSize(_width, _height);
            if (optimalSize != null)
            {
                parameters.SetPreviewSize(optimalSize.Width, optimalSize.Height);
            }

            _camera.SetParameters(parameters);

            try
            {
                _camera.SetPreviewTexture(_surface);
                _camera.StartPreview();
            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 5
0
        public void ShutdownCamera()
        {
            tokenSource.Cancel();

            var theCamera = camera;

            camera = null;

            // make this asyncronous so that we can return from the view straight away instead of waiting for the camera to release.
            Task.Factory.StartNew(() => {
                try {
                    if (theCamera != null)
                    {
                        try {
                            theCamera.SetPreviewCallback(null);
                            theCamera.StopPreview();
                        } catch (Exception ex) {
                            Android.Util.Log.Error(MobileBarcodeScanner.TAG, ex.ToString());
                        }
                        theCamera.Release();
                    }
                } catch (Exception e) {
                    Android.Util.Log.Error(MobileBarcodeScanner.TAG, e.ToString());
                } finally {
                    ReleaseExclusiveAccess();
                }
            });
        }
        /// <summary>
        /// Turn the lamp off
        /// </summary>
        public void TurnOff()
        {
            if (camera == null)
            {
                camera = Camera.Open();
            }

            if (camera == null)
            {
                Debug.WriteLine("Camera failed to initialize");
                return;
            }

            var p = camera.GetParameters();
            var supportedFlashModes = p.SupportedFlashModes;

            if (supportedFlashModes == null)
            {
                supportedFlashModes = new List <string>();
            }

            var flashMode = string.Empty;

            if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
            {
                flashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
            }

            if (!string.IsNullOrEmpty(flashMode))
            {
                p.FlashMode = flashMode;
                camera.SetParameters(p);
            }
        }
Ejemplo n.º 7
0
        public async void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            try
            {
                _camera = Android.Hardware.Camera.Open((int)CameraFacing.Back);
                determineDisplayOrientation();
                setupCamera();

                _textureView.LayoutParameters = new Android.Widget.FrameLayout.LayoutParams(width, height);
                _surfaceTexture = surface;
                _camera.SetPreviewTexture(_surfaceTexture);
                _camera.StartPreview();
            }
            catch (Exception)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(_activity);

                builder.SetMessage("Die Kamera kann nicht geöffnet werden.");
                builder.SetTitle("Fehler");

                AlertDialog dialog = builder.Create();

                dialog.Show();
                await Element.Navigation.PopModalAsync();
            }
        }
Ejemplo n.º 8
0
 protected override void OnDestroy()
 {
     camera?.StopPreview();
     camera?.Release();
     camera = null;
     base.OnDestroy();
 }
Ejemplo n.º 9
0
        private void ApplyCameraSettings()
        {
            if (Camera == null)
            {
                OpenCamera(CameraFacing.Back);
            }

            // do nothing if something wrong with camera
            if (Camera == null)
            {
                return;
            }

            var parameters = Camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;

            var supportedFocusModes = parameters.SupportedFocusModes;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.IceCreamSandwich &&
                supportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousVideo))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousVideo;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeAuto))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeAuto;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeFixed))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeFixed;
            }

            var selectedFps = parameters.SupportedPreviewFpsRange.FirstOrDefault();

            if (selectedFps != null)
            {
                // This will make sure we select a range with the lowest minimum FPS
                // and maximum FPS which still has the lowest minimum
                // This should help maximize performance / support for hardware
                foreach (var fpsRange in parameters.SupportedPreviewFpsRange)
                {
                    if (fpsRange[0] <= selectedFps[0] && fpsRange[1] > selectedFps[1])
                    {
                        selectedFps = fpsRange;
                    }
                }
                parameters.SetPreviewFpsRange(selectedFps[0], selectedFps[1]);
            }



            Camera.SetParameters(parameters);

            SetCameraDisplayOrientation();
        }
 public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
 {
     camera = Android.Hardware.Camera.Open((int)CameraFacing.Back);
     textureView.LayoutParameters = new FrameLayout.LayoutParams(width, height);
     camera.SetPreviewTexture(surface);
     PrepareAndStartCamera();
 }
Ejemplo n.º 11
0
        public void OnPictureTaken(byte[] data, Camera camera)
        {
            if (data != null)
            {
                try
                {
                    TurnOnFocusLockIfNothingCaptured();
                    var wasPreviewRestarted = false;
                    try
                    {
                        _camera.StartPreview();
                        wasPreviewRestarted = true;
                    }
                    catch
                    {
                        // restarting preview failed, try again later, some devices are just weird
                    }

                    _cameraModule.CapturedImage = data;

                    if (!wasPreviewRestarted)
                    {
                        _camera.StartPreview();
                    }
                }
                catch (Exception e)
                {
                    _cameraModule.ErrorMessage = e.ToString();
                }
            }
        }
Ejemplo n.º 12
0
      /// <summary>
      /// Turn the lamp off
      /// </summary>
      public void TurnOff()
      {
          if (camera == null)
              camera = Camera.Open();

          if (camera == null)
          {
              Debug.WriteLine("Camera failed to initialize");
              return;
          }

          var p = camera.GetParameters();
          var supportedFlashModes = p.SupportedFlashModes;

          if (supportedFlashModes == null)
              supportedFlashModes = new List<string>();

          var flashMode = string.Empty;

          if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
              flashMode = Android.Hardware.Camera.Parameters.FlashModeOff;

          if (!string.IsNullOrEmpty(flashMode))
          {
              p.FlashMode = flashMode;
              camera.SetParameters(p);
          }
      }
        public void OpenCamera()
        {
            if (MyCamera != null)
            {
                MyCamera.StopPreview();
                MyCamera.Release();
                MyCamera = null;
            }

            if (_cameraId >= 0)
            {
                Camera.GetCameraInfo(_cameraId, _cameraInfo);

                MyCamera = Camera.Open(_cameraId);

                Camera.Parameters param = MyCamera.GetParameters();
                param.SetRotation(0);

                MyCamera.SetParameters(param);

                try {
                    if (_surfaceTexture != null)
                    {
                        MyCamera.SetPreviewTexture(_surfaceTexture);
                        MyCamera.StartPreview();
                    }
                } catch (Exception) {
                }
            }

            UpdateRotation();
        }
        private bool safeCameraOpenInView(View view)
        {
            bool opened = false;

            releaseCameraAndPreview();
            mCamera     = getCameraInstance(CURRENTCAMERA);
            mCameraView = view;
            opened      = mCamera != null;

            if (opened)
            {
                mPreview = new CameraPreview(Activity.BaseContext, mCamera, view);
                FrameLayout preview = view.FindViewById <FrameLayout>(Resource.Id.camera_preview);
                preview.AddView(mPreview, 0);
                mPreview.StartCameraPreview();
                try
                {
                    mCamera.EnableShutterSound(false);
                }
                catch
                {
                }
            }

            return(opened);
        }
Ejemplo n.º 15
0
        //switches between front and back cameras when button is clicked
        void SwitchCameraButtonTapped(object sender, EventArgs e)
        {
            //if camera isn't started
            if (!_isCameraStarted)
            {
                return;
            }

            if (cameraType == CameraFacing.Front)
            {
                cameraType = CameraFacing.Back;

                camera.StopPreview();
                camera.Release();
                camera = Android.Hardware.Camera.Open((int)cameraType);
                camera.SetPreviewTexture(surfaceTexture);
                PrepareAndStartCamera();
            }
            else
            {
                cameraType = CameraFacing.Front;

                camera.StopPreview();
                camera.Release();
                camera = Android.Hardware.Camera.Open((int)cameraType);
                camera.SetPreviewTexture(surfaceTexture);
                PrepareAndStartCamera();
            }
        }
        private void ToggleFlashButtonTapped(object sender, EventArgs e)
        {
            flashOn = !flashOn;
            if (flashOn)
            {
                if (cameraType == CameraFacing.Back)
                {
                    toggleFlashButton.SetBackgroundResource(Resource.Drawable.FlashButton);
                    cameraType = CameraFacing.Back;

                    camera.StopPreview();
                    camera.Release();
                    camera = Camera.Open((int)cameraType);
                    var parameters = camera.GetParameters();
                    parameters.FlashMode = Camera.Parameters.FlashModeTorch;
                    camera.SetParameters(parameters);
                    camera.SetPreviewTexture(surfaceTexture);
                    PrepareAndStartCamera();
                }
            }
            else
            {
                toggleFlashButton.SetBackgroundResource(Resource.Drawable.NoFlashButton);
                camera.StopPreview();
                camera.Release();

                camera = Camera.Open((int)cameraType);
                var parameters = camera.GetParameters();
                parameters.FlashMode = Camera.Parameters.FlashModeOff;
                camera.SetParameters(parameters);
                camera.SetPreviewTexture(surfaceTexture);
                PrepareAndStartCamera();
            }
        }
Ejemplo n.º 17
0
        public void ShutdownCamera()
        {
            if (Camera == null)
            {
                return;
            }

            // camera release logic takes about 0.005 sec so there is no need in async releasing
            var perf = PerformanceCounter.Start();

            try
            {
                try
                {
                    Camera.SetPreviewCallback(null);
                    Camera.SetPreviewDisplay(null);
                    Camera.StopPreview();
                }
                catch (Exception ex)
                {
                    Android.Util.Log.Error(MobileBarcodeScanner.TAG, ex.ToString());
                }
                Camera.Release();
                Camera = null;
            }
            catch (Exception e)
            {
                Android.Util.Log.Error(MobileBarcodeScanner.TAG, e.ToString());
            }

            PerformanceCounter.Stop(perf, "Shutdown camera took {0}ms");
        }
Ejemplo n.º 18
0
        void Android.Hardware.Camera.IPreviewCallback.OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            count++;
            Console.WriteLine(count);

            if (count == 20)
            {
                new Thread(() =>
                {
                    Console.WriteLine("Hello");

                    var image = textureView.Bitmap;
                    image     = ToGrayscale(image);

                    int width  = textureView.Width;
                    width      = width / 2;
                    int height = textureView.Height;
                    height     = height / 2;
                    image      = Bitmap.CreateBitmap(image, width - 200, height - 200, 400, 400);
                    var x      = Task.Run(() => imageClassifier.RecognizeImage(image));
                    res        = x.Result;
                    Console.WriteLine(x.Result);
                    count = 0;
                }
                           ).Start();
                result.Text = res;
            }
        }
Ejemplo n.º 19
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            camera = Android.Hardware.Camera.Open();
            var parameters = camera.GetParameters();



            parameters.FocusMode = Parameters.FocusModeContinuousPicture;
            parameters.FlashMode = Parameters.FlashModeAuto;
            var aspect = ((decimal)height) / ((decimal)width);


            var previewSize = parameters.SupportedPreviewSizes.First();



            System.Diagnostics.Debug.WriteLine($"Preview sizes: {parameters.SupportedPreviewSizes.Count}");
            var supportedPreviewSizes = parameters.SupportedPreviewSizes;


            parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
            System.Diagnostics.Debug.WriteLine(previewSize.Width + " " + previewSize.Height);
            camera.SetParameters(parameters);

            camera.SetPreviewTexture(surface);
            StartCamera();
        }
Ejemplo n.º 20
0
        public void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            var      outputStream = new MemoryStream();
            YuvImage yuvImage     = new YuvImage(data, ImageFormat.Nv21, _imageWidth, _imageHeight, null);

            yuvImage.CompressToJpeg(new Rect(0, 0, _imageWidth, _imageHeight), 50, outputStream);

            byte[] imageBytes = outputStream.ToArray();

            Element.OnPreviewReady(imageBytes);


            //        Parameters parameters = camera.GetParameters();
            //        var imageFormat = parameters.PreviewFormat;
            //        if (imageFormat == ImageFormatType.Nv21)
            //        {
            //            Rect rect = new Rect(0, 0, liveCameraStream.Width, liveCameraStream.Height);
            //            YuvImage img = new YuvImage(data, ImageFormat.Nv21, liveCameraStream.Width, liveCameraStream.Height, null);

            //            Java.IO.ByteArrayOutputStream baos = new Java.IO.ByteArrayOutputStream();
            //            Java.IO.ObjectOutputStream oos = new Java.IO.ObjectOutputStream(baos);
            //oos.writeObject(C1);
            //oos.flush();
            //}
        }
Ejemplo n.º 21
0
        void ToggleFlashButtonTapped(object sender, EventArgs e)
        {
            _flashOn = !_flashOn;
            if (_flashOn)
            {
                if (_cameraType == CameraFacing.Back)
                {
                    _toggleFlashButton.SetBackgroundResource(Resource.Drawable.FlashButton);
                    _cameraType = CameraFacing.Back;

                    _camera.StopPreview();
                    _camera.Release();
                    _camera = Android.Hardware.Camera.Open((int)_cameraType);
                    var parameters = _camera.GetParameters();
                    parameters.FlashMode = global::Android.Hardware.Camera.Parameters.FlashModeTorch;
                    _camera.SetParameters(parameters);
                    _camera.SetPreviewTexture(_surfaceTexture);
                    PrepareAndStartCamera();
                }
            }
            else
            {
                _toggleFlashButton.SetBackgroundResource(Resource.Drawable.NoFlashButton);
                _camera.StopPreview();
                _camera.Release();

                _camera = global::Android.Hardware.Camera.Open((int)_cameraType);
                var parameters = _camera.GetParameters();
                parameters.FlashMode = global::Android.Hardware.Camera.Parameters.FlashModeOff;
                _camera.SetParameters(parameters);
                _camera.SetPreviewTexture(_surfaceTexture);
                PrepareAndStartCamera();
            }
        }
Ejemplo n.º 22
0
        private async void EnableCamera(int cameraToSwitch)
        {
            try
            {
                _camera   = Camera.Open(cameraToSwitch);
                _cameraId = cameraToSwitch;
                SetPreviewSize(FullScreen);
                SetCameraDisplayOrientation(_cameraId);
                _camera.SetPreviewDisplay(_holder);
                _camera.StartPreview();
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(Java.Lang.RuntimeException) && ex.Message == "Fail to connect to camera service")
                {
                    Activity.Finish();
                }
                else
                {
                    await AppSettings.Logger.Error(ex);

                    Activity.ShowAlert(new InternalException(LocalizationKeys.CameraSettingError, ex), ToastLength.Short);
                }
            }
        }
Ejemplo n.º 23
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

			SetContentView(Resource.Layout.ScannerView);

            var frameLayout = (FrameLayout)FindViewById(Resource.Id.cameraPreview);

            camera = GetCameraInstance();

            if (camera == null)
            {
                Complete(new Intent());
                return;
            }

            previewCb = new PreviewCallback();

            previewCb.ScanComplete += PreviewCb_ScanComplete;

            camPreview = new CameraPreview(this, camera, previewCb);

            frameLayout.AddView(camPreview);
                
        }
Ejemplo n.º 24
0
        //public void RefreshCamera()
        //{
        //    if (_holder == null) return;

        //    ApplyCameraSettings();

        //    try
        //    {
        //        Camera.SetPreviewDisplay(_holder);
        //        Camera.StartPreview();
        //    }
        //    catch (Exception ex)
        //    {
        //        Android.Util.Log.Debug(nameof(CameraController), ex.ToString());
        //    }
        //}



        public void SetupCamera(CameraFacing facing)
        {
            if (Camera != null)
            {
                return;
            }

            PermissionsHandler.CheckCameraPermissions(_context);


            OpenCamera(facing);


            if (Camera == null)
            {
                return;
            }


            ApplyCameraSettings();

            try
            {
                Camera.SetPreviewDisplay(_holder);


                //var previewParameters = Camera.GetParameters();
                //var previewSize = previewParameters.PreviewSize;
                //var bitsPerPixel = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat);


                //int bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8;
                //const int NUM_PREVIEW_BUFFERS = 5;
                //for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i)
                //{
                //    using (var buffer = new FastJavaByteArray(bufferSize))
                //        Camera.AddCallbackBuffer(buffer);
                //}



                Camera.StartPreview();

                // Camera.SetNonMarshalingPreviewCallback(_cameraEventListener);
            }
            catch (Exception ex)
            {
                Android.Util.Log.Debug(nameof(CameraController), ex.ToString());
                return;
            }

            // Docs suggest if Auto or Macro modes, we should invoke AutoFocus at least once
            var currentFocusMode = Camera.GetParameters().FocusMode;

            if (currentFocusMode == Camera.Parameters.FocusModeAuto ||
                currentFocusMode == Camera.Parameters.FocusModeMacro)
            {
                AutoFocus();
            }
        }
Ejemplo n.º 25
0
        public void ShutdownCamera()
        {
            if (Camera == null)
            {
                return;
            }


            try
            {
                try
                {
                    Camera.StopPreview();


                    //Camera.SetPreviewDisplay(null);
                }
                catch (Exception ex)
                {
                    //Android.Util.Log.Error(MobileBarcodeScanner.TAG, ex.ToString());
                }
                Camera.Release();
                Camera = null;
            }
            catch (Exception e)
            {
                //Android.Util.Log.Error(MobileBarcodeScanner.TAG, e.ToString());
            }
        }
        public void OnPictureTaken(byte[] data, Camera _)
        {
            if (_capturePath == null)
            {
                throw new ArgumentNullException(nameof(_capturePath));
            }

            System.IO.File.WriteAllBytes(_capturePath, data);

            var cameraOrientation = GetCameraDisplayOrientation();
            //var ei = new ExifInterface(_capturePath);
            //var orientation = (Orientation) ei.GetAttributeInt(ExifInterface.TagOrientation,
            //									 -1);

            var bitmap = BitmapFactory.DecodeFile(_capturePath);

            RotateImage(bitmap, cameraOrientation);
            //switch (orientation)
            //{

            //	case Orientation.Rotate90:
            //		RotateImage(bitmap, 90);
            //		break;

            //	case Orientation.Rotate180:
            //		RotateImage(bitmap, 180);
            //		break;

            //	case Orientation.Rotate270:
            //		RotateImage(bitmap, 270);
            //		break;
            //}

            _capturePath = null;
        }
        public void SetupCamera()
        {
            if (Camera != null)
            {
                return;
            }

            var perf = PerformanceCounter.Start();

            OpenCamera();
            PerformanceCounter.Stop(perf, "Setup Camera took {0}ms");

            if (Camera == null)
            {
                return;
            }

            perf = PerformanceCounter.Start();
            ApplyCameraSettings();

            try
            {
                Camera.SetPreviewDisplay(holder);


                var previewParameters = Camera.GetParameters();
                var previewSize       = previewParameters.PreviewSize;
                var bitsPerPixel      = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat);


                var       bufferSize          = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8;
                const int NUM_PREVIEW_BUFFERS = 5;
                for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i)
                {
                    using (var buffer = new FastJavaByteArray(bufferSize))
                        Camera.AddCallbackBuffer(buffer);
                }

                Camera.StartPreview();

                Camera.SetNonMarshalingPreviewCallback(cameraEventListener);

                // Docs suggest if Auto or Macro modes, we should invoke AutoFocus at least once
                var currentFocusMode = Camera.GetParameters().FocusMode;
                if (currentFocusMode == Camera.Parameters.FocusModeAuto ||
                    currentFocusMode == Camera.Parameters.FocusModeMacro)
                {
                    AutoFocus();
                }
            }
            catch (Exception ex)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, ex.ToString());
                return;
            }
            finally
            {
                PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");
            }
        }
        public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
            // Creates a data access object to record the intrusion in the history
            DAO = new DataAccessObject();
            DAO.insertHistoryItems(DateTime.Now.ToString(), "Intrusion Detected", data);

            Bitmap bmp;

            BitmapFactory.Options bmpOptions = new BitmapFactory.Options {
                InJustDecodeBounds = true
            };
            bmpOptions.InSampleSize = 4;

            bmpOptions.InJustDecodeBounds = false;

            //decode the data obtained by the camera into a Bitmap
            bmp = BitmapFactory.DecodeByteArray(data, 0, data.Length, bmpOptions);

            int    width  = bmp.Width;
            int    height = bmp.Height;
            Matrix matrix = new Matrix();

            matrix.PostRotate(270);

            Bitmap resized = Bitmap.CreateBitmap(bmp, 0, 0, width, height, matrix, false);

            afile       = new Java.IO.File(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "picture.jpeg");
            fileWritter = new FileOutputStream(afile);
            fileWritter.Write(data, 0, data.Length);

            attach = new Attachment(afile.Path);

            picturePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "picture.jpeg");
        }
Ejemplo n.º 29
0
 public void SetupLiveCameraStream()
 {
     lock (lockObj)
     {
         if (surface == null)
         {
             return;
         }
         try
         {
             camera = Android.Hardware.Camera.Open(1);
             camera.SetDisplayOrientation(90);
             var cameraParams = camera.GetParameters();
             foreach (Android.Hardware.Camera.Size size in cameraParams.SupportedPreviewSizes)
             {
                 if (size.Width <= 176)
                 {
                     cameraParams.SetPreviewSize(size.Width, size.Height);
                 }
             }
             camera.SetParameters(cameraParams);
             camera.SetPreviewTexture(surface);
             camera.SetPreviewCallback(this);
             camera.StartPreview();
         }
         catch (Java.IO.IOException ex)
         {
         }
     }
 }
		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			// Open an instance of the first camera and retrieve its info.
			camera = GetCameraInstance (CAMERA_ID);
			Camera.CameraInfo cameraInfo = null;

			if (camera != null) {
				// Get camera info only if the camera is available
				cameraInfo = new Camera.CameraInfo ();
				Camera.GetCameraInfo (CAMERA_ID, cameraInfo);
			}

			if (camera == null || cameraInfo == null) {
				Toast.MakeText (Activity, "Camera is not available.", ToastLength.Short).Show ();
				return inflater.Inflate (Resource.Layout.fragment_camera_unavailable, null);
			}

			View root = inflater.Inflate (Resource.Layout.fragment_camera, null);

			// Get the rotation of the screen to adjust the preview image accordingly.
			SurfaceOrientation displayRotation = Activity.WindowManager.DefaultDisplay.Rotation;

			// Create the Preview view and set it as the content of this Activity.
			cameraPreview = new CameraPreview (Activity, camera, cameraInfo, displayRotation);
			var preview =  root.FindViewById <FrameLayout> (Resource.Id.camera_preview);
			preview.AddView (cameraPreview);

			return root;
		}
Ejemplo n.º 31
0
        public void ShutdownCamera()
        {
            if (camera == null)
            {
                return;
            }

            try
            {
                try
                {
                    camera.StopPreview();
                    camera.SetNonMarshalingPreviewCallback(null);

                    camera.SetPreviewDisplay(null);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }

                camera.Release();
                camera = null;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Callback when the picture is taken by the Camera
        /// </summary>
        /// <param name="data"></param>
        /// <param name="camera"></param>
        public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)//2
        {
            try
            {
                var DateGenerated = System.DateTime.Now;
                var message       = new MimeMessage();
                message.From.Add(new MailboxAddress("From", "*****@*****.**"));
                message.To.Add(new MailboxAddress("To", "*****@*****.**"));
                if (!string.IsNullOrEmpty(StaticUser.Email))
                {
                    message.Cc.Add(new MailboxAddress("CC", StaticUser.Email));
                }
                message.Subject = "Снимок объекта за " + DateGenerated.ToString();

                var body = new TextPart("plain")
                {
                    Text = "Снимок объекта подготовлен в " + DateGenerated.ToString()
                };

                var attachment = new MimePart("image", "jpg")
                {
                    Content                 = new MimeContent(new MemoryStream(data), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = "снимок_объекта_" + DateGenerated.ToString() + ".jpg"
                };

                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);
                message.Body = multipart;

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect("smtp.mail.ru", 587, false);
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate("*****@*****.**", "MKFe5ElR");
                    client.Send(message);
                    client.Disconnect(true);
                }

                //string fileName = Uri.Parse("test.jpg").LastPathSegment;
                //var os = _context.OpenFileOutput(fileName, FileCreationMode.Private);
                //System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(os);
                //binaryWriter.Write(data);
                //binaryWriter.Close();

                //We start the camera preview back since after taking a picture it freezes
                camera.StartPreview();
            }
            catch (System.Exception e)
            {
                Log.Debug(APP_NAME, "File not found: " + e.Message);
            }
        }
Ejemplo n.º 33
0
 public override void OnPause()
 {
     base.OnPause();
     if (mCamera != null) {
         mCamera.Release();
         mCamera = null;
     }
 }
Ejemplo n.º 34
0
 public void OnAutoFocus(bool success, Android.Hardware.Camera camera)
 {
     if (takePicture)
     {
         takePicture = false;
         camera.TakePicture(null, null, this);
     }
 }
Ejemplo n.º 35
0
 public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
 {
     countImage++;
     photoFile = new File(pictures, "imageFromHideSnap" +
                          countImage + ".jpg");
     camera.StartPreview();
     WritePhotoToSD(photoFile, data);
 }
Ejemplo n.º 36
0
 public void SurfaceDestroyed(ISurfaceHolder holder)
 {
     // TODO Auto-generated method stub
     camera.StopPreview();
     camera.Release();
     camera     = null;
     previewing = false;
 }
Ejemplo n.º 37
0
        public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
            var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempPath() + ".jpg");

            System.IO.File.WriteAllBytes(path, data);
            Element.SendOnPhotoTaken(path);
            camera.StartPreview();
        }
Ejemplo n.º 38
0
		protected override void OnResume ()
		{
			base.OnResume ();

			// Open the default i.e. the first rear facing camera.
			mCamera = Camera.Open ();
			cameraCurrentlyLocked = defaultCameraId;
			mPreview.PreviewCamera = mCamera;
		}
		protected void StartCamera() {
			if (_Camera == null) {
				_Camera = Camera.Open();
				_CameraSupportedFlashModes = _CameraSupportedFlashModes ?? _Camera.GetParameters().SupportedFlashModes;
				if (_CameraSupportedFlashModes == null || !_CameraSupportedFlashModes.Contains(FlashlightOnMode) || !_CameraSupportedFlashModes.Contains(FlashlightOffMode)) {
					StopCamera();
				}
			}
		}
Ejemplo n.º 40
0
 public void Desliga()
 {
     if (camera != null && TemFlash.Equals(true))
     {
         camera.StopPreview();
         camera.Release();
         camera = null;
     }
 }
 protected string GetCameraFlashMode(Camera.Parameters cameraParameters = null)
 {
     string mode = null;
     if (_Camera != null) {
         if (cameraParameters == null) {
             cameraParameters = _Camera.GetParameters();
         }
         mode = cameraParameters.FlashMode;
     }
     return mode;
 }
Ejemplo n.º 42
0
      public CameraPreview(Context context, Camera.IPreviewCallback previewCallback, bool cameraPreviewCallbackWithBuffer)
         : base(context)
      {
         _cameraPreviewCallbackWithBuffer = cameraPreviewCallbackWithBuffer;

         // Install a SurfaceHolder.Callback so we get notified when the
         // underlying surface is created and destroyed.
         _surfaceHolder = Holder;
         _surfaceHolder.AddCallback(this);

         _cameraPreviewCallback = previewCallback;
      }
Ejemplo n.º 43
0
		protected override void OnPause ()
		{
			base.OnPause ();

			// Because the Camera object is a shared resource, it's very
			// important to release it when the activity is paused.
			if (mCamera != null) {
				mPreview.PreviewCamera = null;
				mCamera.Release ();
				mCamera = null;
			}
		}
Ejemplo n.º 44
0
        protected override void OnPause()
        {
            if (_camera != null) {
                _camera.StopPreview ();
                _camera.SetPreviewCallback (null);
                _camera.Release ();

                _camera = null;
            }

            base.OnPause ();
        }
Ejemplo n.º 45
0
 public void CleanUpCamera()
 {
     if (camera != null)
     {
         camera.StopPreview();
         if (cameraPreview != null)
         {
             cameraPreview.PreviewCamera = null;
         }
         camera.Release();
         camera = null;
     }
 }
Ejemplo n.º 46
0
        protected override void OnDestroy()
        {
            base.OnDestroy();

            if (camera != null)
            {
                camera.SetPreviewCallback(null);
                camera.Release();
                camera = null;

            }
            ;
        }
	    public void SurfaceCreated (ISurfaceHolder holder)
		{
			try 
			{
				var version = Android.OS.Build.VERSION.SdkInt;

				if (version >= BuildVersionCodes.Gingerbread)
				{
					var numCameras = Android.Hardware.Camera.NumberOfCameras;
					var camInfo = new Android.Hardware.Camera.CameraInfo();
					var found = false;
					
					for (int i = 0; i < numCameras; i++)
					{
						Android.Hardware.Camera.GetCameraInfo(i, camInfo);
						if (camInfo.Facing == CameraFacing.Back)
						{
							camera = Android.Hardware.Camera.Open(i);
							found = true;
							break;
						}
					}
					
					if (!found)
					{
						Android.Util.Log.Debug("ZXing.Net.Mobile", "Finding rear camera failed, opening camera 0...");
						camera = Android.Hardware.Camera.Open(0);
					}
				}
				else
				{
					camera = Android.Hardware.Camera.Open();
				}
				if (camera == null)
					Android.Util.Log.Debug("ZXing.Net.Mobile", "Camera is null :(");
				
				
				//camera = Android.Hardware.Camera.Open ();
				camera.SetPreviewDisplay (holder);
				//camera.SetPreviewCallback (this);
				camera.SetOneShotPreviewCallback(this);

				
			} catch (Exception ex) {
				ShutdownCamera ();
				
				// TODO: log or otherwise handle this exception
				Console.WriteLine("Setup Error: " + ex);
				//throw;
			}
		}
Ejemplo n.º 48
0
 public void OnSurfaceTextureAvailable (Android.Graphics.SurfaceTexture surface, int w, int h)
 {
     _camera = Camera.Open ();
     
     _textureView.LayoutParameters = new FrameLayout.LayoutParams (w, h);
     
     try {
         _camera.SetPreviewTexture (surface);
         _camera.StartPreview ();
         
     } catch (Java.IO.IOException ex) {
         Console.WriteLine (ex.Message);
     }
 }
Ejemplo n.º 49
0
			public void SurfaceCreated (ISurfaceHolder holder)
			{
				try {
					camera = Camera.Open ();
					camera.SetPreviewDisplay (holder);
					camera.SetPreviewCallback (this);

				} catch (Exception e) {
					ShutdownCamera ();

					// TODO: log or otherwise handle this exception

					throw;
				}
			}
Ejemplo n.º 50
0
        public bool Liga()
        {
            if (TemFlash)
            {
                camera = Camera.Open();

                var parametros = camera.GetParameters();
                parametros.FlashMode = Camera.Parameters.FlashModeTorch;

                camera.SetParameters(parametros);
                camera.StartPreview();

                return true;
            }
            return false;
        }
Ejemplo n.º 51
0
        public CameraPreview(Context context, Camera camera,Camera.IPreviewCallback previewCallback) : base(context)
        {
            this.camera = camera;
            this.previewCallback = previewCallback;

            var parameters = this.camera.GetParameters();
            foreach (var p in from f in parameters.SupportedFocusModes where f == Camera.Parameters.FocusModeContinuousPicture select this.camera.GetParameters())
            {
                p.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
                this.camera.SetParameters(p);
            }

            surfaceHolder = base.Holder;
            surfaceHolder.AddCallback(this);

        }
		public override void Prepare(){
			
			if (camera == null) {
				camera = Camera.Open();
			}
			
			// We reconnect to camera to change flash state if needed
			camera.Reconnect();
			Camera.Parameters parameters = camera.GetParameters();
			parameters.FlashMode = flashState?Camera.Parameters.FlashModeTorch:Camera.Parameters.FlashModeOff;
			camera.SetParameters(parameters);
			camera.SetDisplayOrientation(quality.Orientation);
			camera.StopPreview();
			camera.Unlock();
			base.SetCamera(camera);

			base.SetVideoSource(Android.Media.VideoSource.Camera);
			base.SetOutputFormat(Android.Media.OutputFormat.ThreeGpp);
			base.SetMaxDuration(0);
			base.SetMaxFileSize(int.MaxValue);

			base.SetVideoEncoder(videoEncoder);
			base.SetVideoSize(quality.ResX,quality.ResY);
			base.SetVideoFrameRate(quality.FrameRate);
			base.SetVideoEncodingBitRate(quality.BitRate);


			//SetAudioSource(Android.Media.AudioSource.Mic);
			/*SetVideoSource(Android.Media.VideoSource.Camera);
			
			SetOutputFormat(Android.Media.OutputFormat.ThreeGpp);
			//SetAudioEncoder(Android.Media.AudioEncoder.AmrNb);
			SetVideoEncoder(Android.Media.VideoEncoder.H263);
			SetVideoSize(640,480);
			SetVideoFrameRate(15);
			SetVideoEncodingBitRate(500000);*/

			base.SetPreviewDisplay(surfaceHolder.Surface);
			base.Prepare();
			// Reset flash state to ensure that default behavior is to turn it off
			flashState = false;
			
			// Quality has been updated
			qualityHasChanged = false;
			
		}
Ejemplo n.º 53
0
		public CameraPreview (Context context, Camera camera, Camera.CameraInfo cameraInfo, 
			SurfaceOrientation displayOrientation) :
			base (context)
		{
			// Do not initialize if no camera has been set
			if (camera == null || cameraInfo == null)
				return;
			
			this.camera = camera;
			this.cameraInfo = cameraInfo;
			this.displayOrientation = displayOrientation;

			// Install a SurfaceHolder.Callback so we get notified when the
			// underlying surface is created and destroyed.
			holder = Holder;
			holder.AddCallback (this);
		}
Ejemplo n.º 54
0
      /// <summary>
      /// Turn the lamp on
      /// </summary>
      public void TurnOn()
      {
          // Additional information about using the camera light here:
          // http://forums.xamarin.com/discussion/24237/camera-led-or-flash
          // http://stackoverflow.com/questions/5503480/use-camera-flashlight-in-android?rq=1

          if (camera == null)
              camera = Camera.Open();

          if (camera == null)
          {
              Debug.WriteLine("Camera failed to initialize");
              return;
          }

          var p = camera.GetParameters();
          var supportedFlashModes = p.SupportedFlashModes;

          if (supportedFlashModes == null)
              supportedFlashModes = new List<string>();

          var flashMode = string.Empty;

          if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
                  flashMode = Android.Hardware.Camera.Parameters.FlashModeTorch;

          if (!string.IsNullOrEmpty(flashMode))
          {
              p.FlashMode = flashMode;
              camera.SetParameters(p);
          }

          camera.StartPreview();

          // nexus 5 fix here: http://stackoverflow.com/questions/21417332/nexus-5-4-4-2-flashlight-led-not-turning-on
          try
          {
              camera.SetPreviewTexture(new SurfaceTexture(0));
          }
          catch (IOException ex)
          {
              // Ignore
          }

      }
Ejemplo n.º 55
0
        public void OnSurfaceTextureAvailable(Android.Graphics.SurfaceTexture surface, int width, int height)
        {
            // var camInfo = new Camera.CameraInfo();

                    _camera = Camera.Open(0);

               // _camera = Camera.Open();
            _textureView.LayoutParameters = new FrameLayout.LayoutParams(width, height);
            try
            {
                _camera.SetPreviewTexture(surface);
                _camera.StartPreview();
            }
            catch (Java.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 56
0
        public void OnSurfaceTextureAvailable(Android.Graphics.SurfaceTexture surface, int width, int height)
        {
            _camera = Camera.Open ();
            ConfigureCamera ();

            Preview preview = new Preview ();
            preview.OnFrame += OnPreviewFrame;
            _camera.SetPreviewCallback (preview);

            _textureView.LayoutParameters = new FrameLayout.LayoutParams (width, height);

            try {
                _camera.SetPreviewTexture (surface);
                _camera.StartPreview ();

            } catch (Exception e) {
                Console.WriteLine (e.Message);
            }
        }
Ejemplo n.º 57
0
 public void OnSurfaceTextureAvailable (Android.Graphics.SurfaceTexture surface, int width, int height)
 {
     _camera = Camera.Open ();
     
     var previewSize = _camera.GetParameters ().PreviewSize;
     _textureView.LayoutParameters = 
         new FrameLayout.LayoutParams (previewSize.Width, previewSize.Height, (int)GravityFlags.Center);
     
     try {
         _camera.SetPreviewTexture (surface);
         _camera.StartPreview ();
     } catch (Java.IO.IOException ex) {
         Console.WriteLine (ex.Message);
     }
     
     // this is the sort of thing TextureView enables
     _textureView.Rotation = 45.0f;
     _textureView.Alpha = 0.5f;
 }
Ejemplo n.º 58
0
		public void OnPreviewFrame (byte[] data, Camera camera)
		{
			var parameters = camera.GetParameters ();
			var size = parameters.PreviewSize;

			var barcode = new Image (size.Width, size.Height, "Y800");
			barcode.SetData (data);

			var result = scanner.ScanImage (barcode);

			if (result == 0)
				return;
			

			camera.SetPreviewCallback (null);
			camera.StopPreview ();

			var scannerResult = GetScannerResult ();

			ScanComplete?.Invoke (this, new ScanCompleteEventArgs (scannerResult));
		}
Ejemplo n.º 59
0
 public void OnPictureTaken(byte[] data, Camera camera)
 {
     // Create a filename
     string filename = UUID.RandomUUID().ToString() + ".jpg";
     // Save the jpeg data to disk
     Stream os = null;
     bool success = true;
     try {
         os = Activity.OpenFileOutput(filename, Android.Content.FileCreationMode.Private);
         os.Write(data, 0, data.Length);
     }
     catch (Exception ex) {
         Debug.WriteLine(String.Format("Error writing image to file: {0}, {1}", filename, ex.Message), TAG);
         success = false;
     }
     finally {
         try {
             if (os != null)
                 os.Close();
         }
         catch (Exception ex) {
             Debug.WriteLine(String.Format("Error closing file: {0}, {1}", filename, ex.Message), TAG);
             success = false;
         }
     }
     // Set the photo filename n the result intent
     if (success) {
         Debug.WriteLine(String.Format("Jpeg saved at: {0}", filename), TAG);
         Intent i = new Intent();
         i.PutExtra(EXTRA_PHOTO_FILENAME, filename);
         Activity.SetResult(Result.Ok, i);
     }
     else {
         Activity.SetResult(Result.Canceled);
     }
     Activity.Finish();
 }
Ejemplo n.º 60
0
      public void OnPreviewFrame(byte[] data, Camera camera)
      {
         if (!_busy && ImagePreview != null)
            try
            {
               _busy = true;
               Camera.Size cSize = camera.GetParameters().PreviewSize;
               _imageSize = new Size(cSize.Width, cSize.Height);
               Size size = _imageSize;
               Image<Bgr, Byte> image = _bgrBuffers.GetBuffer(size, 0);

               GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
               using (Image<Gray, Byte> yuv420sp = new Image<Gray, byte>(size.Width, (size.Height >> 1) * 3, size.Width, handle.AddrOfPinnedObject()))
               {
                  ImagePreview(this, new ImagePreviewEventArgs(yuv420sp, image));
               }
               handle.Free();

               Invalidate();
            }
            finally
            {
               _busy = false;
            }

         if (_cameraPreviewCallbackWithBuffer)
            camera.AddCallbackBuffer(data);
      }