/// <summary>
        /// Gets the current orientation of the UI in relation to the device and applies a corrective rotation to the preview
        /// </summary>
        private async Task SetPreviewRotationAsync(IMediaEncodingProperties props)
        {
            // Only need to update the orientation if the camera is mounted on the device.
            if (mediaCapture == null)
            {
                return;
            }

            // Calculate which way and how far to rotate the preview.
            int           rotationDegrees;
            VideoRotation sourceRotation;

            CalculatePreviewRotation(out sourceRotation, out rotationDegrees);

            // Set preview rotation in the preview source.
            mediaCapture.SetPreviewRotation(sourceRotation);

            // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
            //var props = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
            props.Properties.Add(RotationKey, rotationDegrees);
            await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, props);

            var currentPreviewResolution = GetPreviewResolution(props);

            // Setup a frame to use as the input settings
            videoFrame = new VideoFrame(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, (int)currentPreviewResolution.Width, (int)currentPreviewResolution.Height);
        }
Пример #2
0
        private async Task StartPreviewAsync()
        {
            try
            {
                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync();

                displayRequest.RequestActive();

                if ("Windows.Mobile" == AnalyticsInfo.VersionInfo.DeviceFamily)
                {
                    mediaCapture.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
                }

                //DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
            }
            catch (UnauthorizedAccessException)
            {
                // This will be thrown if the user denied access to the camera in privacy settings
                //ShowMessageToUser("The app was denied access to the camera");
                return;
            }

            try
            {
                PreviewControl.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();

                isPreviewing = true;
            }
            catch (System.IO.FileLoadException)
            {
                mediaCapture.CaptureDeviceExclusiveControlStatusChanged += _mediaCapture_CaptureDeviceExclusiveControlStatusChanged;
            }
        }
Пример #3
0
        /// <summary>
        /// Initialze MediaCapture
        /// </summary>
        /// <param name="panel"></param>
        /// <returns></returns>
        public async Task InitializeCapture(Windows.Devices.Enumeration.Panel panel = Windows.Devices.Enumeration.Panel.Back)
        {
            mediaCapture      = new MediaCapture();
            this.currentPanel = panel;
            MediaCaptureInitializationSettings setting = await InitializeSettings(panel);

            if (setting != null)
            {
                await mediaCapture.InitializeAsync(setting);
            }
            else
            {
                await mediaCapture.InitializeAsync();
            }
            var resolutions = this.mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

            if (resolutions.Count >= 1)
            {
                var hires = resolutions.OrderByDescending(item => ((VideoEncodingProperties)item).Width).First();
                await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, hires);
            }
            if (!this.isExternalCamera)
            {
                var previewRotation = (this.currentPanel == Windows.Devices.Enumeration.Panel.Back) ? VideoRotation.Clockwise90Degrees : VideoRotation.Clockwise270Degrees;
                try
                {
                    mediaCapture.SetPreviewRotation(previewRotation);
                    mediaCapture.SetRecordRotation(previewRotation);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }
        }
Пример #4
0
        public async Task <MediaCapture> Initialize()
        {
            var cameraDeviceInfos = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)).Where(d => d.IsEnabled && d.EnclosureLocation != null);

            var frontCamDeviceInfo = cameraDeviceInfos.FirstOrDefault(d => d.EnclosureLocation.Panel == Panel.Front);

            var mediaCaptureInitialization = new MediaCaptureInitializationSettings
            {
                PhotoCaptureSource = PhotoCaptureSource.Photo,
                AudioDeviceId      = string.Empty,
                VideoDeviceId      = frontCamDeviceInfo.Id,
            };

            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync(mediaCaptureInitialization);

            mediaCapture.VideoDeviceController.PrimaryUse = CaptureUse.Photo;

            mediaCapture.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
            mediaCapture.SetRecordRotation(VideoRotation.Clockwise270Degrees);

            // Create photo encoding properties as JPEG and set the size that should be used for photo capturing
            imgEncodingProperties        = ImageEncodingProperties.CreateJpeg();
            imgEncodingProperties.Height = 480;
            imgEncodingProperties.Width  = 640;


            return(mediaCapture);
        }
Пример #5
0
 private void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
 {
     if (_mediaCapture != null)
     {
         var newRotation = VideoRotationUtilities.FromDisplayOrientation(sender.CurrentOrientation, IsMirroredPreview());
         _mediaCapture.SetPreviewRotation(newRotation);
     }
 }
Пример #6
0
        private async Task StartPreview()
        {
            captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            previewElement.Source = captureManager;
            await captureManager.StartPreviewAsync();

            isPreviewing = true;
        }
 private void DisplayInfo_OrientationChanged(DisplayInformation sender, object args)
 {
     if (mediaCapture != null)
     {
         rotation = VideoRotationLookup(sender.CurrentOrientation, false);
         mediaCapture.SetPreviewRotation(rotation);
         mediaCapture.SetRecordRotation(rotation);
     }
 }
Пример #8
0
        public async Task InitializeCameraAsync()
        {
            try
            {
                if (_mediaCapture == null)
                {
                    _mediaCapture         = new MediaCapture();
                    _mediaCapture.Failed += MediaCapture_Failed;

                    _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (_cameraDevices == null || !_cameraDevices.Any())
                    {
                        throw new NotSupportedException();
                    }

                    var device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);

                    var cameraId = device?.Id ?? _cameraDevices.First().Id;

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (Panel == Panel.Back)
                    {
                        _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = true;
                    }

                    IsInitialized = true;
                    CanSwitch     = _cameraDevices?.Count > 1;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
            catch (UnauthorizedAccessException)
            {
                errorMessage.Text = "Camera_Exception_UnauthorizedAccess".GetLocalized();
            }
            catch (NotSupportedException)
            {
                errorMessage.Text = "Camera_Exception_NotSupported".GetLocalized();
            }
            catch (TaskCanceledException)
            {
                errorMessage.Text = "Camera_Exception_InitializationCanceled".GetLocalized();
            }
            catch (Exception)
            {
                errorMessage.Text = "Camera_Exception_InitializationError".GetLocalized();
            }
        }
Пример #9
0
        void OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
        {
            if (_captureManager == null)
            {
                return;
            }

            var orientation = args.Orientation;

            if (orientation == SimpleOrientation.Rotated90DegreesCounterclockwise ||
                orientation == SimpleOrientation.Rotated270DegreesCounterclockwise)
            {
                _captureManager.SetPreviewRotation(VideoRotation.None);
            }
            else
            {
                _captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            }
        }
Пример #10
0
        async Task StartPreview()
        {
            if (String.Equals(Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily, "Windows.Mobile"))
            {
                mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                mediaCapture.SetPreviewMirroring(true);
            }

            var focusControl = mediaCapture.VideoDeviceController.FocusControl;

            if (!focusControl.FocusChangedSupported)
            {
                if (focusControl.Supported)
                {
                    _cleanedUp   = false;
                    _processScan = true;

                    VideoCaptureElement.Source  = mediaCapture;
                    VideoCaptureElement.Stretch = Stretch.UniformToFill;
                    await mediaCapture.StartPreviewAsync();

                    await focusControl.UnlockAsync();

                    focusControl.Configure(new FocusSettings {
                        Mode = FocusMode.Auto
                    });
                    timerFocus.Tick    += timerFocus_Tick;
                    timerFocus.Interval = new TimeSpan(0, 0, 3);
                    timerFocus.Start();
                }
                else
                {
                    OnErrorAsync(new Exception("AutoFocus control is not supported on this device"));
                }
            }
            else
            {
                _cleanedUp   = false;
                _processScan = true;

                mediaCapture.FocusChanged  += mediaCaptureManager_FocusChanged;
                VideoCaptureElement.Source  = mediaCapture;
                VideoCaptureElement.Stretch = Stretch.UniformToFill;
                await mediaCapture.StartPreviewAsync();

                await focusControl.UnlockAsync();

                var settings = new FocusSettings {
                    Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                };
                focusControl.Configure(settings);
                await focusControl.FocusAsync();
            }
        }
Пример #11
0
        private async Task InitializeMediaCaptureAsync(string id)
        {
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings()
            {
                VideoDeviceId = id
            });

            var initialRotation = VideoRotationUtilities.FromDisplayOrientation(_displayInformation.CurrentOrientation, IsMirroredPreview());

            _mediaCapture.SetPreviewRotation(initialRotation);
        }
        private void DisplayInfo_OrientationChanged(DisplayInformation sender, object args)
        {
            if (_mediaCapture == null)
            {
                return;
            }

            _mediaCapture.SetPreviewRotation(_cam
                    ? VideoRotationLookup(sender.CurrentOrientation, true)
                    : VideoRotationLookup(sender.CurrentOrientation, false));
            var rotation = VideoRotationLookup(sender.CurrentOrientation, false);

            _mediaCapture.SetRecordRotation(rotation);
        }
Пример #13
0
        /// <summary>
        /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
        /// </summary>
        /// <returns>Task</returns>
        private async Task InitializeCameraAsync()
        {
            if (_mediaCapture == null)
            {
                _mediaCapture         = new MediaCapture();
                _mediaCapture.Failed += MediaCapture_Failed;

                _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                if (_cameraDevices == null)
                {
                    throw new NotSupportedException();
                }

                try
                {
                    var device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);

                    var cameraId = device != null ? device.Id : _cameraDevices.First().Id;

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (Panel == Panel.Back)
                    {
                        _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = true;
                    }

                    IsInitialized = true;
                }
                catch (UnauthorizedAccessException ex)
                {
                    throw ex;
                }

                if (IsInitialized)
                {
                    CanSwitch             = _cameraDevices?.Count > 1;
                    PreviewControl.Source = _mediaCapture;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
        }
Пример #14
0
        async void camera()
        {
            Windows.Media.Capture.MediaCapture captureManager;

            captureManager = new MediaCapture();        //Define MediaCapture object

            await captureManager.InitializeAsync();     //Initialize MediaCapture and

            captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            capturePreview.Source = captureManager;     //Start preiving on CaptureElement
            await captureManager.StartPreviewAsync();   //Start camera capturing

            SimpleOrientationSensor sensor = SimpleOrientationSensor.GetDefault();

            sensor.OrientationChanged += (s, arg) =>
            {
                switch (arg.Orientation)
                {
                case SimpleOrientation.Rotated90DegreesCounterclockwise:
                    captureManager.SetPreviewRotation(VideoRotation.None);
                    break;

                case SimpleOrientation.Rotated180DegreesCounterclockwise:
                case SimpleOrientation.Rotated270DegreesCounterclockwise:
                    captureManager.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
                    break;

                default:
                    captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                    break;
                }
            };


            captureManager = null;
        }
Пример #15
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var myArgs = (ImageCapturePageArguments)e.Parameter;

            _project     = myArgs.Project;
            _targetFrame = myArgs.TargetFrame;
            await _mediaCapture.InitializeAsync();

            _imageCapture.Source = _mediaCapture;
            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
            await _mediaCapture.StartPreviewAsync();

            HardwareButtons.BackPressed += (sender, args) => Frame.Navigate(typeof(FramingPage), _project);
        }
Пример #16
0
        private async void InitVideoCapture()
        {
            ///摄像头的检测
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                System.Diagnostics.Debug.WriteLine("No camera device found!");
                return;
            }
            var settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                MediaCategory        = MediaCategory.Other,
                AudioProcessing      = AudioProcessing.Default,
                VideoDeviceId        = cameraDevice.Id
            };

            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync(settings);

            _mediaCapture.SetPreviewRotation(VideoRotation.None);
            VideoCapture.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
            //props.Properties.Add(RotationKey, 90);

            await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported)
            {
                await focusControl.UnlockAsync();

                var setting = new FocusSettings {
                    Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                };
                focusControl.Configure(setting);
                await focusControl.FocusAsync();
            }

            _isPreviewing = true;
            _isInitVideo  = true;
            InitVideoTimer();
        }
        public async void StartCamera()
        {
            var cameraId = await GetCameraId(Windows.Devices.Enumeration.Panel.Back);

            _captureManager = new MediaCapture();
            await _captureManager.InitializeAsync(new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource   = PhotoCaptureSource.Photo,
                AudioDeviceId        = string.Empty,
                VideoDeviceId        = cameraId.Id
            });

            cePreview.Source = _captureManager;
            _captureManager.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
            _captureActive = true;
            await _captureManager.StartPreviewAsync();
        }
Пример #18
0
        private async void InitializeCamera()
        {
            var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var rearCamera = videoDevices.First(item => item.EnclosureLocation != null &&
                                                item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            _captureManager = new MediaCapture();

            await _captureManager.InitializeAsync(new MediaCaptureInitializationSettings
            {
                VideoDeviceId = rearCamera.Id
            });

            _captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            capturePreview.Source = _captureManager;
            await _captureManager.StartPreviewAsync();
        }
Пример #19
0
        private async Task InitializeCameraAsync()
        {
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                AudioDeviceId        = string.Empty
            };

            // 检测摄像头,优先后置摄像头
            var allVedioDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var desiredDevice = allVedioDevices.FirstOrDefault(d => d.EnclosureLocation != null && d.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (desiredDevice != null)
            {
                settings.VideoDeviceId = desiredDevice.Id;
            }
            await _mediaCapture.InitializeAsync(settings);

            qrCode.Source = _mediaCapture;
            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            // 设置2倍焦距
            //_mediaCapture.VideoDeviceController.ZoomControl.Value = 2f;
            if (_mediaCapture.VideoDeviceController.FocusControl.Supported && _mediaCapture.VideoDeviceController.FocusControl.WaitForFocusSupported)
            {
                // 设置自动对焦
                _mediaCapture.VideoDeviceController.FocusControl.Configure(new FocusSettings()
                {
                    Mode = FocusMode.Continuous
                });
            }

            await _mediaCapture.StartPreviewAsync();

            if (_mediaCapture.VideoDeviceController.FocusControl.Supported && _mediaCapture.VideoDeviceController.FocusControl.WaitForFocusSupported)
            {
                // 对焦
                await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
            }

            _cameraInitialized = true;
        }
Пример #20
0
        public CapturePreview(MediaCapture capture, VideoRotation rotation = VideoRotation.None)
        {
            capture.SetPreviewRotation(rotation);
            var props = (VideoEncodingProperties)capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            if (rotation == VideoRotation.None || rotation == VideoRotation.Clockwise180Degrees)
            {
                m_width  = props.Width;
                m_height = props.Height;
            }
            else
            {
                m_width  = props.Height;
                m_height = props.Width;
            }

            m_preview = new CapturePreviewNative(this, m_width, m_height);
            m_capture = capture;
        }
Пример #21
0
        /// <summary>
        /// initializes the preview with our desired settings
        /// </summary>
        private async void InitializePreview()
        {
            _captureManager = new MediaCapture();

            var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);

            await _captureManager.InitializeAsync(new MediaCaptureInitializationSettings {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource   = PhotoCaptureSource.Photo,
                AudioDeviceId        = string.Empty,
                VideoDeviceId        = cameraID.Id,
            });

            await _captureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, MaxResolution());

            _captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            StartPreview();
        }
Пример #22
0
        private async void InitializePreview()
        {
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                Debug.WriteLine("No camera device found!");
                return;
            }
            capturePhotoManager = new MediaCapture();
            var settings = new MediaCaptureInitializationSettings {
                VideoDeviceId = cameraDevice.Id
            };
            await capturePhotoManager.InitializeAsync(settings);

            capturePhotoManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            PhotoPreview.Source = null;
            TakenImage.Source   = null;
            StartPreview();
        }
Пример #23
0
        public async Task <MediaCapture> Initialize(CaptureUse primaryUse = CaptureUse.Photo)
        {
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            mediaCapture = new MediaCapture();
            if (devices.Count() > 0)
            {
                await this.mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = devices.ElementAt(1).Id, PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.VideoPreview });
            }
            mediaCapture.VideoDeviceController.PrimaryUse = primaryUse;
            mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            imgEncodingProperties        = ImageEncodingProperties.CreateJpeg();
            imgEncodingProperties.Width  = 640;
            imgEncodingProperties.Height = 480;

            videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);

            return(mediaCapture);
        }
Пример #24
0
        async private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var CameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);

            await captureMgr.InitializeAsync(new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource   = PhotoCaptureSource.Photo,
                AudioDeviceId        = string.Empty,
                VideoDeviceId        = CameraID.Id
            });

            captureMgr.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            CapturePreview.Source = captureMgr;
            CapturePreview.Height = ContentRoot.Height;

            var maxResolution = captureMgr.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) => (i1 as VideoEncodingProperties).Width > (i2 as VideoEncodingProperties).Width ? i1 : i2);
            await captureMgr.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);

            await captureMgr.StartPreviewAsync();
        }
        async void CaptureAndRotate(MediaCapture captureMgrReal)
        {
            // <SnippetCaptureRotateAll>
            // <SnippetCaptureRotateInit>
            MediaCapture captureMgr = new MediaCapture();

            // Set the MediaCapture to a variable in App.xaml.cs to handle suspension.
            (App.Current as App).MediaCapture = captureMgr;

            await captureMgr.InitializeAsync();

            // </SnippetCaptureRotateInit>

            // <SnippetCaptureRotateSetRotate>
            captureMgr.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            // </SnippetCaptureRotateSetRotate>

            // <SnippetCaptureRotateGetRotate>
            VideoRotation previewRotation = captureMgr.GetPreviewRotation();

            // </SnippetCaptureRotateGetRotate>

            // Start capture preview.
            // capturePreview is a CaptureElement defined in XAML.
            capturePreview.Source = captureMgr;

            // Set the CaptureElement to a variable in App.xaml.cs to handle suspension.
            (App.Current as App).PreviewElement = capturePreview;

            // Lock the orientation of the display while previewing.
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

            await captureMgr.StartPreviewAsync();

            // Set a tracking variable for preview state in App.xaml.cs
            (App.Current as App).IsPreviewing = true;
            // </SnippetCaptureRotateAll>
        }
Пример #26
0
        /// <summary>
        /// Gets the current orientation of the UI in relation to the device and applies a corrective rotation to the preview.
        /// </summary>
        private async Task SetPreviewRotationAsync()
        {
            // Only need to update the orientation if the camera is mounted on the device.
            if (externalCamera)
            {
                return;
            }

            // Calculate which way and how far to rotate the preview.
            int           rotationDegrees;
            VideoRotation sourceRotation;

            CalculatePreviewRotation(out sourceRotation, out rotationDegrees);

            // Set preview rotation in the preview source.
            mediaCapture.SetPreviewRotation(sourceRotation);

            // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
            var props = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            props.Properties.Add(RotationKey, rotationDegrees);
            await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
        }
Пример #27
0
        private async void InitVideoCapture()
        {
            ///摄像头的检测
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                await new MessageDialog("没有找到摄像头!").ShowAsync();
                Debug.WriteLine("No camera device found!");
                return;
            }


            var settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                MediaCategory        = MediaCategory.Other,
                AudioProcessing      = Windows.Media.AudioProcessing.Default,
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                VideoDeviceId        = cameraDevice.Id
            };
            await _mediaCapture.InitializeAsync(settings);

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported)
            {
                var focusSettings = new FocusSettings()
                {
                    Mode = focusControl.SupportedFocusModes.FirstOrDefault(f => f == FocusMode.Continuous),
                    DisableDriverFallback = true,
                    AutoFocusRange        = focusControl.SupportedFocusRanges.FirstOrDefault(f => f == AutoFocusRange.FullRange),
                    Distance = focusControl.SupportedFocusDistances.FirstOrDefault(f => f == ManualFocusDistance.Nearest)
                };

                //设置聚焦,最好使用FocusMode.Continuous,否则影响截图会很模糊,不利于识别
                focusControl.Configure(focusSettings);
            }
            if (!SettingHelper.IsPc())
            {
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            }


            VideoCapture.Source        = _mediaCapture;
            VideoCapture.FlowDirection = FlowDirection.LeftToRight;
            await _mediaCapture.StartPreviewAsync();

            //SimpleOrientationSensor sensor = SimpleOrientationSensor.GetDefault();
            //sensor.OrientationChanged += (s, arg) =>
            //{
            //    switch (arg.Orientation)
            //    {
            //        case SimpleOrientation.Rotated90DegreesCounterclockwise:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.None);
            //            break;
            //        case SimpleOrientation.Rotated180DegreesCounterclockwise:
            //        case SimpleOrientation.Rotated270DegreesCounterclockwise:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
            //            break;
            //        default:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            //            break;
            //    }
            //};

            try
            {
                if (_mediaCapture.VideoDeviceController.FlashControl.Supported)
                {
                    //关闭闪光灯
                    _mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
                }
            }
            catch
            {
            }

            if (focusControl.Supported)
            {
                //开始聚焦
                await focusControl.FocusAsync();
            }


            //var angle = CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper.GetUIOrientation());
            // var transform = new RotateTransform { Angle = 90 };
            // VideoCapture.RenderTransform = transform;
        }
Пример #28
0
        public async Task StartStreamAsync(bool isForRealTimeProcessing = false, DeviceInformation desiredCamera = null)
        {
            try
            {
                if (captureManager == null ||
                    captureManager.CameraStreamState == CameraStreamState.Shutdown ||
                    captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    loadingOverlay.Visibility = Visibility.Visible;

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

                    captureManager = new MediaCapture();

                    MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
                    var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    var selectedCamera = allCameras.FirstOrDefault(c => c.Name == SettingsHelper.Instance.CameraName);
                    if (desiredCamera != null)
                    {
                        selectedCamera = desiredCamera;
                    }
                    else if (lastUsedCamera != null)
                    {
                        selectedCamera = lastUsedCamera;
                    }

                    if (selectedCamera != null)
                    {
                        settings.VideoDeviceId = selectedCamera.Id;
                        lastUsedCamera         = selectedCamera;
                    }

                    cameraSwitchButton.Visibility = allCameras.Count > 1 ? Visibility.Visible : Visibility.Collapsed;

                    await captureManager.InitializeAsync(settings);

                    await SetVideoEncodingToHighestResolution(isForRealTimeProcessing);

                    isStreamingOnRealtimeResolution = isForRealTimeProcessing;

                    //rotate the camera
                    captureManager.SetPreviewRotation(SettingsHelper.Instance.CameraRotation);

                    this.webCamCaptureElement.Source = captureManager;
                }

                if (captureManager.CameraStreamState == CameraStreamState.NotStreaming)
                {
                    if (PerformFaceTracking || CameraFrameProcessor != null)
                    {
                        if (this.faceTracker == null)
                        {
                            this.faceTracker = await FaceTracker.CreateAsync();
                        }

                        if (this.frameProcessingTimer != null)
                        {
                            this.frameProcessingTimer.Cancel();
                            frameProcessingSemaphore.Release();
                        }
                        TimeSpan timerInterval = TimeSpan.FromMilliseconds(66); //15fps
                        this.frameProcessingTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);
                    }

                    this.videoProperties = this.captureManager.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
                    await captureManager.StartPreviewAsync();

                    this.webCamCaptureElement.Visibility = Visibility.Visible;

                    loadingOverlay.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Error starting the camera.");
            }
        }
Пример #29
0
        private async Task InitializeQrCode()
        {
            string error = null;

            try
            {
                //if (_mediaCapture == null)
                //{
                // Find all available webcams
                DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


                // Get the proper webcam (default one)
                DeviceInformation backWebcam = (from webcam in webcamList where webcam.IsEnabled select webcam).FirstOrDefault();


                // Initializing MediaCapture


                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    VideoDeviceId        = backWebcam.Id,
                    AudioDeviceId        = "",
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
                });


                // Adjust camera rotation for Phone
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);


                // Set the source of CaptureElement to MediaCapture
                captureElement.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();


                // _mediaCapture.FocusChanged += _mediaCapture_FocusChanged; // ToDo:


                // Seetting Focus & Flash(if Needed)


                var torch = _mediaCapture.VideoDeviceController.TorchControl;
                if (torch.Supported)
                {
                    torch.Enabled = true;
                }


                await _mediaCapture.VideoDeviceController.FocusControl.UnlockAsync();

                var focusSettings = new FocusSettings();
                focusSettings.AutoFocusRange        = AutoFocusRange.FullRange;
                focusSettings.Mode                  = FocusMode.Continuous;
                focusSettings.WaitForFocus          = true;
                focusSettings.DisableDriverFallback = false;
                _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();


                //}
            }
            catch (Exception ex)
            {
                dialog = new MessageDialog("Error: " + ex.Message);
                dialog.ShowAsync();
            }
        }
Пример #30
0
 public void SetPreviewOrientation(PreviewOrientation orientation)
 {
     _mediaCapture.SetPreviewRotation(ConvertOrientationToRotation(orientation));
 }