Exemplo n.º 1
0
 private void SwitchFlash(bool On)
 {
     try
     {
         Android.Hardware.Camera _camer = GetCamera();
         if (On)
         {
             if (_camer != null)
             {
                 var prms = _camer.GetParameters();
                 prms.FlashMode = Android.Hardware.Camera.Parameters.FlashModeTorch;
                 _camer.SetParameters(prms);
             }
         }
         else
         {
             if (_camer != null)
             {
                 var prms = _camer.GetParameters();
                 prms.FlashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
                 _camer.SetParameters(prms);
             }
         }
     }
     catch (Exception es)
     {
         Log.Info("Release", "txtRecognizer.SetProcessor " + es.Message);
     }
 }
Exemplo n.º 2
0
        private void SetupCamera()
        {
            // Get the camera object directly from the parent activity
            // This is safe and doesn't throw NullPointerException or "camera has been released"
            // when resuming from a paused state, because it always takes the latest camera instance
            //MainActivity parent = (PhototasticCamera)this.getContext();
            //Camera camera = parent.getCamera();

            if (_camera == null)
            {
                Console.WriteLine("setupCamera(): warning, camera is null");
                return;
            }

            var parameters = _camera.GetParameters();

            var bestPreviewSize = GetBestSize(parameters.SupportedPictureSizes, PreviewMaxWidth);
            var bestPictureSize = GetBestSize(parameters.SupportedPictureSizes, PictureMaxWidth);

            parameters.SetPreviewSize(bestPreviewSize.Width, bestPreviewSize.Height);
            parameters.SetPreviewSize(bestPictureSize.Width, bestPictureSize.Height);

            parameters.PreviewFormat = ImageFormatType.Nv21;  // NV21 is the most supported format for preview frames
            parameters.PictureFormat = ImageFormatType.Jpeg;  // JPEG for full resolution images

            // example of settings
            try
            {
                parameters.FlashMode = Camera.Parameters.FlashModeOff;
            }
            catch (NoSuchMethodError e)
            {
                // remember that not all the devices support a given feature
                Console.WriteLine($"setupCamera(): this camera ignored some unsupported settings. {e}");
            }

            _camera.SetParameters(parameters); // save everything

            // print saved parameters
            int prevWidth  = _camera.GetParameters().PreviewSize.Width;
            int prevHeight = _camera.GetParameters().PreviewSize.Height;
            int picWidth   = _camera.GetParameters().PictureSize.Width;
            int picHeight  = _camera.GetParameters().PictureSize.Height;

            // here: previewBuffer initialization. It will host every frame that comes out
            // from the preview, so it must be big enough.
            // After that, it's linked to the camera with the setCameraCallback() method.
            try
            {
                this._previewBuffer = new byte[prevWidth * prevHeight * ImageFormat.GetBitsPerPixel(_camera.GetParameters().PreviewFormat) / 8];
                SetCameraCallBack();
            }
            catch (IOException e)
            {
                Console.WriteLine($"setupCamera(): error setting camera callback., {e}");
            }
        }
Exemplo n.º 3
0
        public CameraPreview(Context context, Android.Hardware.Camera camera) : base(context)
        {
            _mCamera = camera;
            Holder.AddCallback(this);

            _mSupportedPreviewSizes = _mCamera.GetParameters().SupportedPreviewSizes.ToList();
            _mSupportedPictureSizes = _mCamera.GetParameters().SupportedPictureSizes.ToList();
            Holder.SetType(SurfaceType.PushBuffers);
        }
Exemplo n.º 4
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            _camera = Camera.Open(FindBackFacingCamera());

            //_textureView.LayoutParameters = new FrameLayout.LayoutParams(width, WallpaperDesiredMinimumHeight);
            var parameters = _camera.GetParameters();

            try
            {
                var aspect = ((decimal)height) / ((decimal)width);

                var previewSize = parameters.SupportedPreviewSizes
                                  .OrderBy(s => Math.Abs(s.Width / (decimal)s.Height - aspect))
                                  .First();

                parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
                _camera.SetParameters(parameters);

                _camera.SetPreviewTexture(surface);
                StartCamera();
            }
            catch (Java.IO.IOException ex)
            {
                // todo handle error here
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
Exemplo n.º 5
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            Logger.LogInfo(nameof(SurfaceHolderCallback), nameof(SurfaceCreated), "called.");

            try
            {
                if (_Camera == null)
                {
                    _Camera = Open();

                    _Parameters = _Camera.GetParameters();

                    if (SupportsFlash())
                    {
                        Logger.LogInfo(nameof(SurfaceHolderCallback), nameof(SurfaceCreated), "flash is supported. Enabling flash.");

                        _Parameters.FlashMode = Parameters.FlashModeTorch;
                    }

                    if (SupportsZoom())
                    {
                        Logger.LogInfo(nameof(SurfaceHolderCallback), nameof(SurfaceCreated), "zoom is supported. Enabling zoom.");

                        _Parameters.Zoom = _Parameters.MaxZoom / 2;
                    }

                    _Camera.SetParameters(_Parameters);
                    _Camera.SetPreviewDisplay(holder);
                }
            }
            catch (Java.Lang.Exception ex)
            {
                Logger.LogError(ex);
            }
        }
 public async void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
 {
     if (ContextCompat.CheckSelfPermission(Activity, Manifest.Permission.Camera) != Permission.Granted)
     {
         ActivityCompat.RequestPermissions(Activity, new string[] { Manifest.Permission.Camera }, 50);
         await(Element as CameraPage).Navigation.PopAsync();
         //(Element as CameraPage).Cancel();
     }
     else
     {
         decimal aspect = 0;
         camera = Android.Hardware.Camera.Open();
         var parameters = camera.GetParameters();
         if (GetOrientation())
         {
             aspect = ((decimal)height) / ((decimal)width);
         }
         else
         {
             aspect = ((decimal)width) / ((decimal)height);
         }
         var previewSize = parameters.SupportedPreviewSizes
                           .OrderBy(s => System.Math.Abs(s.Width / (decimal)s.Height - aspect))
                           .First();
         parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
         camera.SetParameters(parameters);
         camera.SetPreviewTexture(surface);
         StartCamera();
     }
 }
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            //If authorisation not granted for camera
            if (ContextCompat.CheckSelfPermission(CurrentContext, Manifest.Permission.Camera) != Permission.Granted)
            {
                //ask for authorisation
                ActivityCompat.RequestPermissions(CurrentContext, new String[] { Manifest.Permission.Camera }, 50);
            }
            else
            {
                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();
            }
        }
Exemplo n.º 8
0
        public void SurfaceCreated(ISurfaceHolder holder)
        {
            //If authorisation not granted for camera
            if (ContextCompat.CheckSelfPermission(CurrentContext, Manifest.Permission.Camera) != Permission.Granted)
            {
                //ask for authorisation
                ActivityCompat.RequestPermissions(CurrentContext, new System.String[] { Manifest.Permission.Camera }, 50);
            }
            else
            {
                if (camera != null)
                {
                    camera.Release();
                    camera = null;
                }
                camera = Android.Hardware.Camera.Open();
                camera.SetDisplayOrientation(90);


                Parameters parameters = camera.GetParameters();
                parameters.FocusMode = Parameters.FocusModeContinuousVideo;
                camera.SetParameters(parameters);

                camera.SetPreviewDisplay(holder);
                camera.StartPreview();
                initRecorder();
                camera.Unlock();
            }

            prepareRecorder();
        }
    public void OnAutoFocus(bool success, Android.Hardware.Camera camera)
    {
        var parameters          = camera.GetParameters();
        var supportedFocusModes = parameters.SupportedFocusModes;

        var supportedFocusMode = cameraPage.GetSupportedFocusMode();

        parameters.FocusMode = supportedFocusMode;

        if (supportedFocusModes != null && supportedFocusModes.Any())
        {
            if (parameters.MaxNumFocusAreas > 0)
            {
                parameters.FocusAreas = null;
            }
            if (success)
            {
                TextView focusIndicatorTV = this.cameraPage.focusIndicator;
                focusIndicatorTV.SetX(tapX);
                focusIndicatorTV.SetY(tapY);
                focusIndicatorTV.Visibility = ViewStates.Visible;
            }
            else
            {
                TextView focusIndicatorTV = this.cameraPage.focusIndicator;
                focusIndicatorTV.Visibility = ViewStates.Gone;
            }
            camera.SetParameters(parameters);
            camera.StartPreview();
        }
    }
Exemplo n.º 10
0
        public async Task GetPhoto()
        {
            _camera = Camera.Open();
            var parameters = _camera.GetParameters();

            var sizes = parameters.SupportedPictureSizes;

            int index = 0;

            for (int i = 0; i < sizes.Count; i++)
            {
                if (sizes[i].Width > 1200 && sizes[i].Width < 1300)
                {
                    index = i;
                }
            }

            parameters.SetPictureSize(sizes[index].Width, sizes[index].Height);
            parameters.SetRotation(90);
            parameters.SceneMode     = Camera.Parameters.SceneModeAuto;
            parameters.WhiteBalance  = Camera.Parameters.WhiteBalanceAuto;
            parameters.FocusMode     = Camera.Parameters.FocusModeContinuousPicture;
            parameters.PictureFormat = ImageFormatType.Jpeg;
            parameters.JpegQuality   = 100;
            _camera.SetParameters(parameters);
            _camera.SetPreviewCallback(this);
            _camera.Lock();
            SurfaceTexture st = new SurfaceTexture(100);

            _camera.SetPreviewTexture(st);
            _camera.StartPreview();

            await TakePicture();
        }
Exemplo n.º 11
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (surfaceHolder.Surface == null)
            {
                return;
            }
            try
            {
                cameraInstance.StopPreview();
                cameraInstance.SetPreviewDisplay(surfaceHolder);

                Android.Hardware.Camera.Parameters parameters  = cameraInstance.GetParameters();
                Android.Hardware.Camera.Size       optimalSize = CameraHelpers.GetOptimalPreviewSize(context, cameraInstance, width, height);
                parameters.SetPreviewSize(optimalSize.Width, optimalSize.Height);
                parameters.SetPictureSize(optimalSize.Width, optimalSize.Height);
                parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousPicture;
                cameraInstance.SetParameters(parameters);
                cameraInstance.SetDisplayOrientation(CameraHelpers.GetCameraOrientation(context));
                cameraInstance.StartPreview();
            }
            catch (Exception e)
            {
                Log.Debug("Camera activity", "Error starting camera preview: " + e.Message);
            }
        }
Exemplo n.º 12
0
        static Task ToggleTorchAsync(bool switchOn)
        {
            return(Task.Run(() =>
            {
                lock (locker)
                {
                    if (Platform.HasApiLevel(BuildVersionCodes.M) && !AlwaysUseCameraApi)
                    {
                        var cameraManager = Platform.CameraManager;
                        foreach (var id in cameraManager.GetCameraIdList())
                        {
                            var hasFlash = cameraManager.GetCameraCharacteristics(id).Get(CameraCharacteristics.FlashInfoAvailable);
                            if (Java.Lang.Boolean.True.Equals(hasFlash))
                            {
                                cameraManager.SetTorchMode(id, switchOn);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (camera == null)
                        {
                            if (surface == null)
                            {
                                surface = new SurfaceTexture(0);
                            }

#pragma warning disable CS0618 // Camera types are deprecated in Android 10+
                            camera = Camera.Open();

                            // Nexus 5 and some devices require a preview texture
                            camera.SetPreviewTexture(surface);
                        }

                        var param = camera.GetParameters();

                        // Deprecated in an earlier android version
                        param.FlashMode = switchOn ? Camera.Parameters.FlashModeTorch : Camera.Parameters.FlashModeOff;

                        camera.SetParameters(param);

                        if (switchOn)
                        {
                            camera.StartPreview();
                        }
                        else
                        {
                            camera.StopPreview();
                            camera.Release();
                            camera.Dispose();
#pragma warning restore CS0618 // Type or member is obsolete
                            camera = null;
                            surface.Dispose();
                            surface = null;
                        }
                    }
                }
            }));
        }
Exemplo n.º 13
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {
            if (holder.Surface == null)
            {
                return;
            }

            try
            {
                _mCamera.StopPreview();
            }
            catch (Exception e)
            {
                //TODO:KOA: remove Console!
                Console.WriteLine(Localization.Errors.ErrorCameraPreview + e.Message);
            }

            try
            {
                var p = _mCamera.GetParameters();
                p.SetPreviewSize(_mPreviewSize.Width, _mPreviewSize.Height);
                if (p.SupportedFocusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeContinuousVideo))
                {
                    p.FocusMode = Android.Hardware.Camera.Parameters.FocusModeContinuousVideo;
                    _mCamera.SetParameters(p);
                }
                switch (Display.Rotation)
                {
                case SurfaceOrientation.Rotation0:
                    _mCamera.SetDisplayOrientation(90);
                    break;

                case SurfaceOrientation.Rotation90:
                    break;

                case SurfaceOrientation.Rotation180:
                    break;

                case SurfaceOrientation.Rotation270:
                    _mCamera.SetDisplayOrientation(180);
                    break;
                }
                p.SetPreviewSize(_mPreviewSize.Width, _mPreviewSize.Height);

                if (_mPictureSize != null)
                {
                    p.SetPictureSize(_mPictureSize.Width, _mPictureSize.Height);
                }
                p.SetRotation(90);
                _mCamera.SetParameters(p);
                _mCamera.SetPreviewDisplay(holder);
                _mCamera.StartPreview();
            }
            catch (Exception e)
            {
                //TODO:KOA: remove Console!
                Console.WriteLine(Localization.Errors.ErrorCameraPreview + e.Message);
            }
        }
Exemplo n.º 14
0
 public void SetCamera(Camera camera)
 {
     mCamera = camera;
     if (mCamera != null)
     {
         mSupportedPreviewSizes = mCamera.GetParameters()
                                  .SupportedPreviewSizes;
         RequestLayout();
     }
 }
Exemplo n.º 15
0
        public void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
        {
            var paras       = camera.GetParameters();
            var imageformat = paras.PreviewFormat;

            if (imageformat == Android.Graphics.ImageFormatType.Nv21)
            {
                Android.Graphics.YuvImage img = new Android.Graphics.YuvImage(data,
                                                                              imageformat, paras.PreviewSize.Width, paras.PreviewSize.Height, null);
            }
        }
        private void StartCamera()
        {
            var properties = _camera.GetParameters();

            // Set the camera to autofocus and autoflash
            properties.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
            properties.FlashMode = Camera.Parameters.FlashModeAuto;
            _camera.SetParameters(properties);
            SetCameraDisplayOrientation();
            _camera.StartPreview();
        }
Exemplo n.º 17
0
        public void SurfaceChanged(ISurfaceHolder holder, Format format, int w, int h)
        {
            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            Camera.Parameters parameters = camera.GetParameters();

            IList <Camera.Size> sizes = parameters.SupportedPreviewSizes;

            Camera.Size optimalSize = GetOptimalPreviewSize(sizes, w, h);

            parameters.SetPreviewSize(optimalSize.Width, optimalSize.Height);

            camera.SetDisplayOrientation(90);
            camera.SetParameters(parameters);
            int dataBufferSize = (int)(optimalSize.Width * optimalSize.Height *
                                       (ImageFormat.GetBitsPerPixel(camera.GetParameters().PreviewFormat) / 8.0));

            _reader = new QRCodeReader();
            camera.StartPreview();
        }
Exemplo n.º 18
0
        public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h)
        {
            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            Camera.Parameters parameters = mCamera.GetParameters();
            parameters.SetPreviewSize(mPreviewSize.Width, mPreviewSize.Height);
            RequestLayout();

            mCamera.SetParameters(parameters);
            mCamera.StartPreview();
        }
Exemplo n.º 19
0
        private void OpenCamera()
        {
            if (CheckSelfPermission(Manifest.Permission.Camera) != Permission.Granted)
            {
                RequestCameraPermission();
                return;
            }

            camera = Open();
            Parameters parameters = camera.GetParameters();

            parameters.PictureFormat = ImageFormatType.Jpeg;
            parameters.PreviewFormat = ImageFormatType.Nv21;
            if (parameters.SupportedFocusModes.Contains(Parameters.FocusModeContinuousVideo))
            {
                parameters.FocusMode = Parameters.FocusModeContinuousVideo;
            }
            IList <Size> suportedPreviewSizes = parameters.SupportedPreviewSizes;
            int          i = 0;

            for (i = 0; i < suportedPreviewSizes.Count; i++)
            {
                if (suportedPreviewSizes[i].Width < 1300)
                {
                    break;
                }
            }
            parameters.SetPreviewSize(suportedPreviewSizes[i].Width, suportedPreviewSizes[i].Height);
            camera.SetParameters(parameters);
            camera.SetDisplayOrientation(90);
            camera.SetPreviewCallback(this);
            camera.SetPreviewDisplay(surface.Holder);
            camera.StartPreview();
            //Get camera width
            previewWidth = parameters.PreviewSize.Width;
            //Get camera height
            previewHeight = parameters.PreviewSize.Height;

            //Resize SurfaceView Size
            float scaledHeight = previewWidth * 1.0f * surface.Width / previewHeight;
            float prevHeight   = surface.Height;

            ViewGroup.LayoutParams lp = surface.LayoutParameters;
            lp.Width  = surface.Width;
            lp.Height = (int)scaledHeight;
            surface.LayoutParameters = lp;
            surface.Top = (int)((prevHeight - scaledHeight) / 2);
            surface.DrawingCacheEnabled = true;

            handlerThread = new HandlerThread("background");
            handlerThread.Start();
            //backgroundHandler = new MyHandler(handlerThread.Looper);
            backgroundHandler = new MyHandler(Looper.MainLooper);
        }
Exemplo n.º 20
0
        public CameraPreview(Context context, Android.Hardware.Camera camera) : base(context)
        {
            cameraInstance = camera;
            this.context   = context;
            surfaceHolder  = Holder;
            surfaceHolder.AddCallback(this);

            Android.Hardware.Camera.Parameters parameters = cameraInstance.GetParameters();
            parameters.FocusMode = Android.Hardware.Camera.Parameters.FocusModeAuto;
            cameraInstance.SetParameters(parameters);
        }
Exemplo n.º 21
0
        public void TurnOn()
        {
            if (camera == null)
            {
                camera = Camera.Open();
            }

            if (camera == null)
            {
                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();

            try
            {
                camera.SetPreviewTexture(new SurfaceTexture(0));
            }
            catch { }
        }
Exemplo n.º 22
0
        public void StartCamera(int camID, string flash, string resolution, string focuse)
        {
            StopCamera();
            try { mCamera = Android.Hardware.Camera.Open(camID); }
            catch (Exception)
            {
                try
                {
                    byte[] dataPacker = ((MainActivity)MainActivity.global_activity).MyDataPacker("CAMNOT", System.
                                                                                                  Text.Encoding.UTF8.GetBytes("vid"));
                    MainActivity.Soketimiz.BeginSend(dataPacker, 0, dataPacker.Length, SocketFlags.None, null, null);
                }
                catch (Exception) { }
                return;
            }

            Android.Hardware.Camera.Parameters params_ = mCamera.GetParameters();
            SetFlashModeOff(params_);
            if (flash == "1")
            {
                FlashParam(params_);
            }
            ///
            params_.SetPreviewSize(int.Parse(resolution.Split('x')[0]),
                                   int.Parse(resolution.Split('x')[1]));
            ///
            if (focuse == "1")
            {
                SetFocusModeOn(params_);
            }
            ///
            SetSceneModeAuto(params_);
            SetWhiteBalanceAuto(params_);
            mCamera.SetParameters(params_);
            try
            {
                mCamera.SetPreviewDisplay(hldr);
                mCamera.SetPreviewCallback(this);
                mCamera.StartPreview();
            }
            catch (Exception)
            {
                try
                {
                    byte[] senddata = ((MainActivity)MainActivity.global_activity).MyDataPacker("CAMNOT", Encoding.UTF8.GetBytes("Can't start camera"));
                    MainActivity.Soketimiz.BeginSend(senddata, 0, senddata.Length, SocketFlags.None, null, null);
                }
                catch (Exception) { }

                StopCamera();
                return;
            }
        }
        public void TurnOff()
        {
            if (camera == null)
            {
                camera = Camera.Open();
            }

            if (camera == null)
            {
                Console.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);
            }

            camera.StopPreview();

            //added on 1/3/2016 by aditmer to try to fix the ongoing issue on Android 6.x and the battery drain issue
            camera.Release();
            camera = null;
        }
Exemplo n.º 24
0
 public void SurfaceCreated(ISurfaceHolder holder)
 {
     // throw new NotImplementedException();
     // open camera's parameters
     camera = Android.Hardware.Camera.Open();
     camera.SetDisplayOrientation(90);
     Android.Hardware.Camera.Parameters p = camera.GetParameters();
     p.PictureFormat = ImageFormatType.Jpeg;
     camera.SetParameters(p);
     camera.SetPreviewCallback(this);
     camera.SetPreviewDisplay(holder);
     camera.StartPreview();
 }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        private byte[] ConvertYuvToJpeg(byte[] yuvData, Android.Hardware.Camera camera)
        {
            var cameraParameters = camera.GetParameters();
            var width            = cameraParameters.PreviewSize.Width;
            var height           = cameraParameters.PreviewSize.Height;
            var yuv     = new YuvImage(yuvData, cameraParameters.PreviewFormat, width, height, null);
            var ms      = new MemoryStream();
            var quality = 80;   // adjust this as needed

            yuv.CompressToJpeg(new Rect(0, 0, width, height), quality, ms);
            var jpegData = ms.ToArray();

            return(jpegData);
        }
Exemplo n.º 27
0
        public void ToggleFlashLight(Android.Hardware.Camera _myCamera)
        {
            var prams = _myCamera.GetParameters();

            if (prams.FlashMode == Android.Hardware.Camera.Parameters.FlashModeOn)
            {
                prams.FlashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
            }
            else
            {
                prams.FlashMode = Android.Hardware.Camera.Parameters.FlashModeOn;
            }
            _myCamera.SetParameters(prams);
        }
Exemplo n.º 28
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            try {
                _camera = Android.Hardware.Camera.Open(GetFrontCameraId());
                _camera.SetDisplayOrientation(90);

                var pictureSize = _camera.GetParameters().PictureSize;
                var previewSize = _camera.GetParameters().PreviewSize;

                // Need to flip around width and height because of the rotation
                textureView.LayoutParameters = new RelativeLayout.LayoutParams(pictureSize.Height, pictureSize.Width);
                var aspectRatio = ((double)pictureSize.Height) / ((double)pictureSize.Width);

                var lp = this.gameoverOverlayLayer.LayoutParameters;
                lp.Height = (int)(Resources.DisplayMetrics.HeightPixels * 0.6);
                lp.Width  = (int)(lp.Height * aspectRatio);
                this.gameoverOverlayLayer.LayoutParameters = lp;

                _camera.SetPreviewTexture(surface);
                _camera.StartPreview();
            }  catch (Java.IO.IOException ex) {
                System.Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 29
0
        public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
        {
            {
                {
                    int cameraCount = Android.Hardware.Camera.NumberOfCameras;
                    int cameraId    = 0;
                    Android.Hardware.Camera.CameraInfo cameraInfo = new Android.Hardware.Camera.CameraInfo();
                    for (int camIdx = 0; camIdx < cameraCount; camIdx++)
                    {
                        Android.Hardware.Camera.GetCameraInfo(camIdx, cameraInfo);
                        if (cameraInfo.Facing == Android.Hardware.CameraFacing.Front)
                        {
                            camera = Android.Hardware.Camera.Open(camIdx);

                            cameraId = camIdx;
                            break;
                        }
                    }

                    if (camera == null)
                    {
                        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();

                var previewSize = parameters.SupportedPreviewSizes[0];

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

                mainLayout.LayoutParameters.Height = previewSize.Height;
                mainLayout.LayoutParameters.Width  = previewSize.Width;

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

                camera.SetPreviewTexture(surface);
                StartCamera();
            }
        }
Exemplo n.º 30
0
        public List <CameraPixels> GetCameraResolution()
        {
            List <CameraPixels> camPixels = new List <CameraPixels>();

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                //Lolipop and above
                CameraManager          camMan  = (CameraManager)mactivity.GetSystemService(Context.CameraService);
                string[]               camId   = camMan.GetCameraIdList();
                CameraCharacteristics  camChar = camMan.GetCameraCharacteristics(camId[0]); //0 - mostly for back cam
                StreamConfigurationMap camMap  = (StreamConfigurationMap)camChar.Get(CameraCharacteristics.ScalerStreamConfigurationMap);
                Android.Util.Size[]    sizes   = camMap.GetOutputSizes((int)ImageFormatType.Jpeg);

                System.Diagnostics.Debug.WriteLine($"Camera sizes: {sizes.Length}");

                foreach (var size in sizes)
                {
                    //System.Diagnostics.Debug.WriteLine($"Sizes: {size.Width} x {size.Height} = {Convert.ToDouble(size.Width) * Convert.ToDouble(size.Height) / Convert.ToDouble(1024000)} megs");
                    camPixels.Add(new CameraPixels()
                    {
                        Height     = size.Height,
                        Width      = size.Width,
                        Megapixels = Math.Round(Convert.ToDecimal(size.Width) * Convert.ToDecimal(size.Height) / Convert.ToDecimal(1000000), 1)
                    });
                }
            }
            else
            {
                //pre-lolipop
                Android.Hardware.Camera              cam      = Android.Hardware.Camera.Open();
                Android.Hardware.Camera.Parameters   camParam = cam.GetParameters();
                IList <Android.Hardware.Camera.Size> plSizes  = camParam.SupportedPictureSizes;

                foreach (var size in plSizes)
                {
                    System.Diagnostics.Debug.WriteLine($"Sizes: {size.Width} x {size.Height} = {Convert.ToDouble(size.Width) * Convert.ToDouble(size.Height) / Convert.ToDouble(1024000)} megs");
                    camPixels.Add(new CameraPixels()
                    {
                        Height     = size.Height,
                        Width      = size.Width,
                        Megapixels = Math.Round(Convert.ToDecimal(size.Width) * Convert.ToDecimal(size.Height) / Convert.ToDecimal(1000000), 1)
                    });
                }
                cam.Release();
            }

            return(camPixels);
        }
Exemplo n.º 31
0
 private static void SetAutoFocus(Camera camera)
 {
     var parameters = camera.GetParameters();
     var focusModes = parameters.SupportedFocusModes;
     if (focusModes.Contains(Camera.Parameters.FocusModeAuto))
         parameters.FocusMode = Camera.Parameters.FocusModeAuto;
     camera.SetParameters(parameters);
 }
		public void SetCamera (Camera camera)
		{
			mCamera = camera;
			if (mCamera != null) {
				mSupportedPreviewSizes = mCamera.GetParameters ()
				.SupportedPreviewSizes;
				RequestLayout ();
			}
		}
		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);
		}
Exemplo n.º 34
0
 public void SurfaceCreated(ISurfaceHolder holder)
 {
     try
     {
         // if only front camera, get it
         camera = Camera.Open(0);
         Camera.Parameters p = camera.GetParameters();
         p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
         camera.EnableShutterSound(true);
         // fix camera rotation
         camera.SetDisplayOrientation(0);
         camera.SetParameters(p);
         camera.SetPreviewCallback(this);
         camera.Lock();
         camera.SetPreviewDisplay(holder);
         camera.StartPreview();
     }
     catch (Java.IO.IOException e)
     {
     }
 }