예제 #1
0
        async void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            Size   targetMediaElementSize = new Size(640, 480);
            double aspectRatio            = 4.0 / 3.0;

            // 1. Open camera
            if (m_camera == null)
            {
                var  captureRes         = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                Size selectedCaptureRes = captureRes.Where(res => Math.Abs(aspectRatio - res.Width / res.Height) <= 0.1)
                                          .OrderBy(res => res.Width)
                                          .Last();
                m_camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, selectedCaptureRes);

                m_camera.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, m_camera.SensorLocation == CameraSensorLocation.Back ? m_camera.SensorRotationInDegrees : -m_camera.SensorRotationInDegrees);

                var  previewRes         = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back);
                Size selectedPreviewRes = previewRes.Where(res => Math.Abs(aspectRatio - res.Width / res.Height) <= 0.1)
                                          .Where(res => (res.Height >= targetMediaElementSize.Height) && (res.Width >= targetMediaElementSize.Width))
                                          .OrderBy(res => res.Width)
                                          .First();
                await m_camera.SetPreviewResolutionAsync(selectedPreviewRes);

                cameraEffect.CaptureDevice = m_camera;
            }

            // Always create a new source, otherwise the MediaElement will not start.
            source = new CameraStreamSource(cameraEffect, targetMediaElementSize);
            MyCameraMediaElement.SetSource(source);

            m_timer          = new DispatcherTimer();
            m_timer.Interval = new TimeSpan(0, 0, 0, 1, 0); // Tick every 1s.
            m_timer.Tick    += m_timer_Tick;
            m_timer.Start();
        }
예제 #2
0
        private async Task <Result> DetectBarcodeAsync()
        {
            var width  = (int)PreviewResolution.Width;
            var height = (int)PreviewResolution.Height;

            var             rotation        = PhotoCaptureDevice.SensorRotationInDegrees;
            LuminanceSource luminanceSource = null;

            PhotoCaptureDevice.GetPreviewBufferY(_previewBuffer);

            luminanceSource = new RGBLuminanceSource(_previewBuffer, width, height, RGBLuminanceSource.BitmapFormat.Gray8);
            var result = _barcodeReader.Decode(luminanceSource);

            if (result == null)
            {
                // ok, one try with rotation by 90 degrees
                if ((Orientation & PageOrientation.Portrait) == PageOrientation.Portrait)
                {
                    // if we are in potrait orientation it's better to rotate clockwise
                    // to get it in the right direction
                    luminanceSource = new RGBLuminanceSource(RotateClockwise(_previewBuffer, width, height), height, width, RGBLuminanceSource.BitmapFormat.Gray8);
                }
                else
                {
                    // in landscape we try counter clockwise until we know it better
                    luminanceSource = luminanceSource.rotateCounterClockwise();
                }
                result = _barcodeReader.Decode(luminanceSource);
            }
            return(result);
        }
예제 #3
0
        protected override void PopulateOptions()
        {
            var auto = new ArrayParameterOption <uint?>(null, "Auto");

            Options.Add(auto);

            CameraCapturePropertyRange times = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation,
                                                                                            KnownCameraPhotoProperties
                                                                                            .ExposureTime);
            var currentValue = (uint?)Device.GetProperty(ParameterId);

            uint[] standardValues = { 2000, 1000, 500, 250, 125, 60, 30, 15, 8, 4, 2, 1 };
            var    min            = (uint)times.Min;
            var    max            = (uint)times.Max;

            foreach (uint timeValue in standardValues)
            {
                uint microSeconds = 1000000 / timeValue;

                if (microSeconds >= min && microSeconds <= max)
                {
                    string name   = string.Format("1 / {0} s", timeValue);
                    var    option = new ArrayParameterOption <uint?>(microSeconds, name);
                    Options.Add(option);

                    if (currentValue == microSeconds)
                    {
                        SelectedOption = option;
                    }
                }
            }
        }
예제 #4
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            //Check available back cam & front cam
            if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back) || PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
            {
                if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back)) //check available back cam
                {
                    IReadOnlyList <Windows.Foundation.Size> supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                    Windows.Foundation.Size res = supportedResolutions[0];
                    captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, res); // init object Photo Capture Device
                }
                else // check front cam
                {
                    IReadOnlyList <Windows.Foundation.Size> supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
                    Windows.Foundation.Size res = supportedResolutions[0];
                    captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Front, res);
                }

                captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, captureDevice.SensorLocation == CameraSensorLocation.Back
                    ? captureDevice.SensorRotationInDegrees :-captureDevice.SensorRotationInDegrees);
                ViewFinderPanel.SetSource(captureDevice); //set source VideoBrush
                ViewFinderPanel.RelativeTransform = new CompositeTransform()
                {
                    CenterX = 0.5, CenterY = 0.5, Rotation = 90
                };                                                                                                            //set transform portrait
            }
        }
        async void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            Size targetMediaElementSize = new Size(640, 480);
            double aspectRatio = 4.0/3.0;

            // 1. Open camera 
            if (m_camera == null)
            {
                var captureRes = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                Size selectedCaptureRes = captureRes.Where(res => Math.Abs(aspectRatio - res.Width/res.Height ) <= 0.1)
                                                    .OrderBy(res => res.Width)
                                                    .Last();
                m_camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, selectedCaptureRes);
                m_camera.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, m_camera.SensorLocation == CameraSensorLocation.Back ? m_camera.SensorRotationInDegrees : -m_camera.SensorRotationInDegrees);
               
                var previewRes = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back);
                Size selectedPreviewRes = previewRes.Where(res => Math.Abs(aspectRatio - res.Width/res.Height ) <= 0.1) 
                                                    .Where(res => (res.Height >= targetMediaElementSize.Height) && (res.Width >= targetMediaElementSize.Width))
                                                    .OrderBy(res => res.Width)
                                                    .First();
                await m_camera.SetPreviewResolutionAsync(selectedPreviewRes);
                cameraEffect.CaptureDevice = m_camera;
            }

            // Always create a new source, otherwise the MediaElement will not start.
            source = new CameraStreamSource(cameraEffect, targetMediaElementSize);
            MyCameraMediaElement.SetSource(source);

            m_timer = new DispatcherTimer();
            m_timer.Interval = new TimeSpan(0, 0, 0, 1, 0); // Tick every 1s.
            m_timer.Tick += m_timer_Tick;
            m_timer.Start();
        }
예제 #6
0
        private void LoadResolutions(CameraPosition cameraPosition)
        {
            IReadOnlyList <Windows.Foundation.Size> availableResolutions;

            AvailableResolutions.Clear();

            if (cameraPosition == CameraPosition.Back)
            {
                availableResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
            }
            else
            {
                availableResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
            }

            if (availableResolutions != null)
            {
                foreach (var resolution in availableResolutions)
                {
                    AvailableResolutions.Add(new Resolution(resolution));
                }
            }

            if (AvailableResolutions != null)
            {
                if (AvailableResolutions.Count > 0)
                {
                    SelectedResolution = AvailableResolutions[AvailableResolutions.Count() - 1];
                }
            }

            OpenCameraDevice(cameraPosition);
        }
        private async void InitCamera()
        {
            if (this.commandeRunning)
            {
                return;
            }
            try
            {
                this.commandeRunning = true;
                if (this.captureDevice != null)
                {
                    this.captureDevice.Dispose();
                    this.captureDevice = null;
                }

                var supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(this.sensorLocation).ToArray();
                this.captureDevice = await PhotoCaptureDevice.OpenAsync(this.sensorLocation, supportedResolutions[0]);

                this.viewfinderBrush.SetSource(this.captureDevice);

                this.ComputeVideoBruchTransform();
            }

            finally
            {
                this.commandeRunning = false;
            }
        }
예제 #8
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back) ||
                PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front))
            {
                if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
                {
                    System.Collections.Generic.IReadOnlyList<Windows.Foundation.Size> SupportedResolutions =
                        PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                    Windows.Foundation.Size res = SupportedResolutions[0];
                    captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, res);
                }
                else
                {
                    System.Collections.Generic.IReadOnlyList<Windows.Foundation.Size> SupportedResolutions =
                        PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
                    Windows.Foundation.Size res = SupportedResolutions[0];
                    captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Front, res);
                }
                viewfinderBrush.SetSource(captureDevice);
            }
            else
            {
                msg.Text = "相机不可用";
            }

            base.OnNavigatedTo(e);
        }
예제 #9
0
 public void Release()
 {
     _timer.Stop();
     _photoDevice.Dispose();
     _photoDevice = null;
     _frameBuffer = null;
 }
예제 #10
0
        /// <summary>
        /// If camera has not been initialized when navigating to this page, initialization
        /// will be started asynchronously in this method. Once initialization has been
        /// completed the camera will be set as a source to the VideoBrush element
        /// declared in XAML. On-screen controls are enabled when camera has been initialized.
        /// </summary>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {


            if (_photoCaptureDevice != null)
            {
                _photoCaptureDevice.Dispose();
                _photoCaptureDevice = null;
            }

            ShowProgress(AppResources.InitializingCameraText);
            await InitializeCamera(CameraSensorLocation.Back);
            HideProgress();
            BackgroundVideoBrush.SetSource(_photoCaptureDevice);

            SetScreenButtonsEnabled(true);
            SetCameraButtonsEnabled(true);
            Storyboard sb = (Storyboard)Resources["CaptureAnimation"];
            sb.Stop();

            SetOrientation(this.Orientation);

            

            base.OnNavigatedTo(e);
        }
예제 #11
0
        protected RangeParameter(PhotoCaptureDevice device, Guid propertyId, string name)
            : base(device, name)
        {
            _propertyId = propertyId;

            Refresh();
        }
예제 #12
0
        /// <summary>
        /// Reads supported white balance preset values from Parameter.Device and populates
        /// ArrayParameter.Options accordingly. Sets the SelectedOption as well.
        ///
        /// White balace preset auto value is set by setting the value in PhotoCaptureDevice API to
        /// null, therefore the separate handling for option "Auto".
        /// </summary>
        protected override void PopulateOptions()
        {
            ArrayParameterOption option         = new ArrayParameterOption(null, "Auto");
            ArrayParameterOption selectedOption = option;

            Options.Add(option);

            IReadOnlyList <object> supportedValues = PhotoCaptureDevice.GetSupportedPropertyValues(Device.SensorLocation, PropertyId);
            object value = Device.GetProperty(PropertyId);

            foreach (dynamic i in supportedValues)
            {
                WhiteBalancePreset wbp = (WhiteBalancePreset)i;

                option = new ArrayParameterOption(wbp, wbp.EnumerationToParameterName <WhiteBalancePreset>());

                Options.Add(option);

                if (i.Equals(value))
                {
                    selectedOption = option;
                }
            }

            SelectedOption = selectedOption;
        }
예제 #13
0
        public async void initialise()
        {
            // Disable transmit.
            transmit = false;
            // Get available resolutions.
            IReadOnlyList <Windows.Foundation.Size> available_res = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
            int count = available_res.Count;

            // Make the resolution details public
            imheight = (int)available_res[count - 1].Height;
            imwidth  = (int)available_res[count - 1].Width;
            // Allocate memory for the preview image variable
            preview_image = new int[imheight * imwidth];
            // Open a new capture device asynchronously.
            cam_open_busy = true;
            _camera       = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, available_res[count - 1]);

            cam_open_busy = false;
            // Set the exposure time to 200ms
            // _camera.SetProperty(KnownCameraPhotoProperties.ExposureTime, 200000);
            // Create a new sequence
            _camsequence = _camera.CreateCaptureSequence(1);
            // Create a new memory stream.
            imstream = new MemoryStream();
            _camsequence.Frames[0].CaptureStream = imstream.AsOutputStream();
            // Wait for the camera to initialize.
            await _camera.PrepareCaptureSequenceAsync(_camsequence);
        }
예제 #14
0
        // Override method for adjusting exposure time.
        public async void set_focus(double focus_val, int exposure_time)
        {
            // Set exposure time.
            try
            {
                _camera.SetProperty(KnownCameraPhotoProperties.ExposureTime, exposure_time * 1000);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            focus_busy = true;
            try
            {
                CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(CameraSensorLocation.Back, KnownCameraGeneralProperties.ManualFocusPosition);
                double value = (UInt32)range.Min + (focus_val / 100.0) * ((UInt32)range.Max - (UInt32)range.Min);
                focus_min = (UInt32)range.Min;
                focus_max = (UInt32)range.Max;
                _camera.SetProperty(KnownCameraGeneralProperties.ManualFocusPosition, (UInt32)value);
            }
            //
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            await _camera.FocusAsync();

            focus_busy = false;
        }
예제 #15
0
        async private Task <PhotoCaptureDevice> InitCamera(CameraPreviewSettings settings, CameraSensorLocation loc)
        {
            PhotoCaptureDevice camera = await OpenCamera(settings.Width, settings.Height, loc);

            UInt32                     iso           = Helper.GetISO((UInt32)settings.ISO, loc);
            Nullable <UInt32>          wb            = Helper.GetWhiteBalance(settings.WhiteBalance, loc);
            CameraCapturePropertyRange focusRange    = PhotoCaptureDevice.GetSupportedPropertyRange(loc, KnownCameraGeneralProperties.ManualFocusPosition);
            UInt32                     focusDistance = settings.FocusDistance.Equals("min", StringComparison.OrdinalIgnoreCase) ? (UInt32)focusRange.Min : (UInt32)focusRange.Max;

            camera.SetProperty(KnownCameraPhotoProperties.ExposureCompensation, 0);
            camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off);
            camera.SetProperty(KnownCameraPhotoProperties.FocusIlluminationMode, 0);

            if (wb.HasValue)
            {
                camera.SetProperty(KnownCameraPhotoProperties.WhiteBalancePreset, wb.Value);
                _waitForWb = true;
                Debug.WriteLine("Using WB value: {0}", wb.Value);
            }

            camera.SetProperty(KnownCameraPhotoProperties.Iso, iso);
            camera.SetProperty(KnownCameraGeneralProperties.ManualFocusPosition, focusDistance);

            Debug.WriteLine("Using ISO: {0}, Using Focus Distance: {1}", camera.GetProperty(KnownCameraPhotoProperties.Iso), camera.GetProperty(KnownCameraGeneralProperties.ManualFocusPosition));

            return(camera);
        }
예제 #16
0
        /// <summary>
        /// Reads supported ISO values from Parameter.Device and populates
        /// ArrayParameter.Options accordingly. Sets the SelectedOption as well.
        ///
        /// ISO auto value is set by setting the value in PhotoCaptureDevice API to
        /// null, therefore the separate handling for option "Auto".
        /// </summary>
        protected override void PopulateOptions()
        {
            ArrayParameterOption option         = new ArrayParameterOption(null, "Auto", "Assets/Icons/overlay.iso.auto.png");
            ArrayParameterOption selectedOption = option;

            Options.Add(option);

            CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation, PropertyId);
            object value = Device.GetProperty(PropertyId);

            UInt32[] standardValues = { 100, 200, 400, 800, 1600, 3200 };

            UInt32 min = (UInt32)range.Min;
            UInt32 max = (UInt32)range.Max;

            foreach (UInt32 i in standardValues)
            {
                if (i >= min && i <= max)
                {
                    option = new ArrayParameterOption(i, "ISO " + i.ToString(), "Assets/Icons/overlay.iso." + i.ToString() + ".png");

                    Options.Add(option);

                    if (i.Equals(value))
                    {
                        selectedOption = option;
                    }
                }
            }

            SelectedOption = selectedOption;
        }
예제 #17
0
        protected override void PopulateOptions()
        {
            var auto = new ArrayParameterOption <uint?>(null, "Auto");

            Options.Add(auto);
            SelectedOption = auto;

            CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation,
                                                                                            ParameterId);
            object currentValue = Device.GetProperty(ParameterId);

            uint[] standardValues = { 100, 200, 400, 800, 1600, 3200 };

            var min = (uint)range.Min;
            var max = (uint)range.Max;

            foreach (uint isoValue in standardValues)
            {
                if (isoValue >= min && isoValue <= max)
                {
                    string name   = string.Format("ISO {0}", isoValue);
                    var    option = new ArrayParameterOption <uint?>(isoValue, name);
                    Options.Add(option);

                    if (isoValue.Equals(currentValue))
                    {
                        SelectedOption = option;
                    }
                }
            }
        }
예제 #18
0
    private async Task initCameraAsync(CameraSensorLocation sensorLocation) {

      if (cam != null) {
        cam.Dispose();
        cam = null;
      }


      Windows.Foundation.Size res = new Windows.Foundation.Size(640, 480);

      cam = await PhotoCaptureDevice.OpenAsync(sensorLocation, res);
      await cam.SetPreviewResolutionAsync(res);

      viewfinder.SetSource(cam);

      viewfinderTransform.Rotation = sensorLocation == CameraSensorLocation.Back ?
                                       cam.SensorRotationInDegrees : -cam.SensorRotationInDegrees;

      imgFilterTransform.Rotation = sensorLocation == CameraSensorLocation.Back ?
                                       cam.SensorRotationInDegrees : -cam.SensorRotationInDegrees;

      // Vorbereitung für die Live s/w Vorschau
      bmp = new WriteableBitmap((int)cam.PreviewResolution.Width,  (int)cam.PreviewResolution.Height);
      timer = new DispatcherTimer {
        Interval = TimeSpan.FromMilliseconds(10)
      };
      timer.Tick += timer_Tick;
      timer.Start();

    }
예제 #19
0
        public async Task InitializeAsync()
        {
            if (_isInitialized)
            {
                return;
            }

            IReadOnlyList <Size> availableCaptureResulotions =
                PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);

            Device = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, availableCaptureResulotions.First());

            InitParameters();
            Device.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, true);

            _captureStream   = new MemoryStream();
            _captureSequence = Device.CreateCaptureSequence(1);
            _captureSequence.Frames[0].CaptureStream = _captureStream.AsOutputStream();
            await Device.PrepareCaptureSequenceAsync(_captureSequence);

            CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
            CameraButtons.ShutterKeyPressed     += CameraButtons_ShutterKeyPressed;
            CameraButtons.ShutterKeyReleased    += CameraButtons_ShutterKeyReleased;

            _isInitialized = true;
        }
예제 #20
0
        /// <summary>
        /// Initializes camera. Once initialized the instance is set to the
        /// DataContext.Device property for further usage from this or other
        /// pages.
        /// </summary>
        /// <param name="sensorLocation">Camera sensor to initialize.</param>
        private async Task InitializeCamera(CameraSensorLocation sensorLocation)
        {
            // Find out the largest capture resolution available on device
            IReadOnlyList <Size> availableResolutions =
                PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);

            var captureResolution = new Windows.Foundation.Size(0, 0);

            foreach (Size t in availableResolutions)
            {
                if (captureResolution.Width < t.Width)
                {
                    captureResolution = t;
                }
            }

            PhotoCaptureDevice device =
                await PhotoCaptureDevice.OpenAsync(sensorLocation, _defaultCameraResolution);

            await device.SetPreviewResolutionAsync(_defaultCameraResolution);

            await device.SetCaptureResolutionAsync(captureResolution);

            device.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
                               device.SensorLocation == CameraSensorLocation.Back ?
                               device.SensorRotationInDegrees : -device.SensorRotationInDegrees);

            PhotoCaptureDevice   = device;
            _isCameraInitialized = true;
        }
예제 #21
0
        public override sealed void ReadCurrent()
        {
            try
            {
                CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation,
                                                                                                ParameterId);
                if (range == null)
                {
                    IsSupported = false;
                }
                else
                {
                    Minimum     = (T)range.Min;
                    Maximum     = (T)range.Max;
                    _value      = (T)Device.GetProperty(ParameterId);
                    IsSupported = true;
                }
            }
            catch (Exception)
            {
                IsSupported = false;
            }

            IsModifiable = IsSupported && !Minimum.Equals(Maximum);
        }
예제 #22
0
        /// <summary>
        /// Initializes camera. Once initialized the instance is set to the
        /// DataContext.Device property for further usage from this or other
        /// pages.
        /// </summary>
        /// <param name="sensorLocation">Camera sensor to initialize.</param>
        private async Task InitializeCamera(CameraSensorLocation sensorLocation)
        {
            // Find out the largest capture resolution available on device
            IReadOnlyList <Windows.Foundation.Size> availableResolutions =
                PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);

            Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(0, 0);

            for (int i = 0; i < availableResolutions.Count; ++i)
            {
                if (captureResolution.Width < availableResolutions[i].Width)
                {
                    Debug.WriteLine("MainPage.InitializeCamera(): New capture resolution: " + availableResolutions[i]);
                    captureResolution = availableResolutions[i];
                }
            }

            PhotoCaptureDevice device =
                await PhotoCaptureDevice.OpenAsync(sensorLocation, DefaultCameraResolution);

            await device.SetPreviewResolutionAsync(DefaultCameraResolution);

            await device.SetCaptureResolutionAsync(captureResolution);

            device.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
                               device.SensorLocation == CameraSensorLocation.Back ?
                               device.SensorRotationInDegrees : -device.SensorRotationInDegrees);

            _dataContext.Device = device;
        }
예제 #23
0
        private async Task InitCamera()
        {
            if (!PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
            {
                MessageBox.Show("No primary camera found. Unable to capture photos.", "Error", MessageBoxButton.OK);
                cameraButton.IsEnabled = false;
                return;
            }

            System.Collections.Generic.IReadOnlyList <Windows.Foundation.Size> supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);

            Windows.Foundation.Size res = GetResolution(supportedResolutions);
            Camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, res);

            Camera.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off);
            Camera.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, App.ShutterSoundEnabled);
            Camera.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Normal);
            CameraButtons.ShutterKeyHalfPressed += OnCameraButtonHalfPress;
            CameraButtons.ShutterKeyPressed     += OnCameraButtonFullPress;

            var viewFinderTransform = new CompositeTransform();

            viewFinderTransform.CenterX       = 0.5;
            viewFinderTransform.CenterY       = 0.5;
            viewfinderBrush                   = new VideoBrush();
            viewfinderBrush.RelativeTransform = viewFinderTransform;
            viewfinderBrush.Stretch           = Stretch.UniformToFill;
            camCanvas.Background              = viewfinderBrush;
            viewfinderBrush.SetSource(Camera);
            m_canTakePicture = true;
        }
예제 #24
0
        /// <summary>
        /// Reads the range minimum, maximum and current value. Sets Supported and Modifiable
        /// appropriately.
        /// </summary>
        public override void Refresh()
        {
            try
            {
                CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation, _propertyId);

                if (range == null)
                {
                    Supported = false;
                }
                else
                {
                    Minimum   = (T)range.Min;
                    Maximum   = (T)range.Max;
                    _value    = (T)Device.GetProperty(_propertyId);
                    Supported = true;
                }
            }
            catch (Exception)
            {
                Supported = false;

                System.Diagnostics.Debug.WriteLine("Getting " + Name.ToLower() + " failed");
            }

            Modifiable = Supported && !_minimum.Equals(_maximum);

            if (Supported)
            {
                NotifyPropertyChanged("Value");
                NotifyPropertyChanged("OverlaySource");
            }
        }
예제 #25
0
 private void ShutDownCamera()
 {
     if (Camera != null)
     {
         Camera.Dispose();
         Camera = null;
     }
 }
 // Code to execute when the application is deactivated (sent to background)
 // This code will not execute when the application is closing
 private void Application_Deactivated(object sender, DeactivatedEventArgs e)
 {
     if (Camera != null)
     {
         Camera.Dispose();
         Camera = null;
     }
 }
 // Code to execute when the application is closing (eg, user hit Back)
 // This code will not execute when the application is deactivated
 private void Application_Closing(object sender, ClosingEventArgs e)
 {
     if (Camera != null)
     {
         Camera.Dispose();
         Camera = null;
     }
 }
 public void StopPreview()
 {
     this.isPreviewRunning = false;
     if (this.captureDevice != null)
     {
         this.captureDevice.Dispose();
         this.captureDevice = null;
     }
 }
예제 #29
0
        private void UninitializeCamera()
        {
            if (_device != null)
            {
                _device.PreviewFrameAvailable -= PhotoCaptureDevice_PreviewFrameAvailable;

                _device.Dispose();
                _device = null;
            }
        }
        public void strop()
        {
            m_previewRunning = false;
            if (m_captureDevice != null)
            {
                m_captureDevice.Dispose();
                m_captureDevice = null;

            }
        }
        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            var resolution = new Windows.Foundation.Size(640, 480);
            var task       = PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, new Windows.Foundation.Size(640, 480)).AsTask();

            task.Wait();

            Camera = task.Result;
            Camera.SetPreviewResolutionAsync(resolution).AsTask().Wait();
        }
예제 #32
0
        async private Task <PhotoCaptureDevice> OpenCamera(int width, int height, CameraSensorLocation loc)
        {
            var sizes = Helper.GetCameraSize(new Size(width, height), loc);

            PhotoCaptureDevice camera = await PhotoCaptureDevice.OpenAsync(loc, sizes["captureSize"]);

            await camera.SetPreviewResolutionAsync(sizes["previewSize"]);

            return(camera);
        }
예제 #33
0
        private async void Canvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (!_focusing && !_capturing)
            {
                _focusing = true;

                var point  = e.GetPosition(Canvas);
                var scaleX = _device.PreviewResolution.Width / Canvas.ActualWidth;
                var scaleY = _device.PreviewResolution.Height / Canvas.ActualHeight;

                // Show focusing bracket and set focus region if supported by the HW

                if (PhotoCaptureDevice.IsFocusRegionSupported(SENSOR_LOCATION))
                {
                    FocusBracket.RenderTransform = new TranslateTransform()
                    {
                        X = point.X,
                        Y = point.Y
                    };

                    FocusBracket.Visibility = Visibility.Visible;

                    _device.FocusRegion = new Windows.Foundation.Rect(point.X * scaleX, point.Y * scaleY, 1, 1);
                }

                // Focus and capture if focus is supported by the HW, otherwise just capture

                if (PhotoCaptureDevice.IsFocusSupported(SENSOR_LOCATION))
                {
                    CameraFocusStatus status;

                    try
                    {
                        status = await _device.FocusAsync();
                    }
                    catch (Exception)
                    {
                        status = CameraFocusStatus.NotLocked;
                    }

                    _focusing = false;

                    FocusBracket.Visibility = Visibility.Collapsed;

                    if (status == CameraFocusStatus.Locked)
                    {
                        await CaptureAsync();
                    }
                }
                else
                {
                    await CaptureAsync();
                }
            }
        }
예제 #34
0
        private async Task <Size> GetBestCaptureResolution()
        {
            // The last size in the AvailableCaptureResolutions is the lowest available
            var captureResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
            var previewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back);

            Size resolution = await Task.Factory.StartNew(() => captureResolutions.Last(
                                                              c => (c.Width > 1000.0 || c.Height > 1000.0) && previewResolutions.Any(p => (c.Width / c.Height).Equals(p.Width / p.Height))));

            return(resolution);
        }
예제 #35
0
        /// <summary>
        /// Reads supported exposure time values from Parameter.Device and populates
        /// ArrayParameter.Options accordingly. Sets the SelectedOption as well.
        ///
        /// Exposure time auto value is set by setting the value in PhotoCaptureDevice API to
        /// null, therefore the separate handling for option "Auto".
        /// </summary>
        protected override void PopulateOptions()
        {
            ArrayParameterOption option         = new ArrayParameterOption(null, "Auto", "Assets/Icons/overlay.exposuretime.auto.png");
            ArrayParameterOption selectedOption = option;

            Options.Add(option);

            CameraCapturePropertyRange range = PhotoCaptureDevice.GetSupportedPropertyRange(Device.SensorLocation, KnownCameraPhotoProperties.ExposureTime);
            object value = Device.GetProperty(PropertyId);

            // UInt32[] standardValues = { /* 16000, 8000, 4000,*/ 2000, 1000, 500, 250, 125, 60, 30, 15, 8, 4, 2 };
            UInt32[] standardValues = { 16666, 16000, 8000, 4000, 2000, 1000, 500, 250, 125, 60, 30, 15, 8, 4, 2 };

            UInt32 min = (UInt32)range.Min;
            UInt32 max = (UInt32)range.Max;

            System.Diagnostics.Debug.WriteLine(String.Format("Exposure time range (min {0}, max {1})", min, max));

            foreach (UInt32 i in standardValues)
            {
                UInt32 usecs = 1000000 / i;

                if (usecs >= min && usecs <= max)
                {
                    option = new ArrayParameterOption(usecs, "1 / " + i.ToString() + " s", "Assets/Icons/overlay.exposuretime." + i.ToString() + ".png");

                    Options.Add(option);

                    if (selectedOption == null && usecs.Equals(value))
                    {
                        selectedOption = option;
                    }
                }
            }

            // Expsoure times of 1 second and over are possible in some devices.
            UInt32 microseconds = 1000000; // second in microseconds

            while (microseconds <= max)
            {
                UInt32 usecs = microseconds / 1000000;
                option = new ArrayParameterOption(microseconds, usecs.ToString() + " s", "Assets/Icons/overlay.exposuretime." + usecs.ToString() + "s.png");

                Options.Add(option);

                if (selectedOption == null && usecs.Equals(value))
                {
                    selectedOption = option;
                }
                microseconds *= 2;
            }

            SelectedOption = selectedOption;
        }
예제 #36
0
        private void DestroyCam()
        {
            if (cam != null)
            {
                cam.Dispose();
                cam = null;
                seq = null;
            }

            CameraButtons.ShutterKeyHalfPressed -= OnShutterHalfPress;
            CameraButtons.ShutterKeyPressed -= OnShutterFullPress;
            CameraButtons.ShutterKeyReleased -= OnShutterReleased;
        }
예제 #37
0
    private async Task initCameraAsync(CameraSensorLocation sensorLocation) {

      if (_cam != null) {
        _cam.Dispose();
        _cam = null;
      }


      var res = new Windows.Foundation.Size(640, 480);

      _cam = await PhotoCaptureDevice.OpenAsync(sensorLocation, res);
      await _cam.SetPreviewResolutionAsync(res);

      viewfinder.SetSource(_cam);

      viewfinderTransform.Rotation = sensorLocation == CameraSensorLocation.Back ?
                                       _cam.SensorRotationInDegrees : -_cam.SensorRotationInDegrees;



    }
        async void IinitCamera()
        {
            canvas.Children.Clear();
            camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First());

            previewtmp = new WriteableBitmap((int)camera.PreviewResolution.Width, (int)camera.PreviewResolution.Height);
            preview = new WriteableBitmap((int)camera.PreviewResolution.Width,(int)camera.PreviewResolution.Height);
           

          

            var t1 = new Triangle(
                new Triangle.Point(0, 0, 0, 0),
                new Triangle.Point(0, 480, 0, 1),
                new Triangle.Point(240, 480, 0.5, 1));
            var t2 = new Triangle(
               new Triangle.Point(0, 0, 0, 0),
               new Triangle.Point(240, 480, 0.5, 1),
               new Triangle.Point(480, 0, 1, 0));

            var t3 = new Triangle(
              new Triangle.Point(480, 0,1, 0),
              new Triangle.Point(240, 480, 0.5, 1),
              new Triangle.Point(480, 480, 1, 1));


            t1.ImageSource = preview;
            t2.ImageSource = preview;
            t3.ImageSource = preview;
            canvas.Children.Add(t1.Polygon);
            canvas.Children.Add(t2.Polygon);
            canvas.Children.Add(t3.Polygon);

            camera.PreviewFrameAvailable += camera_PreviewFrameAvailable;
          


        }
예제 #39
0
        /// <summary>
        /// Initializes camera.
        /// </summary>
        /// <param name="sensorLocation">Camera sensor to initialize</param>
        private async Task InitializeCamera(CameraSensorLocation sensorLocation)
        {
            Windows.Foundation.Size initialResolution =
                new Windows.Foundation.Size(FilterEffects.DataContext.DefaultPreviewResolutionWidth,
                                            FilterEffects.DataContext.DefaultPreviewResolutionHeight);
            Windows.Foundation.Size previewResolution =
                new Windows.Foundation.Size(FilterEffects.DataContext.DefaultPreviewResolutionWidth,
                                            FilterEffects.DataContext.DefaultPreviewResolutionHeight);

            // Find out the largest 4:3 capture resolution available on device
            IReadOnlyList<Windows.Foundation.Size> availableResolutions =
                PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);

            Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(0, 0);

            for (int i = 0; i < availableResolutions.Count; i++)
            {
                double ratio = availableResolutions[i].Width / availableResolutions[i].Height;
                if (ratio > 1.32 && ratio < 1.34)
                {
                    if (captureResolution.Width < availableResolutions[i].Width)
                    {
                        captureResolution = availableResolutions[i];
                    }
                }
            }
 
            PhotoCaptureDevice device =
                await PhotoCaptureDevice.OpenAsync(sensorLocation, initialResolution);

            await device.SetPreviewResolutionAsync(previewResolution);
            await device.SetCaptureResolutionAsync(captureResolution);

            _photoCaptureDevice = device;

            SetOrientation(this.Orientation);
        }
        private void InitializeCamera()
        {
            var captureResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).ToArray();
            var previewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back).ToArray();

            Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(640, 480);
            Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(640, 480);

            try
            {
                captureResolution = GetFirstWideResolution(captureResolutions);
                previewResolution = GetFirstWideResolution(previewResolutions);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Unable to get wide resolution for viewfinder, using 640x480");
            }

            var task = PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, captureResolution).AsTask();

            task.Wait();

            _device = task.Result;
            _device.SetPreviewResolutionAsync(previewResolution).AsTask().Wait();

            var objectResolutionSide = _device.PreviewResolution.Height * (ReaderBorder.Height - 2 * ReaderBorder.Margin.Top) / 480;
            var objectResolution = new Windows.Foundation.Size(objectResolutionSide, objectResolutionSide);
            var focusRegionSize = new Windows.Foundation.Size(objectResolutionSide, objectResolutionSide);
            var objectSize = OpticalReaderLib.OpticalReaderTask.Instance.ObjectSize;

            if (objectSize.Width * objectSize.Height > 0)
            {
                var parameters = OpticalReaderLib.Utilities.GetSuggestedParameters(_device.PreviewResolution, _device.SensorRotationInDegrees, objectSize, objectResolution);

                _zoom = Math.Max(parameters.Zoom, 1.0);
            }
            else
            {
                _zoom = 1.0;
            }

            var centerPoint = new Windows.Foundation.Point(previewResolution.Width / 2, previewResolution.Height / 2);

            _device.FocusRegion = new Windows.Foundation.Rect(
                centerPoint.X - focusRegionSize.Width / 2, centerPoint.Y - focusRegionSize.Height / 2,
                focusRegionSize.Width, focusRegionSize.Height);

            ViewfinderVideoBrush.SetSource(_device);
        }
        private void Uninitialize()
        {
            StatusTextBlock.Text = "";

            if (_mediaElement != null)
            {
                _mediaElement.Source = null;
                _mediaElement = null;
            }

            if (_cameraStreamSource != null)
            {
                _cameraStreamSource.FrameRateChanged -= CameraStreamSource_FPSChanged;
                _cameraStreamSource = null;
            }

            _cameraEffect = null;

            if (_photoCaptureDevice != null)
            {
                _photoCaptureDevice.Dispose();
                _photoCaptureDevice = null;
            }
        }
예제 #42
0
        /// <summary>
        /// Opens and sets up the camera if not already. Creates a new
        /// CameraStreamSource with an effect and shows it on the screen via
        /// the media element.
        /// </summary>
        private async void Initialize()
        {
            Size mediaElementSize = new Size(MediaElementWidth, MediaElementHeight);

            if (camera == null)
            {
                // Resolve the capture resolution and open the camera
                var captureResolutions =
                    PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);

                Size selectedCaptureResolution =
                    captureResolutions.Where(
                        resolution => Math.Abs(AspectRatio - resolution.Width / resolution.Height) <= 0.1)
                            .OrderBy(resolution => resolution.Width).Last();

                camera = await PhotoCaptureDevice.OpenAsync(
                    CameraSensorLocation.Back, selectedCaptureResolution);

                // Set the image orientation prior to encoding
                camera.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
                    camera.SensorLocation == CameraSensorLocation.Back
                    ? camera.SensorRotationInDegrees : -camera.SensorRotationInDegrees);

                // Resolve and set the preview resolution
                var previewResolutions =
                    PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back);

                Size selectedPreviewResolution =
                    previewResolutions.Where(
                        resolution => Math.Abs(AspectRatio - resolution.Width / resolution.Height) <= 0.1)
                            .Where(resolution => (resolution.Height >= mediaElementSize.Height)
                                   && (resolution.Width >= mediaElementSize.Width))
                                .OrderBy(resolution => resolution.Width).First();

                await camera.SetPreviewResolutionAsync(selectedPreviewResolution);

                cameraEffect.CaptureDevice = camera;
            }


            if (mediaElement == null)
            {
                mediaElement = new MediaElement();
                mediaElement.Stretch = Stretch.UniformToFill;
                mediaElement.BufferingTime = new TimeSpan(0);
                mediaElement.Tap += OnMyCameraMediaElementTapped;
                source = new CameraStreamSource(cameraEffect, mediaElementSize);
                mediaElement.SetSource(source);
                MediaElementContainer.Children.Add(mediaElement);
                
            } 
            
            // Show the index and the name of the current effect
            if (cameraEffect is NokiaSketchEffect)
            {
                NokiaSketchEffect effects = cameraEffect as NokiaSketchEffect;
            }
            
        }
        /// <summary>
        /// On-screen controls are disabled when navigating away from the
        /// viewfinder. This is because we want the controls to default to
        /// disabled when arriving to the page again.
        /// </summary>
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            Uninitialize();

            if (Camera != null)
            {
                Camera.Dispose();
                Camera = null;
            }

            SetScreenButtonsEnabled(false);
            SetCameraButtonsEnabled(false);

            base.OnNavigatingFrom(e);
        }
        async void initCamera()
        {
            if (commandeRunning)
                return;
            try
            {
                commandeRunning = true;
                if (m_captureDevice != null)
                {
                    m_captureDevice.Dispose();
                    m_captureDevice = null;

                }

                // Use the back camera.
                /*  var deviceName = Microsoft.Phone.Info.DeviceStatus.DeviceName;
                  if (m_sensorLocation == CameraSensorLocation.Back && (deviceName.Contains("RM-875") || deviceName.Contains("RM-876") || deviceName.Contains("RM-877")))
                  {
                      m_captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, new Windows.Foundation.Size(7712, 4352));
                      //m_captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back,new Windows.Foundation.Size(7136,5360));

                  }
                  else if (m_sensorLocation == CameraSensorLocation.Back && (deviceName.Contains("RM-937") || deviceName.Contains("RM-938") || deviceName.Contains("RM-939")))
                  {
                      m_captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, new Windows.Foundation.Size(5376, 3024)); // 16:9 ratio
                      //m_captureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back,new Windows.Foundation.Size(4992, 3744)); // 4:3 ratio
                  }
                  else*/
                {
                    var SupportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(m_sensorLocation).ToArray();
                    m_captureDevice = await PhotoCaptureDevice.OpenAsync(m_sensorLocation, SupportedResolutions[0]);
                }

                viewfinderBrush.SetSource(m_captureDevice);

                computeVideoBruchTransform();
            }

            finally
            {
                commandeRunning = false;

            }

        }
예제 #45
0
 protected Parameter(string name, Guid propertyId, PhotoCaptureDevice device)
 {
     Name = name;
     ParameterId = propertyId;
     Device = device;
 }
예제 #46
0
 protected UrlParameter(PhotoCaptureDevice device, String name)
     : base(device, name)
 {
 }
        public async Task InitializeCamera(CameraSensorLocation sensorLocation)
        {
            activeThreads = 0;
            isClosing = false;
            Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(1280, 720);
            Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(1280, 720);

            IReadOnlyList<Windows.Foundation.Size> prevSizes = PhotoCaptureDevice.GetAvailablePreviewResolutions(sensorLocation);
            IReadOnlyList<Windows.Foundation.Size> captSizes = PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);

          
            double bestAspect = 1000;

            int bestAspectResIndex = 0;


            double aspect =  Application.Current.Host.Content.ActualHeight / Application.Current.Host.Content.ActualWidth;

           
            for (int i = 0; i < captSizes.Count; i++)
            {
                double w = captSizes[i].Width;
                double h = captSizes[i].Height;

                double resAspect = w / h;

                double diff = aspect - resAspect;
                if (diff < 0)
                    diff = -diff;


                if (diff < bestAspect)
                {
                    bestAspect = diff;
                    bestAspectResIndex = i;
                }

               
            }

            if (bestAspectResIndex >= 0)
            {
                captureResolution.Width = captSizes[bestAspectResIndex].Width;
                captureResolution.Height = captSizes[bestAspectResIndex].Height;
            }

            Windows.Foundation.Size initialResolution = captureResolution;

            try
            {
                PhotoCaptureDevice d = null;
             

                System.Diagnostics.Debug.WriteLine("Settinge camera initial resolution: " + initialResolution.Width + "x" + initialResolution.Height + "......");

                bool initialized = false;

                try
                {
                    d = await PhotoCaptureDevice.OpenAsync(sensorLocation, initialResolution);
                    System.Diagnostics.Debug.WriteLine("Success " + initialResolution);
                    initialized = true;
                    captureResolution = initialResolution;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Failed to set initial resolution: " + initialResolution + " error:" + e.Message);

                }

                if (!initialized)
                    try
                    {
                        d = await PhotoCaptureDevice.OpenAsync(sensorLocation, captSizes.ElementAt<Windows.Foundation.Size>(0));
                        System.Diagnostics.Debug.WriteLine("Success " + captSizes.ElementAt<Windows.Foundation.Size>(0));
                        initialized = true;
                        captureResolution = captSizes.ElementAt<Windows.Foundation.Size>(0);
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to set initial resolution: " + captSizes.ElementAt<Windows.Foundation.Size>(0));
                    }

                //try to not use too high resolution

                if (param_EnableHiRes)
                {
                    MAX_RESOLUTION = 1280 * 800;
                }
                else
                {
                    MAX_RESOLUTION = 800 * 480;
                }


                if (d.PreviewResolution.Height * d.PreviewResolution.Width > MAX_RESOLUTION)
                {

                    bestAspectResIndex = -1;

                    aspect = (double)captureResolution.Width / captureResolution.Height;

                    for (int i = 0; i < prevSizes.Count; i++)
                    {
                        double w = prevSizes[i].Width;
                        double h = prevSizes[i].Height;

                        double resAspect = w / h;

                        double diff = aspect - resAspect;
                        if (diff < 0.01 && diff > -0.01)
                        {

                            if (w * h <= MAX_RESOLUTION)
                            {
                                previewResolution = prevSizes.ElementAt<Windows.Foundation.Size>(i);
                                bestAspectResIndex = i;
                                break;
                            }
                        }



                    }


                    if (bestAspectResIndex >= 0)
                        try
                        {
                            await d.SetPreviewResolutionAsync(previewResolution);
                        }
                        finally
                        {

                        }

                }

                System.Diagnostics.Debug.WriteLine("Preview resolution: " + d.PreviewResolution);

                d.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,
                                d.SensorLocation == CameraSensorLocation.Back ?
                                d.SensorRotationInDegrees : -d.SensorRotationInDegrees);


                cameraDevice = d;
                

                cameraDevice.PreviewFrameAvailable += previewFrameHandler;

                IReadOnlyList<object> flashProperties = PhotoCaptureDevice.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);

                if (param_EnableFlash)
                {

                    if (flashProperties.ToList().Contains((UInt32)VideoTorchMode.On))
                    {
                        flashAvailable = true;

                        if (param_DefaultFlashOn)
                        {
                            flashActive = true;
                            cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
                            flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonon.png", UriKind.Relative));
                        }
                        else
                        {
                            flashActive = false;
                            cameraDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
                            flashButtonImage.Source = new BitmapImage(new Uri("/Plugins/com.manateeworks.barcodescanner/flashbuttonoff.png", UriKind.Relative));
                        }

                        flashButton.Visibility = System.Windows.Visibility.Visible;
                        
                        
                    }
                    else
                    {
                        flashAvailable = false;
                        flashButton.Visibility = System.Windows.Visibility.Collapsed;

                    }
                }
                else
                {
                    flashButton.Visibility = System.Windows.Visibility.Collapsed;
                }

                videoBrush.SetSource(cameraDevice);
                focusTimer = new DispatcherTimer();
                focusTimer.Interval = TimeSpan.FromSeconds(3);
                focusTimer.Tick += delegate
                {
                    cameraDevice.FocusAsync();
                };
                focusTimer.Start();

               
            }
            catch (Exception e)
            {
                Debug.WriteLine("Camera initialization error: " + e.Message);
            }

        }
예제 #48
0
        /// <summary>
        /// From PhoneApplicationPage.
        /// Sets the media element source to null and disconnects the event
        /// handling.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            Debug.WriteLine("MainPage.OnNavigatedFrom()");
            //MyCameraMediaElement.Source = null;
            MediaElementContainer.Children.Remove(mediaElement); 
 		            mediaElement = null; 
 		 
 		            if (camera != null) 
 		            { 
 		                camera.Dispose(); 
 		                camera = null; 
 		            }
            
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="_cameraEffect">Camera effect to use.</param>
        /// <param name="size">Size of the media element where the stream is rendered to.</param>
        public CameraStreamSource(PhotoCaptureDevice camera, Windows.Foundation.Size size)
        {
            _camera = camera;

            _frameSize = size;
        }
        protected override void CloseMedia()
        {

            {
                _camera = null;
                if (_frameStream != null)
                {
                    _frameStream.Close();
                    _frameStream = null;
                }




                if (_renderer != null)
                {
                    _renderer.Bitmap = null; // bug  : crash on bitmap dispose

                    _renderer.Dispose();
                    _renderer = null;

                }

                if (_effect != null && _effect is IDisposable)
                {
                    // (_effect as IDisposable).Dispose(); // bug : crash on CustomEffectBase dispose
                    _effect = null;
                }

                if (_source != null)
                {
                    _source.Dispose();
                    _source = null;
                }
                if (_frameBitmap != null)
                {
                    _frameBitmap.Dispose();
                    _frameBitmap = null;
                }
                if (_cameraBitmap != null)
                {
                    _cameraBitmap.Dispose();
                    _cameraBitmap = null;
                }


                _frameStreamOffset = 0;
                _frameTime = 0;

                _frameBufferSize = 0;
                _frameBuffer = null;
                _cameraFrameBuffer = null;
                _videoStreamDescription = null;
                _currentTime = 0;
            }
        }
예제 #51
0
        /// <summary>
        /// On-screen controls are disabled when navigating away from the
        /// viewfinder. This is because we want the controls to default to
        /// disabled when arriving to the page again.
        /// </summary>
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (_photoCaptureDevice != null)
            {
                _photoCaptureDevice.Dispose();
                _photoCaptureDevice = null;
            }

            SetScreenButtonsEnabled(false);
            SetCameraButtonsEnabled(false);


            //AdRequest adRequest = new AdRequest();
            //adRequest.ForceTesting = true;
            //interstitialAd.LoadAd(adRequest);
            //interstitialAd.ReceivedAd += OnAdReceived;




            //if (p == true)
            //{


            //    p = false;

            //    q = true;

            //    interstitialAd.ShowAd();

            //}


            base.OnNavigatingFrom(e);
        }
        private void Uninitialize()
        {


            if (_mediaElement != null)
            {
                _mediaElement.Source = null;
                _mediaElement = null;
            }

            if (_cameraStreamSource != null)
            {

                _cameraStreamSource = null;
            }



            if (_photoCaptureDevice != null)
            {
                _photoCaptureDevice.Dispose();
                _photoCaptureDevice = null;
            }
        }
        void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (m_captureDevice != null)
            {
                m_captureDevice.Dispose();
                m_captureDevice = null;

            }
        }
        private async Task Initialize()
        {


            var resolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(_cameraLocation).First();

            _photoCaptureDevice = await PhotoCaptureDevice.OpenAsync(_cameraLocation, resolution);

            Windows.Foundation.Size PreviewResolution;
            foreach (var res in PhotoCaptureDevice.GetAvailablePreviewResolutions(_cameraLocation).ToArray().Reverse())
            {
                try
                {
                    await _photoCaptureDevice.SetPreviewResolutionAsync(res);
                    PreviewResolution = res;
                    break;

                }
                catch (Exception e)
                {
                }
            }



            _cameraStreamSource = new CameraStreamSource(_photoCaptureDevice, PreviewResolution);

            _mediaElement = new MediaElement();
            _mediaElement.BufferingTime = new TimeSpan(0);
            _mediaElement.SetSource(_cameraStreamSource);

            // Using VideoBrush in XAML instead of MediaElement, because otherwise
            // CameraStreamSource.CloseMedia() does not seem to be called by the framework:/

            BackgroundVideoBrush.SetSource(_mediaElement);



            AdjustOrientation();
        }
        /// <summary>
        /// Initializes camera.
        /// </summary>
        /// <param name="sensorLocation">Camera sensor to initialize</param>
        private async Task InitializeCamera(CameraSensorLocation sensorLocation)
        {
            IReadOnlyList<Windows.Foundation.Size> availablePreviewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(sensorLocation);

            Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(int.MaxValue, int.MaxValue);
            for (int i = 0; i < availablePreviewResolutions.Count; i++)
            {
                double ratio = availablePreviewResolutions[i].Width / availablePreviewResolutions[i].Height;
                if (ratio > 1.32 && ratio < 1.34 && PerfectCamera.DataContext.Instance.CameraRatio == CameraRatio.Ratio_4x3)
                {
                    if (previewResolution.Width > availablePreviewResolutions[i].Width)
                    {
                        previewResolution = availablePreviewResolutions[i];
                    }
                }
                else if (ratio > 1.7 && ratio < 1.8 && PerfectCamera.DataContext.Instance.CameraRatio == CameraRatio.Ratio_16x9)
                {
                    if (previewResolution.Width > availablePreviewResolutions[i].Width)
                    {
                        previewResolution = availablePreviewResolutions[i];
                    }
                }
            }

            PerfectCamera.DataContext.Instance.PreviewResolution = previewResolution;

            IReadOnlyList<Windows.Foundation.Size> availableResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation);

            //find 4:3 (2048 x 1536) or 16:9 (1280x720)
            Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(0, 0);
            for (int i = 0; i < availableResolutions.Count; i++)
            {
                double ratio = availableResolutions[i].Width / availableResolutions[i].Height;
                if (ratio > 1.32 && ratio < 1.34 && PerfectCamera.DataContext.Instance.CameraRatio == CameraRatio.Ratio_4x3)
                {
                    if (captureResolution.Width < availableResolutions[i].Width)
                    {
                        captureResolution = availableResolutions[i];
                    }
                }
                else if (ratio > 1.7 && ratio < 1.8 && PerfectCamera.DataContext.Instance.CameraRatio == CameraRatio.Ratio_16x9)
                {
                    if (captureResolution.Width < availableResolutions[i].Width)
                    {
                        captureResolution = availableResolutions[i];
                    }
                }
            }
            //
            

            PhotoCaptureDevice device = await PhotoCaptureDevice.OpenAsync(sensorLocation, captureResolution);

            await device.SetPreviewResolutionAsync(previewResolution);
            await device.SetCaptureResolutionAsync(captureResolution);

            Camera = device;

            if (PerfectCamera.DataContext.Instance.CameraType == PerfectCameraType.Selfie)
            {
                _cameraEffect = new Effects()
                {
                    PhotoCaptureDevice = Camera
                };

                _cameraStreamSource = new CameraStreamSource(_cameraEffect, previewResolution);
            }

            if (Camera != null)
            {
                if (Camera.SensorLocation == CameraSensorLocation.Front)
                {
                    FlashButton.IsHitTestVisible = false;
                    FlashButton.Opacity = 0.5;
                }
                else
                {
                    FlashButton.IsHitTestVisible = true;
                    FlashButton.Opacity = 1.0;
                }
            }

            SetOrientation(this.Orientation);
        }
        private void UninitializeCamera()
        {
            if (_device != null)
            {
                _device.PreviewFrameAvailable -= PhotoCaptureDevice_PreviewFrameAvailable;

                _device.Dispose();
                _device = null;
            }
        }
        /// <summary>
        /// If camera has not been initialized when navigating to this page, initialization
        /// will be started asynchronously in this method. Once initialization has been
        /// completed the camera will be set as a source to the VideoBrush element
        /// declared in XAML. On-screen controls are enabled when camera has been initialized.
        /// </summary>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Camera != null)
            {
                Camera.Dispose();
                Camera = null;
            }

            ShowProgress(AppResources.InitializingCameraText);
            await InitializeCamera(PerfectCamera.DataContext.Instance.SensorLocation);
            HideProgress();

            InitEffectPanel();

            if (PerfectCamera.DataContext.Instance.CameraType == PerfectCameraType.Selfie)
            {
                _mediaElement = new MediaElement { Stretch = Stretch.UniformToFill, BufferingTime = new TimeSpan(0) };
                _mediaElement.SetSource(_cameraStreamSource);

                BackgroundVideoBrush.SetSource(_mediaElement);

                EffectNameTextBlock.Text = _cameraEffect.EffectName;
                EffectNameFadeIn.Begin();
            }
            else
            {
                BackgroundVideoBrush.SetSource(Camera);
            }

            SetScreenButtonsEnabled(true);
            SetCameraButtonsEnabled(true);
            Storyboard sb = (Storyboard)Resources["CaptureAnimation"];
            sb.Stop();

            SetOrientation(this.Orientation);

            base.OnNavigatedTo(e);
        }
        private async void Initialize()
        {
            StatusTextBlock.Text = AppResources.MainPage_StatusTextBlock_StartingCamera;

            var resolution = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back).Last();

            _photoCaptureDevice = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);

            await _photoCaptureDevice.SetPreviewResolutionAsync(resolution);

            _cameraEffect = new NokiaImagingSDKEffects();
            _cameraEffect.PhotoCaptureDevice = _photoCaptureDevice;

            _cameraStreamSource = new CameraStreamSource(_cameraEffect, resolution);
            _cameraStreamSource.FrameRateChanged += CameraStreamSource_FPSChanged;

            _mediaElement = new MediaElement();
            _mediaElement.Stretch = Stretch.UniformToFill;
            _mediaElement.BufferingTime = new TimeSpan(0);
            _mediaElement.SetSource(_cameraStreamSource);

            // Using VideoBrush in XAML instead of MediaElement, because otherwise
            // CameraStreamSource.CloseMedia() does not seem to be called by the framework:/

            BackgroundVideoBrush.SetSource(_mediaElement);

            _cameraEffect.PreviousEffect();
            StatusTextBlock.Text = _cameraEffect.EffectName;
        }
예제 #59
0
 public UploadURLParameter(PhotoCaptureDevice device)
     : base(device, "upload_url")
 {
 }
예제 #60
0
 protected CameraParameter(PhotoCaptureDevice device, string name)
 {
     _device = device;
     _name = name;
 }