コード例 #1
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);
            }
        }
コード例 #2
0
		protected void StartCamera() {
			if (_Camera == null) {
				_Camera = Camera.Open();
				_CameraSupportedFlashModes = _CameraSupportedFlashModes ?? _Camera.GetParameters().SupportedFlashModes;
				if (_CameraSupportedFlashModes == null || !_CameraSupportedFlashModes.Contains(FlashlightOnMode) || !_CameraSupportedFlashModes.Contains(FlashlightOffMode)) {
					StopCamera();
				}
			}
		}
コード例 #3
0
        /// <summary>
        ///Scanning Improvement, VK 10/2018
        /// </summary>
        public void LowLightMode(bool on)
        {
            var parameters = Camera?.GetParameters();

            if (parameters != null)
            {
                SetBestExposure(parameters, on);
                Camera.SetParameters(parameters);
            }
        }
コード例 #4
0
        /// <summary>
        /// Events when surfacetexture is available, sets camera parameters
        /// </summary>
        /// <param name="surface">Surface</param>
        /// <param name="width">Width</param>
        /// <param name="height">Height</param>
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
#pragma warning disable 618
            camera = Camera.Open((int)cameraType);
            var parameters = camera.GetParameters();
            if (parameters.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
            }
            camera.SetParameters(parameters);
#pragma warning restore 618
            textureView.LayoutParameters = new FrameLayout.LayoutParams(width, height);
            camera.SetPreviewTexture(surface);
            PrepareAndStartCamera();
        }
コード例 #5
0
        public void SurfaceChanged(ISurfaceHolder holder, global::Android.Graphics.Format format, int w, int h)
        {
            if (camera == null)
            {
                return;
            }

            Android.Hardware.Camera.Parameters parameters = camera.GetParameters();

            width  = parameters.PreviewSize.Width;
            height = parameters.PreviewSize.Height;
            //parameters.PreviewFormat = ImageFormatType.Rgb565;
            //parameters.PreviewFrameRate = 15;

            parameters.PreviewFormat = ImageFormatType.Nv21;

            camera.SetParameters(parameters);
            camera.SetDisplayOrientation(90);
            camera.StartPreview();

            cameraResolution = new Size(parameters.PreviewSize.Width, parameters.PreviewSize.Height);

            AutoFocus();
        }
コード例 #6
0
ファイル: RecordActivity.cs プロジェクト: riklugtenberg/Lippz
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Window.RequestFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.Fullscreen | WindowManagerFlags.TurnScreenOn);

            SetContentView(Resource.Layout.RecordWordView);

            _surfaceView   = FindViewById <SurfaceView>(Resource.Id.surfaceView);
            _camera        = GetCameraInstance();
            _surfaceHolder = _surfaceView.Holder;
            _surfaceHolder.AddCallback(this);
            _parameters = _camera.GetParameters();
            StartCamera();
        }
コード例 #7
0
        public BarcodeScannerRenderer(Context context) : base(context)
        {
            cameraInfo = new Camera.CameraInfo();
            Camera.GetCameraInfo(0, cameraInfo);
            cam        = Camera.Open(0);
            parameters = cam.GetParameters();

            Camera.Size size = parameters.PictureSize;
            cheight = size.Height;
            cwidth  = size.Width;

            maxZoom = parameters.MaxZoom;


            cam.SetPreviewCallback(this);
        }
コード例 #8
0
ファイル: Flash.cs プロジェクト: RonildoSouza/HajaLuz
        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;
        }
コード例 #9
0
        public void SetupCamera()
        {
            if (Camera != null)
            {
                return;
            }

            ZXing.Net.Mobile.Android.PermissionsHandler.CheckCameraPermissions(_context);

            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);
                Camera.StartPreview();
            }
            catch (Exception ex)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, ex.ToString());
                return;
            }
            finally
            {
                PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");
            }

            // 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();
            }
        }
コード例 #10
0
        /// <summary>
        /// Toggles the camera torch.
        /// If the camera does not support flash this is a noop.
        /// </summary>
        public void ToggleTorch(AndroidCamera camera, bool state)
        {
            if (camera == null)
            {
                return;
            }

            var parameters = camera.GetParameters();

            var flashMode = determineFlashMode(parameters, state);

            invokeIfAvailable(flashMode, val => {
                this.Debug("Flash mode [{0}]", val);
                parameters.FlashMode = val;
                camera.SetParameters(parameters);
            });
        }
コード例 #11
0
        /// <summary>
        /// Apply camera zoom. The zoom value is capped to the maximum supported zoom value.
        /// If the camera does not support zoom this method is a noop.
        /// </summary>
        public void Zoom(AndroidCamera camera, uint zoom)
        {
            var parameters = camera.GetParameters();

            if (!parameters.IsZoomSupported)
            {
                return;
            }

            var cappedZoom = Convert.ToInt32(zoom);

            cappedZoom = (cappedZoom > parameters.MaxZoom) ? parameters.MaxZoom : cappedZoom;

            this.Debug("Zoom [{0}]", cappedZoom);
            parameters.Zoom = cappedZoom;

            camera.SetParameters(parameters);
        }
コード例 #12
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            camera = Android.Hardware.Camera.Open();
            var parameters = camera.GetParameters();
            var aspect     = ((decimal)height) / ((decimal)width);

            // Find the preview aspect ratio that is closest to the surface aspect
            var previewSize = parameters.SupportedPreviewSizes
                              .OrderBy(s => Math.Abs(s.Width / (decimal)s.Height - aspect))
                              .First();

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

            parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
            camera.SetParameters(parameters);

            camera.SetPreviewTexture(surface);
            StartCamera();
        }
コード例 #13
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;
 }
コード例 #14
0
ファイル: MainActivity.cs プロジェクト: Elmentris/CameraTest
        private void SetCamFocusMode()
        {
            if (_camera == null)
            {
                return;
            }
            var           parameters = _camera.GetParameters();
            List <String> focusModes = parameters.SupportedFocusModes.ToList();

            if (focusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeContinuousPicture))
            {
                parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousPicture;
            }
            else if (focusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeAuto))
            {
                parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeAuto;
            }
            _camera.SetParameters(parameters);
        }
コード例 #15
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            // TODO Auto-generated method stub
            try
            {
                camera = Android.Hardware.Camera.Open();
                Android.Hardware.Camera.Parameters param = camera.GetParameters();

                // Check what resolutions are supported by your camera
                IList <Android.Hardware.Camera.Size> sizes = param.SupportedPictureSizes;

                // setting small image size in order to avoid OOM error
                Android.Hardware.Camera.Size cameraSize = null;
                foreach (Android.Hardware.Camera.Size size in sizes)
                {
                    //set whatever size you need
                    //if(size.height<500) {
                    cameraSize = size;
                    break;
                    //}
                }

                if (cameraSize != null)
                {
                    param.SetPictureSize(cameraSize.Width, cameraSize.Height);
                    camera.SetParameters(param);

                    float ratio = relativeLayout.Height * 1f / cameraSize.Height;
                    float w     = cameraSize.Width * ratio;
                    float h     = cameraSize.Height * ratio;
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams((int)w, (int)h);
                    cameraSurfaceView.LayoutParameters = (lp);
                }
            }
            catch (RuntimeException e)
            {
                Toast.MakeText(
                    ApplicationContext,
                    "Device camera  is not working properly, please try after sometime.",
                    ToastLength.Long).Show();
            }
        }
コード例 #16
0
ファイル: CameraRenderer.cs プロジェクト: meta012/MoodFull
        //turns on or off camera flash
        void ToggleFlashButtonTapped(object sender, EventArgs e)
        {
            //if camera isn't started
            if (!_isCameraStarted)
            {
                return;
            }

            _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 = Android.Hardware.Camera.Parameters.FlashModeTorch;
                    camera.SetParameters(parameters);
                    camera.SetPreviewTexture(surfaceTexture);
                    PrepareAndStartCamera();
                }
            }
            else
            {
                toggleFlashButton.SetBackgroundResource(Resource.Drawable.NoFlashButton);
                camera.StopPreview();
                camera.Release();

                camera = Android.Hardware.Camera.Open((int)cameraType);
                var parameters = camera.GetParameters();
                parameters.FlashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
                camera.SetParameters(parameters);
                camera.SetPreviewTexture(surfaceTexture);
                PrepareAndStartCamera();
            }
        }
コード例 #17
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));
		}
コード例 #18
0
        public void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            Camera.Size size = camera.GetParameters().PreviewSize;
            if (!bCapture)
            {
                return;
            }

            Android.Graphics.YuvImage image = new Android.Graphics.YuvImage(data, Android.Graphics.ImageFormatType.Nv21, size.Width, size.Height, null);
            if (image != null)
            {
                MemoryStream stream = new MemoryStream();
                image.CompressToJpeg(new Android.Graphics.Rect(0, 0, size.Width, size.Height), 80, stream);
                Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeByteArray(stream.ToArray(), 0, (int)stream.Length);
                stream.Close();

                //因为图片会放生旋转,因此要对图片进行旋转到和手机在一个方向上
                var newbmp = rotateMyBitmap(bmp);

                MemoryStream rotateStream = new MemoryStream();
                newbmp.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 90, rotateStream);
                byte[] bitmapData = rotateStream.ToArray();

                var     faceimage = Convert.ToBase64String(bitmapData);
                Message msg       = new Message
                {
                    action = "androidface",
                    face   = faceimage
                };
                var json = JsonConvert.SerializeObject(msg);
                mySocket.Send(json);
            }
            else
            {
                Toast.MakeText(this, "Take photo failure", ToastLength.Short).Show();
            }
            bCapture = false;
        }
コード例 #19
0
        private void ConfigurePreviewSize()
        {
            var cameraParams          = mCamera.GetParameters();
            var supportedPreviewSizes = cameraParams.SupportedPreviewSizes;
            int minDiff = int.MaxValue;

            Android.Hardware.Camera.Size bestSize = null;

            if (Application.Context.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
            {
                foreach (Android.Hardware.Camera.Size size in supportedPreviewSizes)
                {
                    var diff = Math.Abs(size.Width - mTextureView.Width);

                    if (diff < minDiff)
                    {
                        minDiff  = diff;
                        bestSize = size;
                    }
                }
            }
            else
            {
                foreach (Android.Hardware.Camera.Size size in supportedPreviewSizes)
                {
                    var diff = Math.Abs(size.Height - mTextureView.Width);

                    if (diff < minDiff)
                    {
                        minDiff  = diff;
                        bestSize = size;
                    }
                }
            }

            cameraParams.SetPreviewSize(bestSize.Width, bestSize.Height);
            mCamera.SetParameters(cameraParams);
        }
コード例 #20
0
        public void OnSurfaceChanged(Javax.Microedition.Khronos.Opengles.IGL10 gl, int width, int height)
        {
            // Adjust the viewport based on geometry changes,
            // such as screen rotation
            GLES20.GlViewport(0, 0, width, height);

            float ratio = (float)width / height;

            // this projection matrix is applied to object coordinates
            // in the onDrawFrame() method
            Android.Opengl.Matrix.FrustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

            GLES20.GlViewport(0, 0, width, height);
            if (mCamera != null)
            {
                Android.Hardware.Camera.Parameters p = mCamera.GetParameters();
                System.Collections.Generic.IList <Android.Hardware.Camera.Size> sizes = p.SupportedPreviewSizes;
                p.SetPreviewSize(sizes[0].Width, sizes[0].Height);
                mCamera.SetParameters(p);
                //mCamera.SetPreviewDisplay(holder);
                mCamera.StartPreview();
            }
        }
コード例 #21
0
 public void Zoom(bool isZoomIn)
 {
     Camera.Parameters parameters = Camera?.GetParameters();
     if (parameters?.IsZoomSupported == true)
     {
         int maxZoom = parameters.MaxZoom;
         int zoom    = parameters.Zoom;
         if (isZoomIn && zoom < maxZoom)
         {
             zoom++;
         }
         else if (zoom > 0)
         {
             zoom--;
         }
         parameters.Zoom = zoom;
         Camera.SetParameters(parameters);
     }
     else
     {
         Android.Util.Log.Error("lv", "zoom not supported or camera unavailable");
     }
 }
コード例 #22
0
        public void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            try
            {
                noFrames = 0;
                YuvImage yi = new YuvImage(data, camera.GetParameters().PreviewFormat, camera.GetParameters().PreviewSize.Width, camera.GetParameters().PreviewSize.Height, null);

                byte[][] frames = new byte[fragmentation][];

                using MemoryStream ms = new MemoryStream();

                yi.CompressToJpeg(new Rect(0, 0, yi.Width, yi.Height), 20, ms);

                byte[]   jpegBytes = ms.ToArray();
                UdpFrame frame     = new UdpFrame(jpegBytes);

                FrameRefreshed?.Invoke(frame.packages);
            }
            catch (Exception e)
            {
                start();
            }
        }
コード例 #23
0
        private void SvOnTouch(object sender, View.TouchEventArgs touchEventArgs)
        {
            Camera.Parameters cameraParams = _camera.GetParameters();
            var action = touchEventArgs.Event.Action;

            if (touchEventArgs.Event.PointerCount > 1)
            {
                if (action == MotionEventActions.PointerDown)
                {
                    _dist = GetFingerSpacing(touchEventArgs.Event);
                }
                else if (action == MotionEventActions.Move && cameraParams.IsZoomSupported)
                {
                    _camera.CancelAutoFocus();
                    HandleZoom(touchEventArgs.Event, cameraParams);
                }
            }
            touchEventArgs.Handled = true;
        }
コード例 #24
0
 public void SetCamera(Camera camera)
 {
     mCamera = camera;
     if (mCamera != null) {
         mSupportedPreviewSizes = mCamera.GetParameters ()
         .SupportedPreviewSizes;
         RequestLayout ();
     }
 }
コード例 #25
0
        public void OnPreviewFrame(byte [] bytes, Android.Hardware.Camera camera)
        {
            if ((DateTime.Now - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames)
            {
                return;
            }

            try
            {
                var cameraParameters = camera.GetParameters();
                var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);

                if (barcodeReader == null)
                {
                    barcodeReader = new BarcodeReader(null, null, null, (p, w, h, f) =>
                                                      new PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false));
                    //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))

                    if (this.options.TryHarder.HasValue)
                    {
                        barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
                    }
                    if (this.options.PureBarcode.HasValue)
                    {
                        barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value;
                    }
                    if (!string.IsNullOrEmpty(this.options.CharacterSet))
                    {
                        barcodeReader.Options.CharacterSet = this.options.CharacterSet;
                    }
                    if (this.options.TryInverted.HasValue)
                    {
                        barcodeReader.TryInverted = this.options.TryInverted.Value;
                    }

                    if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0)
                    {
                        barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>();

                        foreach (var pf in this.options.PossibleFormats)
                        {
                            barcodeReader.Options.PossibleFormats.Add(pf);
                        }
                    }

                    //Always autorotate on android
                    barcodeReader.AutoRotate = true;
                }

                //Try and decode the result
                var result = barcodeReader.Decode(img.GetYuvData(), img.Width, img.Height, RGBLuminanceSource.BitmapFormat.Unknown);

                lastPreviewAnalysis = DateTime.Now;

                if (result == null || string.IsNullOrEmpty(result.Text))
                {
                    return;
                }

                Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

                ShutdownCamera();

                callback(result);
            } catch (ReaderException) {
                Android.Util.Log.Debug("ZXing.Mobile", "No barcode Found");
                // ignore this exception; it happens every time there is a failed scan
            } catch (Exception) {
                // TODO: this one is unexpected.. log or otherwise handle it
                throw;
            }
        }
コード例 #26
0
ファイル: CameraPreview.cs プロジェクト: reidblomquist/emgucv
 private static Camera.Size SetCameraOptimalPreviewSize(Camera camera, int w, int h)
 {
    Camera.Parameters parameters = camera.GetParameters();
    IList<Camera.Size> sizes = parameters.SupportedPreviewSizes;
    int maxWidth = 512, maxHeight = 512;
    Camera.Size optimalSize = GetOptimalPreviewSize(sizes, w, h, maxWidth, maxHeight);
    parameters.SetPreviewSize(optimalSize.Width, optimalSize.Height);
    camera.SetParameters(parameters);
    return optimalSize;
 }
コード例 #27
0
        protected override void OnStart()
        {
            try
            {
                if (Camera == null)
                {
                    Camera = Hardware.Camera.Open(cameraIndex);
                }

                if (Texture == null)
                {
                    Texture = new Graphics.SurfaceTexture(0);
                }

                CameraPreviewCallback callback = new CameraPreviewCallback();
                callback.PreviewUpdated += Callback_PreviewUpdated;

                Hardware.Camera.Parameters  parameter   = Camera.GetParameters();
                List <Hardware.Camera.Size> supportSize = parameter.SupportedPreviewSizes.OrderByDescending(x => x.Width).ToList();
                foreach (Hardware.Camera.Size size in supportSize)
                {
                    CvLogger.Log(this, $"Camera Support Size: W{size.Width},H{size.Height}");

                    if (size.Width == 960 && size.Height == 720)
                    {
                        parameter.SetPreviewSize(size.Width, size.Height);
                        CvLogger.Log(this, $"SET Camera Size: W{size.Width},H{size.Height}");
                    }
                }

                string[] supportedFocusMode = parameter.SupportedFocusModes.ToArray();
                if (supportedFocusMode.Contains(Hardware.Camera.Parameters.FocusModeContinuousVideo))
                {
                    parameter.FocusMode = Hardware.Camera.Parameters.FocusModeContinuousVideo;
                }
                else if (supportedFocusMode.Contains(Hardware.Camera.Parameters.FocusModeContinuousPicture))
                {
                    parameter.FocusMode = Hardware.Camera.Parameters.FocusModeContinuousPicture;
                }
                parameter.ColorEffect = Hardware.Camera.Parameters.EffectNone;

                width      = parameter.PreviewSize.Width;
                height     = parameter.PreviewSize.Height;
                fps        = parameter.PreviewFrameRate;
                cameraType = parameter.PreviewFormat;

                CvLogger.Log(this, string.Format("Camera is creating W{0} H{1} FPS{2}", width, height, fps));
                Camera.SetParameters(parameter);

                Camera.SetPreviewCallback(callback);
                Camera.SetPreviewTexture(Texture);
                Camera.StartPreview();

                cameraOn = true;
            }
            catch (Exception ex)
            {
                CvLogger.Log(this, "Camera Init Failed.\n" + ex.ToString());

                Dispose();

                throw new ArgumentException("Camera Exception", ex);
            }
        }
コード例 #28
0
        void OnSurfaceChanged()
        {
            surfaceChanged = true;

            if (camera == null)
            {
                return;
            }

            var perf = PerformanceCounter.Start();

            var parameters = camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;


            var availableResolutions = new List <CameraResolution> ();

            foreach (var sps in parameters.SupportedPreviewSizes)
            {
                availableResolutions.Add(new CameraResolution {
                    Width  = sps.Width,
                    Height = sps.Height
                });
            }

            // Try and get a desired resolution from the options selector
            var resolution = scanningOptions.GetResolution(availableResolutions);

            // If the user did not specify a resolution, let's try and find a suitable one
            if (resolution == null)
            {
                // Loop through all supported sizes
                foreach (var sps in parameters.SupportedPreviewSizes)
                {
                    // Find one that's >= 640x360 but <= 1000x1000
                    // This will likely pick the *smallest* size in that range, which should be fine
                    if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                    {
                        resolution = new CameraResolution {
                            Width  = sps.Width,
                            Height = sps.Height
                        };
                        break;
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            camera.SetParameters(parameters);

            SetCameraDisplayOrientation(this.activity);

            camera.SetPreviewDisplay(this.Holder);
            camera.StartPreview();

            PerformanceCounter.Stop(perf, "SurfaceChanged took {0}ms");

            // Reset cancel token source so we can do things like autofocus
            autoFocusTokenCancelSrc = new CancellationTokenSource();

            AutoFocus();
        }
コード例 #29
0
        public void SwitchCamera(Camera camera)
        {
            SetCamera (camera);
            try {
                camera.SetPreviewDisplay (mHolder);
            } catch (IOException exception) {
                Log.Error (TAG, "IOException caused by setPreviewDisplay()", exception);
            }
            Camera.Parameters parameters = camera.GetParameters ();
            parameters.SetPreviewSize (mPreviewSize.Width, mPreviewSize.Height);
            RequestLayout();

            camera.SetParameters (parameters);
        }
コード例 #30
0
        private void AutoFocus(int x, int y, bool useCoordinates)
        {
            if (Camera == null)
            {
                return;
            }

            if (_scannerHost.ScanningOptions.DisableAutofocus)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocus Disabled");
                return;
            }

            var cameraParams = Camera.GetParameters();

            Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocus Requested");

            // Cancel any previous requests
            Camera.CancelAutoFocus();

            try
            {
                // If we want to use coordinates
                // Also only if our camera supports Auto focus mode
                // Since FocusAreas only really work with FocusModeAuto set
                if (useCoordinates &&
                    cameraParams.SupportedFocusModes.Contains(Camera.Parameters.FocusModeAuto))
                {
                    // Let's give the touched area a 20 x 20 minimum size rect to focus on
                    // So we'll offset -10 from the center of the touch and then
                    // make a rect of 20 to give an area to focus on based on the center of the touch
                    x = x - 10;
                    y = y - 10;

                    // Ensure we don't go over the -1000 to 1000 limit of focus area
                    if (x >= 1000)
                    {
                        x = 980;
                    }
                    if (x < -1000)
                    {
                        x = -1000;
                    }
                    if (y >= 1000)
                    {
                        y = 980;
                    }
                    if (y < -1000)
                    {
                        y = -1000;
                    }

                    // Explicitly set FocusModeAuto since Focus areas only work with this setting
                    cameraParams.FocusMode = Camera.Parameters.FocusModeAuto;
                    // Add our focus area
                    cameraParams.FocusAreas = new List <Camera.Area>
                    {
                        new Camera.Area(new Rect(x, y, x + 20, y + 20), 1000)
                    };
                    Camera.SetParameters(cameraParams);
                }

                // Finally autofocus (weather we used focus areas or not)
                Camera.AutoFocus(_cameraEventListener);
            }
            catch (Exception ex)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocus Failed: {0}", ex);
            }
        }
コード例 #31
0
        private void configureCameraAndStartPreview(Android.Hardware.Camera camera)
        {
            // Setting camera parameters when preview is running can cause crashes on some android devices
            stopPreview();

            // Configure camera orientation. This is needed for both correct preview orientation
            // and recognition
            orientation = getCameraOrientation();
            camera.SetDisplayOrientation(orientation);

            // Configure camera parameters
            Android.Hardware.Camera.Parameters parameters = camera.GetParameters();

            // Select preview size. The preferred size for Text Capture scenario is 1080x720. In some scenarios you might
            // consider using higher resolution (small text, complex background) or lower resolution (better performance, less noise)
            cameraPreviewSize = null;
            foreach (Android.Hardware.Camera.Size size in parameters.SupportedPreviewSizes)
            {
                if (size.Height <= 720 || size.Width <= 720)
                {
                    if (cameraPreviewSize == null)
                    {
                        cameraPreviewSize = size;
                    }
                    else
                    {
                        int resultArea = cameraPreviewSize.Width * cameraPreviewSize.Height;
                        int newArea    = size.Width * size.Height;
                        if (newArea > resultArea)
                        {
                            cameraPreviewSize = size;
                        }
                    }
                }
            }
            parameters.SetPreviewSize(cameraPreviewSize.Width, cameraPreviewSize.Height);

            // Zoom
            parameters.Zoom = cameraZoom;
            // Buffer format. The only currently supported format is NV21
            parameters.PreviewFormat = Android.Graphics.ImageFormatType.Nv21;
            // Default focus mode
            parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeAuto;

            // Done
            camera.SetParameters(parameters);

            // The camera will fill the buffers with image data and notify us through the callback.
            // The buffers will be sent to camera on requests from recognition service (see implementation
            // of ITextCaptureService.Callback.onRequestLatestFrame above)
            camera.SetPreviewCallbackWithBuffer(cameraPreviewCallback);

            // Clear the previous recognition results if any
            clearRecognitionResults();

            // Width and height of the preview according to the current screen rotation
            int width  = 0;
            int height = 0;

            switch (orientation)
            {
            case 0:
            case 180:
                width  = cameraPreviewSize.Width;
                height = cameraPreviewSize.Height;
                break;

            case 90:
            case 270:
                width  = cameraPreviewSize.Height;
                height = cameraPreviewSize.Width;
                break;
            }

            // Configure the view scale and area of interest (camera sees it as rotated 90 degrees, so
            // there's some confusion with what is width and what is height)
            surfaceViewWithOverlay.setScaleX(surfaceViewWithOverlay.Width, width);
            surfaceViewWithOverlay.setScaleY(surfaceViewWithOverlay.Height, height);
            // Area of interest
            int marginWidth  = (areaOfInterestMargin_PercentOfWidth * width) / 100;
            int marginHeight = (areaOfInterestMargin_PercentOfHeight * height) / 100;

            surfaceViewWithOverlay.setAreaOfInterest(
                new Rect(marginWidth, marginHeight, width - marginWidth,
                         height - marginHeight));

            // Start preview
            camera.StartPreview();

            setCameraFocusMode(Android.Hardware.Camera.Parameters.FocusModeAuto);
            autoFocus(finishCameraInitialisationAutoFocusCallback);

            inPreview = true;
        }
コード例 #32
0
        // Sets camera focus mode and focus area
        public void setCameraFocusMode(string mode)
        {
            // Camera sees it as rotated 90 degrees, so there's some confusion with what is width and what is height)
            int  width             = 0;
            int  height            = 0;
            int  halfCoordinates   = 1000;
            int  lengthCoordinates = 2000;
            Rect area = new Rect();

            surfaceViewWithOverlay.GetDrawingRect(area);
            switch (orientation)
            {
            case 0:
            case 180:
                height = cameraPreviewSize.Height;
                width  = cameraPreviewSize.Width;
                break;

            case 90:
            case 270:
                width  = cameraPreviewSize.Height;
                height = cameraPreviewSize.Width;
                break;
            }

            camera.CancelAutoFocus();
            Android.Hardware.Camera.Parameters parameters = camera.GetParameters();
            // Set focus and metering area equal to the area of interest. This action is essential because by defaults camera
            // focuses on the center of the frame, while the area of interest in this sample application is at the top
            List <Android.Hardware.Camera.Area> focusAreas = new List <Android.Hardware.Camera.Area>();
            Rect areasRect;

            switch (orientation)
            {
            case 0:
                areasRect = new Rect(
                    -halfCoordinates + area.Left * lengthCoordinates / width,
                    -halfCoordinates + area.Top * lengthCoordinates / height,
                    -halfCoordinates + lengthCoordinates * area.Right / width,
                    -halfCoordinates + lengthCoordinates * area.Bottom / height
                    );
                break;

            case 180:
                areasRect = new Rect(
                    halfCoordinates - area.Right * lengthCoordinates / width,
                    halfCoordinates - area.Bottom * lengthCoordinates / height,
                    halfCoordinates - lengthCoordinates * area.Left / width,
                    halfCoordinates - lengthCoordinates * area.Top / height
                    );
                break;

            case 90:
                areasRect = new Rect(
                    -halfCoordinates + area.Top * lengthCoordinates / height,
                    halfCoordinates - area.Right * lengthCoordinates / width,
                    -halfCoordinates + lengthCoordinates * area.Bottom / height,
                    halfCoordinates - lengthCoordinates * area.Left / width
                    );
                break;

            case 270:
                areasRect = new Rect(
                    halfCoordinates - area.Bottom * lengthCoordinates / height,
                    -halfCoordinates + area.Left * lengthCoordinates / width,
                    halfCoordinates - lengthCoordinates * area.Top / height,
                    -halfCoordinates + lengthCoordinates * area.Right / width
                    );
                break;

            default:
                throw new IllegalArgumentException();
            }

            focusAreas.Add(new Android.Hardware.Camera.Area(areasRect, 800));
            if (parameters.MaxNumFocusAreas >= focusAreas.Count)
            {
                parameters.FocusAreas = focusAreas;
            }
            if (parameters.MaxNumMeteringAreas >= focusAreas.Count)
            {
                parameters.MeteringAreas = focusAreas;
            }

            parameters.FocusMode = mode;

            // Commit the camera parameters
            camera.SetParameters(parameters);
        }
コード例 #33
0
        /// <summary>
        /// Create the camera and try to set auto focus with flash
        /// </summary>
        /// <param name="holder"></param>
		public void CreateCamera(ISurfaceHolder holder) {
			try
			{
				_camera = Camera.Open();
				Camera.Parameters p = _camera.GetParameters();
				p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
				p.JpegQuality = 100;
				hasAutoFocus = (p.SupportedFocusModes.Contains(Camera.Parameters.FocusModeAuto));
				if (hasAutoFocus)
				{
					p.FocusMode = Camera.Parameters.FocusModeAuto;
					focusReady = true;
				}
				else if (p.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
				{
					p.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
				}
				if (p.SupportedFlashModes.Contains(Camera.Parameters.FlashModeOn))
				{
					p.FlashMode = Camera.Parameters.FlashModeOn;
				}
				_camera.SetParameters(p);
				_camera.SetDisplayOrientation(90);
				_camera.SetPreviewCallback(this);
				_camera.Lock();
				_camera.SetPreviewDisplay(holder);
				_camera.StartPreview();
				if (hasAutoFocus)
				{
					Toast.MakeText(this, "Press screen to focus", ToastLength.Long).Show();
				}
			}
			catch (Exception e)
			{
			}
		}
コード例 #34
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);
      }
コード例 #35
0
        public void OnPreviewFrame(byte [] bytes, Android.Hardware.Camera camera)
        {
            //Check and see if we're still processing a previous frame
            if (processingTask != null && !processingTask.IsCompleted)
            {
                return;
            }

            if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames)
            {
                return;
            }

            var cameraParameters = camera.GetParameters();
            var width            = cameraParameters.PreviewSize.Width;
            var height           = cameraParameters.PreviewSize.Height;

            //var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);
            lastPreviewAnalysis = DateTime.UtcNow;

            processingTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    if (barcodeReader == null)
                    {
                        barcodeReader = new BarcodeReader(null, null, null, (p, w, h, f) =>
                                                          new PlanarYUVLuminanceSource(p, w, h, 0, 0, w, h, false));
                        //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))

                        if (this.options.TryHarder.HasValue)
                        {
                            barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
                        }
                        if (this.options.PureBarcode.HasValue)
                        {
                            barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value;
                        }
                        if (!string.IsNullOrEmpty(this.options.CharacterSet))
                        {
                            barcodeReader.Options.CharacterSet = this.options.CharacterSet;
                        }
                        if (this.options.TryInverted.HasValue)
                        {
                            barcodeReader.TryInverted = this.options.TryInverted.Value;
                        }

                        if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0)
                        {
                            barcodeReader.Options.PossibleFormats = new List <BarcodeFormat> ();

                            foreach (var pf in this.options.PossibleFormats)
                            {
                                barcodeReader.Options.PossibleFormats.Add(pf);
                            }
                        }
                    }

                    bool rotate   = false;
                    int newWidth  = width;
                    int newHeight = height;

                    var cDegrees = getCameraDisplayOrientation(this.activity);

                    if (cDegrees == 90 || cDegrees == 270)
                    {
                        rotate    = true;
                        newWidth  = height;
                        newHeight = width;
                    }

                    var start = PerformanceCounter.Start();

                    if (rotate)
                    {
                        bytes = rotateCounterClockwise(bytes, width, height);
                    }

                    var result = barcodeReader.Decode(bytes, newWidth, newHeight, RGBLuminanceSource.BitmapFormat.Unknown);

                    PerformanceCounter.Stop(start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")");

                    if (result == null || string.IsNullOrEmpty(result.Text))
                    {
                        return;
                    }

                    Android.Util.Log.Debug("ZXing.Mobile", "Barcode Found: " + result.Text);

                    ShutdownCamera();

                    callback(result);
                }
                catch (ReaderException)
                {
                    Android.Util.Log.Debug("ZXing.Mobile", "No barcode Found");
                    // ignore this exception; it happens every time there is a failed scan
                }
                catch (Exception)
                {
                    // TODO: this one is unexpected.. log or otherwise handle it
                    throw;
                }
            });
        }
コード例 #36
0
		// getting camera parameters
		private void GetCamera() {
			if (camera == null) {
				try {
					camera = Android.Hardware.Camera.Open();
					params1 = camera.GetParameters();
				} catch (Exception e) {
					Log.Error("Camera Error. Failed to Open. Error: ", e.Message);
				}
			}
		}
コード例 #37
0
        private void ApplyCameraSettings()
        {
            if (Camera == null)
            {
                OpenCamera();
            }

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

            var parameters = Camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;

            var supportedFocusModes = parameters.SupportedFocusModes;

            if (_scannerHost.ScanningOptions.DisableAutofocus)
            {
                parameters.FocusMode = Camera.Parameters.FocusModeFixed;
            }
            else 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]);
            }

            CameraResolution resolution = null;
            var supportedPreviewSizes   = parameters.SupportedPreviewSizes;

            if (supportedPreviewSizes != null)
            {
                var availableResolutions = supportedPreviewSizes.Select(sps => new CameraResolution
                {
                    Width  = sps.Width,
                    Height = sps.Height
                });

                // Try and get a desired resolution from the options selector
                resolution = _scannerHost.ScanningOptions.GetResolution(availableResolutions.ToList());

                // If the user did not specify a resolution, let's try and find a suitable one
                if (resolution == null)
                {
                    foreach (var sps in supportedPreviewSizes)
                    {
                        if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                        {
                            resolution = new CameraResolution
                            {
                                Width  = sps.Width,
                                Height = sps.Height
                            };
                            break;
                        }
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution
                {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG,
                                       "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            Camera.SetParameters(parameters);

            SetCameraDisplayOrientation();
        }
コード例 #38
0
        private void ApplyCameraSettings()
        {
            if (Camera == null)
            {
                OpenCamera();
            }

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

            var parameters = Camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;

            var supportedFocusModes = parameters.SupportedFocusModes;

            if (_scannerHost.ScanningOptions.DisableAutofocus)
            {
                parameters.FocusMode = Camera.Parameters.FocusModeFixed;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeAuto))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeAuto;
            }
            else 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.FocusModeFixed))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeFixed;
            }


            Log.Debug(MobileBarcodeScanner.TAG,
                      $"FocusMode ={parameters.FocusMode}");
            var selectedFps = parameters.SupportedPreviewFpsRange.FirstOrDefault();

            if (selectedFps != null)
            {
                Log.Debug(MobileBarcodeScanner.TAG,
                          $"Old Selected fps Min:{selectedFps[0]}, Max {selectedFps[1]}");
                // 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;
                //}

                /// <summary>
                ///Scanning Improvement, VK 10/2018
                /// </summary>
                foreach (var fpsRange in parameters.SupportedPreviewFpsRange)
                {
                    if (fpsRange[1] > selectedFps[1] || fpsRange[1] == selectedFps[1] && fpsRange[0] < selectedFps[0])
                    {
                        selectedFps = fpsRange;
                    }
                }

                Log.Debug(MobileBarcodeScanner.TAG,
                          $" Setting Selected fps to Min:{selectedFps[0]}, Max {selectedFps[1]}");

                /// <summary>
                ///Scanning Improvement, Apacheta corporation 11/14/2018
                ///Changed the fps to use low and high. instead of low value and low value ie., selectedFps[0].
                ///Old code ::  parameters.SetPreviewFpsRange(selectedFps[0], selectedFps[0]);
                /// </summary>
                parameters.SetPreviewFpsRange(selectedFps[0], selectedFps[1]);
            }

            if (_scannerHost.ScanningOptions.LowLightMode == true)
            {
                SetBestExposure(parameters, parameters.FlashMode != Camera.Parameters.FlashModeOn);
            }

            /*
             * Edited by VK - Apacheta corporation 11/14/2018
             * Improvements based on zxing android library
             * - Setting default auto focus areas instead of single focus point
             * - Setting Barcode scene mode if available for the device
             * - Set metering to improve lighting/ exposure in the focused area (i.e., rectangular focus area in the center)
             * - **** Imp ==> In UI project a layout should be created to mask other areas except the center rectangular area.
             *                  To inform the user that app/ camera only scans the center rectangular area of the device.
             */
            SetDefaultFocusArea(parameters);
            SetBarcodeSceneMode(parameters);
            SetMetering(parameters);

            CameraResolution resolution = null;
            var supportedPreviewSizes   = parameters.SupportedPreviewSizes;

            if (supportedPreviewSizes != null)
            {
                var availableResolutions = supportedPreviewSizes.Select(sps => new CameraResolution
                {
                    Width  = sps.Width,
                    Height = sps.Height
                });

                // Try and get a desired resolution from the options selector
                resolution = _scannerHost.ScanningOptions.GetResolution(availableResolutions.ToList());

                // If the user did not specify a resolution, let's try and find a suitable one
                if (resolution == null)
                {
                    foreach (var sps in supportedPreviewSizes)
                    {
                        if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                        {
                            resolution = new CameraResolution
                            {
                                Width  = sps.Width,
                                Height = sps.Height
                            };
                            break;
                        }
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution
                {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Log.Debug(MobileBarcodeScanner.TAG,
                          "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            Camera.SetParameters(parameters);

            SetCameraDisplayOrientation();
        }
コード例 #39
0
        public void SetupCamera()
        {
            if (Camera != null)
            {
                return;
            }

            ZXing.Net.Mobile.Android.PermissionsHandler.CheckCameraPermissions(_context);

            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);


                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(MobileBarcodeScanner.TAG, ex.ToString());
                return;
            }
            finally
            {
                PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");
            }

            // 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();
            }
        }
コード例 #40
0
ファイル: CameraManager.cs プロジェクト: butaman/AutoSendPic
        public void OnPreviewFrame(byte[] data, Camera camera)
        {
            lock (syncObj)
            {
                if (flgReqTakePic)
                {
                    flgReqTakePic = false;
                }
                else
                {
                    return;
                }

            }

            try
            {

                //JPEG圧縮を行うため、別スレッドで処理を行う
                TaskExt.Run(() =>
                {
                    //データを読み取り
                    Camera.Parameters parameters = camera.GetParameters();
                    Camera.Size size = parameters.PreviewSize;
                    using (Android.Graphics.YuvImage image = new Android.Graphics.YuvImage(data, parameters.PreviewFormat,
                            size.Width, size.Height, null))
                    {

                        //データをJPGに変換してメモリに保持
                        using (MemoryStream ms = new MemoryStream())
                        {
                            image.CompressToJpeg(
                                new Android.Graphics.Rect(0, 0, image.Width, image.Height), 90,
                                ms);

                            ms.Close(); // Closeしてからでないと、ToArrayは正常に取得できない

                            byte[] jpegData = ms.ToArray();
                            OnPictureTaken(new PicData(jpegData, DateTime.Now, new LocationData()));

                        }

                    }
                });
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
コード例 #41
0
        public async Task StartScanningAsync(Action <Result> scanResultCallback, MobileBarcodeScanningOptions options = null)
        {
            this.callback        = scanResultCallback;
            this.scanningOptions = options ?? MobileBarcodeScanningOptions.Default;

            lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(this.scanningOptions.InitialDelayBeforeAnalyzingFrames);
            isAnalyzing         = true;

            Console.WriteLine("StartScanning");

            CheckCameraPermissions();

            var perf = PerformanceCounter.Start();

            GetExclusiveAccess();

            try {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    if (this.scanningOptions.UseFrontCameraIfAvailable.HasValue && this.scanningOptions.UseFrontCameraIfAvailable.Value)
                    {
                        whichCamera = CameraFacing.Front;
                    }

                    for (int i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
                            camera   = Camera.Open(i);
                            cameraId = i;
                            found    = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
                        camera   = Camera.Open(0);
                        cameraId = 0;
                    }
                }
                else
                {
                    camera = Camera.Open();
                }

                if (camera == null)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Camera is null :(");
                }

                camera.SetPreviewCallback(this);
            } catch (Exception ex) {
                ShutdownCamera();

                Console.WriteLine("Setup Error: " + ex);
            }

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

            if (!surfaceChanged)
            {
                await waitSurface.WaitAsync();
            }

            if (camera == null)
            {
                return;
            }

            perf = PerformanceCounter.Start();

            var parameters = camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;


            var availableResolutions = new List <CameraResolution> ();

            foreach (var sps in parameters.SupportedPreviewSizes)
            {
                availableResolutions.Add(new CameraResolution {
                    Width  = sps.Width,
                    Height = sps.Height
                });
            }

            // Try and get a desired resolution from the options selector
            var resolution = scanningOptions.GetResolution(availableResolutions);

            // If the user did not specify a resolution, let's try and find a suitable one
            if (resolution == null)
            {
                // Loop through all supported sizes
                foreach (var sps in parameters.SupportedPreviewSizes)
                {
                    // Find one that's >= 640x360 but <= 1000x1000
                    // This will likely pick the *smallest* size in that range, which should be fine
                    if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                    {
                        resolution = new CameraResolution {
                            Width  = sps.Width,
                            Height = sps.Height
                        };
                        break;
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            camera.SetParameters(parameters);

            SetCameraDisplayOrientation(this.activity);

            camera.SetPreviewDisplay(this.Holder);
            camera.StartPreview();

            PerformanceCounter.Stop(perf, "SurfaceChanged took {0}ms");

            AutoFocus();
        }
コード例 #42
0
 // Checks that FOCUS_MODE_CONTINUOUS_VIDEO supported
 public bool isContinuousVideoFocusModeEnabled(Android.Hardware.Camera camera)
 {
     return(camera.GetParameters().SupportedFocusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeContinuousVideo));
 }