public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Android.Graphics.Format format, int width, int height)
        {
            if (Holder.Surface == null)
            {
                return;
            }

            try
            {
                Camera.Parameters parameters = mCamera.GetParameters();
                //parameters.FocusMode = Camera.Parameters.FocusModeInfinity;

                if (parameters.IsVideoStabilizationSupported)
                {
                    parameters.VideoStabilization = true;
                }

                if (mPreviewSize != null)
                {
                    Camera.Size previewSize = mPreviewSize;
                    parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
                }

                mCamera.SetParameters(parameters);
                mCamera.StartPreview();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #2
0
        public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h)
        {
            if (mCamera == null)
            {
                return;
            }

            // The surface has changed size. Update the camera preview size
            Camera.Parameters parameters = mCamera.GetParameters();
            Camera.Size       s          = GetBestSupportedSize(parameters.SupportedPreviewSizes, w, h);
            // Correcting aspect ratio error - gets rid of extraneous lines that jpeg fills in.
            s.Width = s.Height > s.Width ? s.Height * 3 / 4 : s.Height * 4 / 3;
            parameters.SetPreviewSize(s.Width, s.Height);
            s = GetBestSupportedSize(parameters.SupportedPictureSizes, w, h);
            parameters.SetPictureSize(s.Width, s.Height);
            mCamera.SetParameters(parameters);
            try {
                mCamera.StartPreview();
            }
            catch (Exception ex) {
                Debug.WriteLine(String.Format("Could not start preview: {0}", ex.Message), TAG);
                mCamera.Release();
                mCamera = null;
            }
        }
Beispiel #3
0
        public static Camera GetCameraInstance(int target = 1600 * 1200, bool video = false) //2mp
        {
            Camera c = null;

            try
            {
                c = Camera.Open();
                Camera.Parameters   camParams = c.GetParameters();
                IList <Camera.Size> sizes     = (video) ? camParams.SupportedVideoSizes :
                                                camParams.SupportedPictureSizes;

                Camera.Size size        = sizes[0];
                int         currentDiff = System.Math.Abs(size.Height * size.Width - target);

                foreach (Camera.Size thisSize in sizes)
                {
                    int thisDiff = System.Math.Abs(thisSize.Height * thisSize.Width - target);
                    if (thisDiff >= currentDiff)
                    {
                        continue;
                    }

                    size        = thisSize;
                    currentDiff = thisDiff;
                }
                camParams.SetPictureSize(size.Width, size.Height);
                c.SetParameters(camParams);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(c);
        }
Beispiel #4
0
        public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int w, int h)
        {
            if (_surfaceHolder != holder)
            {
                _surfaceHolder = holder;
                _surfaceHolder.AddCallback(this);
            }

            // Now that the size is known, set up the camera parameters and begin
            // the preview.
            Camera.Size optimalSize = SetCameraOptimalPreviewSize(_camera, w, h);

            //set for protrait mode
            //camera.SetDisplayOrientation(90);

            if (_cameraPreviewCallback != null)
            {
                if (_cameraPreviewCallbackWithBuffer)
                {
                    int bufferSize = optimalSize.Width * (optimalSize.Height >> 1) * 3;
                    _camera.SetPreviewCallbackWithBuffer(_cameraPreviewCallback);
                    for (int i = 0; i < 1; ++i)
                    {
                        _camera.AddCallbackBuffer(new byte[bufferSize]);
                    }
                }
                else
                {
                    _camera.SetPreviewCallback(_cameraPreviewCallback);
                }
            }
            _camera.StartPreview();

            Layout(0, 0, optimalSize.Width, optimalSize.Height);
        }
Beispiel #5
0
        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] global::Android.Graphics.Format format, int width, int height)
        {
            if (Holder.Surface == null)
            {
                return;
            }

            try
            {
                Camera.Parameters parameters = Camera.GetParameters();
                parameters.FocusMode        = Camera.Parameters.FocusModeContinuousPicture;
                parameters.PreviewFrameRate = 30;

                if (previewSize != null)
                {
                    Camera.Size tempPreviewSize = previewSize;
                    parameters.SetPreviewSize(tempPreviewSize.Width, tempPreviewSize.Height);
                }

                Camera.SetParameters(parameters);
                Camera.StartPreview();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #6
0
        public void OnPreviewFrame(byte[] data, Camera camera)
        {
            Log.Info(TAG, "OnPreviewFrame: ricevuto frame dalla camera.");

            try {
                if (!DontTakeFrameCameraPreview)
                {
                    DontTakeFrameCameraPreview = true;
                    Camera.Parameters         parameters = camera.GetParameters();
                    Camera.Size               size       = parameters.PreviewSize;
                    Android.Graphics.YuvImage image      =
                        new Android.Graphics.YuvImage(data, parameters.PreviewFormat,
                                                      size.Width, size.Height, null);
                    MemoryStream imageStreamToSave = new MemoryStream();
                    image.CompressToJpeg(
                        new Android.Graphics.Rect(0, 0, image.Width, image.Height), 90,
                        imageStreamToSave);
                    imageStreamToSave.Flush();

                    InvokeGotchAFrameCallback(imageStreamToSave);//Invoke se la callback non e' null
                }
            }
            catch (Exception e) {
                Log.Error("TakePictureCommand",
                          string.Format("An error occure while writing on file.\nException:{0}", e.StackTrace));
            }
            finally {
            }
        }
        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);
            }
        }
Beispiel #8
0
        public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
        {
            var parameters = Preview.GetParameters();

            //プレビューサイズ設定
            if (supportedPreviewSizes != null)
            {
                previewSize = GetOptimalPreviewSize(supportedPreviewSizes, surfaceView.Width, surfaceView.Height);
            }
            parameters.SetPreviewSize(previewSize.Width, previewSize.Height);

            //フレームレート設定
            //parameters.SetPreviewFpsRange(10000, 24000);

            RequestLayout();

            switch (windowManager.DefaultDisplay.Rotation)
            {
            case SurfaceOrientation.Rotation0:
                camera.SetDisplayOrientation(90);
                break;

            case SurfaceOrientation.Rotation90:
                camera.SetDisplayOrientation(0);
                break;

            case SurfaceOrientation.Rotation270:
                camera.SetDisplayOrientation(180);
                break;
            }

            Preview.SetParameters(parameters);
            Preview.StartPreview();
            IsPreviewing = true;
        }
        /**
         * Iterate over supported camera video sizes to see which one best fits the
         * dimensions of the given view while maintaining the aspect ratio. If none can,
         * be lenient with the aspect ratio.
         *
         * @param supportedVideoSizes Supported camera video sizes.
         * @param previewSizes Supported camera preview sizes.
         * @param w     The width of the view.
         * @param h     The height of the view.
         * @return Best match camera video size to fit in the view.
         */
        public static Camera.Size getOptimalVideoSize(IList <Camera.Size> supportedVideoSizes,
                                                      IList <Camera.Size> previewSizes, int w, int h)
        {
            // Use a very small tolerance because we want an exact match.
            const double ASPECT_TOLERANCE = 0.1;
            double       targetRatio      = (double)w / h;

            // Supported video sizes list might be null, it means that we are allowed to use the preview
            // sizes
            IList <Camera.Size> videoSizes;

            if (supportedVideoSizes != null)
            {
                videoSizes = supportedVideoSizes;
            }
            else
            {
                videoSizes = previewSizes;
            }
            Camera.Size optimalSize = null;

            // Start with max value and refine as we iterate over available video sizes. This is the
            // minimum difference between view and camera height.
            double minDiff = Double.MaxValue;

            // Target view height
            int targetHeight = h;

            // Try to find a video size that matches aspect ratio and the target view size.
            // Iterate over all available sizes and pick the largest size that can fit in the view and
            // still maintain the aspect ratio.
            foreach (Camera.Size size in videoSizes)
            {
                double ratio = (double)size.Width / size.Height;
                if (Math.Abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                {
                    continue;
                }
                if (Math.Abs(size.Height - targetHeight) < minDiff && previewSizes.Contains(size))
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Height - targetHeight);
                }
            }

            // Cannot find video size that matches the aspect ratio, ignore the requirement
            if (optimalSize == null)
            {
                minDiff = Double.MaxValue;
                foreach (Camera.Size size in videoSizes)
                {
                    if (Math.Abs(size.Height - targetHeight) < minDiff && previewSizes.Contains(size))
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Height - targetHeight);
                    }
                }
            }
            return(optimalSize);
        }
        /// <summary>
        /// Starts preview.
        /// </summary>
        internal void StartPreview()
        {
            // if camera uses preview buffer
            if (USE_PREVIEW_BUFFER)
            {
                // get camera parameters
                Camera.Parameters previewParameters = Camera.GetParameters();
                // get camera preview size
                Camera.Size previewSize = previewParameters.PreviewSize;
                // get bits per pixel for camera preview format
                int bitsPerPixel = Android.Graphics.ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat);
                // get buffer size
                int bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8;
                // add camera buffer
                _camera.AddCallbackBuffer(new byte[bufferSize]);
                _camera.SetPreviewCallbackWithBuffer(_previewCallbackDelegate);
            }
            else
            {
                _camera.SetPreviewCallback(_previewCallbackDelegate);
            }

            // start camera preview
            _camera.StartPreview();

            // if autofocus is enabled
            if (Autofocus)
            {
                // request autofocus
                RequestAutoFocus();
            }
        }
 /// <summary>
 /// Sets the camera preview size.
 /// </summary>
 /// <param name="previewSizeIndex">Index of preview size.</param>
 internal void SetCameraPreviewSizeSettings(int previewSizeIndex)
 {
     // if index is -1
     if (previewSizeIndex == -1)
     {
         // set camera preview size null
         _cameraPreviewSize = null;
         return;
     }
     try
     {
         // if camera is not empty
         // and camera preview size list is not empty
         // and index is correct
         if (Camera != null && CameraPreviewSizes != null && CameraPreviewSizes.Count > previewSizeIndex)
         {
             // if new camera preview size is not equal to previous one
             if (_cameraPreviewSize != CameraPreviewSizes[previewSizeIndex])
             {
                 // set new camera preview size
                 _cameraPreviewSize = CameraPreviewSizes[previewSizeIndex];
                 // stop camera preview
                 Camera.StopPreview();
                 // apply settings
                 ApplyCameraSettings();
                 // start camera preview
                 Camera.StartPreview();
             }
         }
     }
     catch
     {
     }
 }
Beispiel #12
0
        public static Camera.Size GetOptimalPreviewSize(Context context, Camera camera, int w, int h)
        {
            if (camera == null)
            {
                return(null);
            }

            List <Camera.Size> sizes = camera.GetParameters().SupportedPreviewSizes.ToList();

            if (DisplayHelpers.GetScreenOrientation(context) == Android.Content.Res.Orientation.Portrait)
            {
                int portraitWidth = h;
                h = w;
                w = portraitWidth;
            }

            double ASPECT_TOLERANCE = 0.1;
            double targetRatio      = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = double.MaxValue;

            int targetHeight = h;

            foreach (Camera.Size size in sizes)
            {
                double ratio = (double)size.Width / size.Height;
                if (System.Math.Abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                {
                    continue;
                }
                if (System.Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = System.Math.Abs(size.Height - targetHeight);
                }
            }

            if (optimalSize == null)
            {
                minDiff = double.MaxValue;
                foreach (Camera.Size size in sizes)
                {
                    if (System.Math.Abs(size.Height - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = System.Math.Abs(size.Height - targetHeight);
                    }
                }
            }
            return(optimalSize);
        }
Beispiel #13
0
        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            int width  = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec);
            int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec);

            SetMeasuredDimension(width, height);
            if (supportedPreviewSizes != null)
            {
                previewSize = GetOptimalPreviewSize(supportedPreviewSizes, width, height);
            }
        }
Beispiel #14
0
        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);
        }
Beispiel #15
0
        public void Initialize()
        {
            Preview = Camera.Open((int)FormsCameraPreview.Camera);

            //Portrait固定
            Preview.SetDisplayOrientation(90);

            //var parameters = Preview.GetParameters();


            //プレビューサイズ設定
            if (supportedPreviewSizes != null)
            {
                previewSize = GetOptimalPreviewSize(supportedPreviewSizes, surfaceView.Width, surfaceView.Height);
            }
            //parameters.SetPreviewSize(previewSize.Width, previewSize.Height);

            ////フレームレート設定
            //parameters.SetPreviewFpsRange(10000, 24000);

            var parameters = Preview.GetParameters();

            parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
            RequestLayout();

            Preview.SetParameters(parameters);
            RequestLayout();

            //フレーム処理用バッファの作成
            int size = previewSize.Width * previewSize.Height * Android.Graphics.ImageFormat.GetBitsPerPixel(Android.Graphics.ImageFormatType.Nv21) / 8;

            Buff = new byte[size];
            //フレーム処理用のコールバック生成
            PreviewCallback = new CameraPreviewCallback {
                CameraPreview = FormsCameraPreview, Buff = Buff
            };

            Preview.SetPreviewCallbackWithBuffer(PreviewCallback);
            Preview.AddCallbackBuffer(Buff);

            //ピンチジェスチャー登録処理
            pinchlistener = new PinchListener {
                camera = Preview, PreviewCallback = PreviewCallback, buff = Buff
            };
            scaleGestureDetector = new ScaleGestureDetector(context, pinchlistener);

            Preview.SetPreviewDisplay(holder);

            if (IsPreviewing)
            {
                StartPreview();
            }
        }
 public void RefreshPreviewSize()
 {
     if (mSupportedPreviewSizes != null)
     {
         // Switched because we want portrait not landscape
         mPreviewSize = GetOptimalPreviewSize(mSupportedPreviewSizes, MeasuredHeight, MeasuredWidth);
     }
     if (mSupportedPreviewSizes != null)
     {
         // Switched because we want portrait not landscape
         mSize = GetOptimalPreviewSize(mSupportedSizes, MeasuredHeight, MeasuredWidth);
     }
 }
        private Camera.Size GetOptimalPreviewSize(IList <Camera.Size> sizes, int w, int h)
        {
            const double ASPECT_TOLERANCE = 0.05;
            double       targetRatio      = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = Double.MaxValue;

            int targetHeight = h;

            // Try to find an size match aspect ratio and size
            for (int i = 0; i < sizes.Count; i++)
            {
                Camera.Size size  = sizes [i];
                double      ratio = (double)size.Width / size.Height;

                if (Math.Abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                {
                    continue;
                }

                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Height - targetHeight);
                }
            }

            // Cannot find the one match the aspect ratio, ignore the requirement
            if (optimalSize == null)
            {
                minDiff = Double.MaxValue;
                for (int i = 0; i < sizes.Count; i++)
                {
                    Camera.Size size = sizes [i];

                    if (Math.Abs(size.Height - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Height - targetHeight);
                    }
                }
            }

            return(optimalSize);
        }
        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            // We purposely disregard child measurements because act as a
            // wrapper to a SurfaceView that centers the camera preview instead
            // of stretching it.
            int width  = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec);
            int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec);

            SetMeasuredDimension(width, height);

            if (mSupportedPreviewSizes != null)
            {
                mPreviewSize = GetOptimalPreviewSize(mSupportedPreviewSizes, width, height);
            }
        }
        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 = camera.GetParameters();

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

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

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

            camera.SetParameters(parameters);
            camera.StartPreview();
        }
        /// <summary>
        /// Gets the size of the optimal preview.
        /// </summary>
        /// <param name="sizes">The sizes.</param>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <returns>Camera.Size.</returns>
        private Camera.Size GetOptimalPreviewSize(IList <Camera.Size> sizes, int w, int h)
        {
            const double AspectTolerance = 0.1;
            double       targetRatio     = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = Double.MaxValue;

            int targetHeight = h;

            // Try to find an size match aspect ratio and size
            foreach (Camera.Size size in sizes)
            {
                double ratio = (double)size.Width / size.Height;

                if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                {
                    continue;
                }

                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Height - targetHeight);
                }
            }

            // Cannot find the one match the aspect ratio, ignore the requirement
            if (optimalSize == null)
            {
                minDiff = Double.MaxValue;
                foreach (Camera.Size size in sizes)
                {
                    if (Math.Abs(size.Height - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Height - targetHeight);
                    }
                }
            }

            return(optimalSize);
        }
Beispiel #21
0
        // A simple algorithm to get the largest size available. For a more
        // robust version, see CameraPreview.java in the API demos
        // sample app from Android

        private Camera.Size GetBestSupportedSize(IList <Camera.Size> sizes, int width, int height)
        {
            Camera.Size bestSize    = sizes[0];
            int         largestArea = bestSize.Width * bestSize.Height;

            foreach (Camera.Size s in sizes)
            {
                int area = s.Width * s.Height;
                if (area > largestArea)
                {
                    bestSize    = s;
                    largestArea = area;
                }
            }
            return(bestSize);
        }
        private void configureCaptureSize(int preferredWidth, int preferredHeight)
        {
            Camera.Parameters parameters = mCamera.Parameters;

            IList <Camera.Size> sizes = parameters.SupportedPreviewSizes;
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("deprecation") java.util.List<Integer> frameRates = parameters.getSupportedPreviewFrameRates();
            IList <int?> frameRates = parameters.SupportedPreviewFrameRates;
            int          maxFPS     = 0;

            if (frameRates != null)
            {
                foreach (int?frameRate in frameRates)
                {
                    if (frameRate > maxFPS)
                    {
                        maxFPS = frameRate.Value;
                    }
                }
            }
            mCaptureFPS = maxFPS;

            int maxw = 0;
            int maxh = 0;

            for (int i = 0; i < sizes.Count; ++i)
            {
                Camera.Size s = sizes[i];
                if (s.width >= maxw && s.height >= maxh)
                {
                    if (s.width <= preferredWidth && s.height <= preferredHeight)
                    {
                        maxw = s.width;
                        maxh = s.height;
                    }
                }
            }
            if (maxw == 0 || maxh == 0)
            {
                Camera.Size s = sizes[0];
                maxw = s.width;
                maxh = s.height;
            }

            mCaptureWidth  = maxw;
            mCaptureHeight = maxh;
        }
        private Camera.Size GetOptimalPreviewSize(IList <Camera.Size> sizes, int w, int h)
        {
            const double AspectTolerance = 0.1;
            double       targetRatio     = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = double.MaxValue;

            int targetHeight = 720;

            foreach (Camera.Size size in sizes)
            {
                double ratio = (double)size.Width / size.Height;

                if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                {
                    continue;
                }
                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Height - targetHeight);
                }
            }

            if (optimalSize == null)
            {
                minDiff = double.MaxValue;
                foreach (Camera.Size size in sizes)
                {
                    if (Math.Abs(size.Height - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Height - targetHeight);
                    }
                }
            }

            Console.WriteLine($"Camera Optimizal Size: {optimalSize?.Height??0} {optimalSize?.Width??0}");
            return(optimalSize);
        }
Beispiel #24
0
        Camera.Size GetOptimalPreviewSize(IList <Camera.Size> sizes, int w, int h)
        {
            const double AspectTolerance = 0.1;
            double       targetRatio     = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = double.MaxValue;

            int targetHeight = h;

            foreach (Camera.Size size in sizes)
            {
                double ratio = (double)size.Width / size.Height;

                if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                {
                    continue;
                }
                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Height - targetHeight);
                }
            }

            if (optimalSize == null)
            {
                minDiff = double.MaxValue;
                foreach (Camera.Size size in sizes)
                {
                    if (Math.Abs(size.Height - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Height - targetHeight);
                    }
                }
            }

            System.Diagnostics.Debug.WriteLine("GetOptimalPreviewSize: W{0}/H{0}", optimalSize.Height, optimalSize.Width);
            return(optimalSize);
        }
Beispiel #25
0
        private Camera.Size GetOptimalPreviewSize(IList <Camera.Size> sizes, int w, int h)
        {
            double AspectTolerance = 0.1;
            double targetRatio     = (double)w / h;

            if (sizes == null)
            {
                return(null);
            }

            Camera.Size optimalSize = null;
            double      minDiff     = double.MaxValue;

            int targetHeight = h;

            foreach (Camera.Size size in sizes)
            {
                double ratio = (double)size.Height / size.Width;    //Portraitは縦横逆


                if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                {
                    continue;
                }
                if (Math.Abs(size.Width - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff     = Math.Abs(size.Width - targetHeight);
                }
            }

            if (optimalSize == null)
            {
                minDiff = double.MaxValue;
                foreach (Camera.Size size in sizes)
                {
                    if (Math.Abs(size.Width - targetHeight) < minDiff)
                    {
                        optimalSize = size;
                        minDiff     = Math.Abs(size.Width - targetHeight);
                    }
                }
            }

            return(optimalSize);
        }
        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            int width  = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec);
            int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec);

            SetMeasuredDimension(width, height);

            //Console.WriteLine(width);

            //force to widescreen aspect:

            height = (int)(width * (1080f / 1920));

            if (mSupportedPreviewSizes != null)
            {
                mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
            }
        }
        private Camera.Parameters GetModifiedParameters(Camera.Parameters oldParameters)
        {
            Camera.Parameters newParameters = oldParameters;
            Camera.Size       size          = FindMaxSize(newParameters.SupportedPictureSizes);

            newParameters.SetPreviewSize(640, 480);
            newParameters.SetPictureSize(size.Width, size.Height);
            newParameters.Set("contrast", "0");
            newParameters.FlashMode = Camera.Parameters.FlashModeOff;
            newParameters.FocusMode = Camera.Parameters.FocusModeAuto;
            newParameters.SceneMode = Camera.Parameters.SceneModeAuto;
            //newParameters.AutoExposureLock = false;
            newParameters.WhiteBalance = Camera.Parameters.WhiteBalanceAuto;
            //newParameters.ExposureCompensation = -12;
            newParameters.PictureFormat = Android.Graphics.ImageFormat.Jpeg;
            newParameters.JpegQuality   = 100;
            int angle = _cameraInfo.CalculateRotationAngle(CAMERA_ID);

            newParameters.SetRotation(angle);

            return(newParameters);
        }
        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;
        }
        private Camera.Size getOptimalPreviewSize(IEnumerable <Camera.Size> sizes, int width, int height)
        {
            Camera.Size optimalSize      = null;
            double      ASPECT_TOLERANCE = 0.1;
            double      targetRatio      = (double)width / height;

            // Try to find a size match which suits the whole screen minus the menu on the left.
            foreach (Camera.Size size in sizes.OrderBy(o => o.Width))
            {
                double ratio = (double)size.Width / size.Height;

                if (ratio <= targetRatio + ASPECT_TOLERANCE && ratio >= targetRatio - ASPECT_TOLERANCE)
                {
                    optimalSize = size;
                }
            }

            // If we cannot find the one that matches the aspect ratio, ignore the requirement.
            if (optimalSize == null)
            {
                // TODO : Backup in case we don't get a size.
            }
            return(optimalSize);
        }
Beispiel #30
0
        private bool prepareVideoRecorder()
        {
            // BEGIN_INCLUDE (configure_preview)
            mCamera = CameraHelper.getDefaultCameraInstance();

            // We need to make sure that our preview and recording video size are supported by the
            // camera. Query camera to find all the sizes and choose the optimal size given the
            // dimensions of our preview surface.
            Camera.Parameters   parameters             = mCamera.GetParameters();
            IList <Camera.Size> mSupportedPreviewSizes = parameters.SupportedPreviewSizes;
            IList <Camera.Size> mSupportedVideoSizes   = parameters.SupportedVideoSizes;

            Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes,
                                                                       mSupportedPreviewSizes, mPreview.Width, mPreview.Height);

            // Use the same size for recording profile.
            CamcorderProfile profile = CamcorderProfile.Get(CamcorderQuality.High);

            profile.VideoFrameWidth  = optimalSize.Width;
            profile.VideoFrameHeight = optimalSize.Height;

            // likewise for the camera object itself.
            parameters.SetPreviewSize(profile.VideoFrameWidth, profile.VideoFrameHeight);
            mCamera.SetParameters(parameters);
            try
            {
                // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay}
                // with {@link SurfaceView}
                mCamera.SetPreviewTexture(mPreview.SurfaceTexture);
            }
            catch (IOException e)
            {
                Log.Error(TAG, "Surface texture is unavailable or unsuitable" + e.Message);
                return(false);
            }
            // END_INCLUDE (configure_preview)


            // BEGIN_INCLUDE (configure_media_recorder)
            mMediaRecorder = new Android.Media.MediaRecorder();

            // Step 1: Unlock and set camera to MediaRecorder
            mCamera.Unlock();
            mMediaRecorder.SetCamera(mCamera);

            // Step 2: Set sources
            mMediaRecorder.SetAudioSource(AudioSource.Default);
            mMediaRecorder.SetVideoSource(VideoSource.Camera);

            // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
            mMediaRecorder.SetProfile(profile);

            // Step 4: Set output file
            mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO);
            if (mOutputFile == null)
            {
                return(false);
            }
            mMediaRecorder.SetOutputFile(mOutputFile.Path);
            // END_INCLUDE (configure_media_recorder)

            // Step 5: Prepare configured MediaRecorder
            try
            {
                mMediaRecorder.Prepare();
            }
            catch (IllegalStateException e)
            {
                Log.Debug(TAG, "IllegalStateException preparing MediaRecorder: " + e.Message);
                releaseMediaRecorder();
                return(false);
            }
            catch (IOException e)
            {
                Log.Debug(TAG, "IOException preparing MediaRecorder: " + e.Message);
                releaseMediaRecorder();
                return(false);
            }
            return(true);
        }