/// <summary> /// Asynchronously autofocuses the photo capture device. /// </summary> private async void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e) { if (!_focusing && !_capturing) { _focusing = true; _device.FocusRegion = null; await _device.FocusAsync(); _focusing = false; if (_capture) { _capture = false; await CaptureAsync(); } } }
public async void set_focus(double focus_val) { 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; }
// Provide touch focus in the viewfinder. async void focus_Tapped(object sender, GestureEventArgs e) { if (cam == null) { return; } Point uiTapPoint = e.GetPosition(viewfinderCanvas); if (PhotoCaptureDevice.IsFocusRegionSupported(cam.SensorLocation)) { Size _focusRegionSize = new Size(100, 100); // Get tap coordinates as a foundation point Windows.Foundation.Point tapPoint = new Windows.Foundation.Point(uiTapPoint.X, uiTapPoint.Y); double xRatio = viewfinderCanvas.ActualHeight / cam.PreviewResolution.Width; double yRatio = viewfinderCanvas.ActualWidth / cam.PreviewResolution.Height; // adjust to center focus on the tap point Windows.Foundation.Point displayOrigin = new Windows.Foundation.Point( tapPoint.Y - _focusRegionSize.Width / 2, (viewfinderCanvas.ActualWidth - tapPoint.X) - _focusRegionSize.Height / 2); // adjust for resolution difference between preview image and the canvas Windows.Foundation.Point viewFinderOrigin = new Windows.Foundation.Point(displayOrigin.X / xRatio, displayOrigin.Y / yRatio); Rect focusrect = new Rect(viewFinderOrigin, _focusRegionSize); // clip to preview resolution Rect viewPortRect = new Rect(0, 0, cam.PreviewResolution.Width, cam.PreviewResolution.Height); focusrect.Intersect(viewPortRect); cam.FocusRegion = focusrect; // show a focus indicator //focusBrackets.SetValue(Shape.StrokeProperty, new SolidColorBrush(Colors.Blue)); focusBrackets.Visibility = Visibility.Visible; focusBrackets.SetValue(Canvas.LeftProperty, uiTapPoint.X - _focusRegionSize.Width / 2); focusBrackets.SetValue(Canvas.TopProperty, uiTapPoint.Y - _focusRegionSize.Height / 2); CameraFocusStatus status = await cam.FocusAsync(); if (status == CameraFocusStatus.Locked) { //focusBrackets.SetValue(Shape.StrokeProperty, new SolidColorBrush(Colors.Green)); cam.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Focus); } else { cam.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None); } } }
private async void OnCameraButtonHalfPress(object sender, EventArgs e) { try { if (m_canTakePicture) { await Camera.FocusAsync(); } } catch (Exception) { } }
/// <summary> /// Starts autofocusing, if supported. Capturing buttons are disabled /// while focusing. /// </summary> private async Task AutoFocus() { if (!_capturing && PhotoCaptureDevice.IsFocusSupported(_photoCaptureDevice.SensorLocation)) { SetScreenButtonsEnabled(false); SetCameraButtonsEnabled(false); await _photoCaptureDevice.FocusAsync(); SetScreenButtonsEnabled(true); SetCameraButtonsEnabled(true); _capturing = false; } }
async public void TakePictures(CameraPreviewSettings settings) { ResetVariables(); _settings = settings; _photoDevice = await InitCamera(_settings, SENSOR_LOCATION); // Init buffer _frameBuffer = new byte[(int)_photoDevice.PreviewResolution.Width * (int)_photoDevice.PreviewResolution.Height * 2]; Debug.WriteLine("Capturing {0} frames...", _settings.Frames); await _photoDevice.FocusAsync(); _photoDevice.PreviewFrameAvailable += OnPreviewFrame; }
private async void Focusing() { while (!stop) { if (PhotoCaptureDevice.IsFocusSupported(sensorLocation)) { await PhotoCaptureDevice.FocusAsync(); } else { System.Threading.Thread.Sleep(200); } } PhotoCaptureDevice.PreviewFrameAvailable -= PreviewFrame; PhotoCaptureDevice.Dispose(); PhotoCaptureDevice = null; }
private async Task FocusAsyncInternal() { if (_inited) { if (!_focusing && PhotoCaptureDevice.IsFocusSupported(_device.SensorLocation)) { _focusing = true; try { await _device.FocusAsync(); } finally { _focusing = false; } } } }
private 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); } }
private async Task <Tuple <ProcessResult, WriteableBitmap> > ProcessFrameAsync(OpticalReaderLib.Frame frame) { //System.Diagnostics.Debug.WriteLine("Start processing"); var rectSize = new Windows.Foundation.Size( ReaderBorder.ActualWidth / Canvas.ActualWidth * frame.Dimensions.Width / _zoom, ReaderBorder.ActualHeight / Canvas.ActualHeight * frame.Dimensions.Height / _zoom); var rectOrigin = new Windows.Foundation.Point( frame.Dimensions.Width / 2 - rectSize.Width / 2, frame.Dimensions.Height / 2 - rectSize.Height / 2); var area = new Windows.Foundation.Rect(rectOrigin, rectSize); ProcessResult result = null; try { result = await OpticalReaderTask.Instance.Processor.ProcessAsync(frame, area, _rotation); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(String.Format("Processing frame failed: {0}\n{1}", ex.Message, ex.StackTrace)); } //System.Diagnostics.Debug.WriteLine("Stop processing"); InterestAreaPolygon.Points = null; if (result != null) { _lastSuccess = DateTime.Now; var thumbnail = GenerateThumbnail(); var interestPointCollection = new PointCollection(); foreach (var point in result.InterestPoints) { interestPointCollection.Add(new System.Windows.Point(point.X, point.Y)); } InterestAreaPolygon.Points = interestPointCollection; return(new Tuple <ProcessResult, WriteableBitmap>(result, thumbnail)); } else { var sinceLastSuccess = DateTime.Now - _lastSuccess; if (sinceLastSuccess > OpticalReaderTask.Instance.FocusInterval) { try { var status = await _device.FocusAsync(); _lastSuccess = DateTime.Now; // todo use camera focus lock status } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(String.Format("Focusing camera failed: {0}\n{1}", ex.Message, ex.StackTrace)); } } return(null); } }
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); } }
private async void VideoCanvasOnTap(object sender, GestureEventArgs e) { try { System.Windows.Point uiTapPoint = e.GetPosition(VideoCanvas); if (PhotoCaptureDevice.IsFocusRegionSupported(PhotoCaptureDevice.SensorLocation) && _focusSemaphore.WaitOne(0)) { // Get tap coordinates as a foundation point var tapPoint = new Windows.Foundation.Point(uiTapPoint.X, uiTapPoint.Y); double xRatio = VideoCanvas.ActualHeight / PhotoCaptureDevice.PreviewResolution.Width; double yRatio = VideoCanvas.ActualWidth / PhotoCaptureDevice.PreviewResolution.Height; // adjust to center focus on the tap point var displayOrigin = new Windows.Foundation.Point( tapPoint.Y - _focusRegionSize.Width / 2, (VideoCanvas.ActualWidth - tapPoint.X) - _focusRegionSize.Height / 2); // adjust for resolution difference between preview image and the canvas var viewFinderOrigin = new Windows.Foundation.Point(displayOrigin.X / xRatio, displayOrigin.Y / yRatio); var focusrect = new Windows.Foundation.Rect(viewFinderOrigin, _focusRegionSize); // clip to preview resolution var viewPortRect = new Windows.Foundation.Rect(0, 0, PhotoCaptureDevice.PreviewResolution.Width, PhotoCaptureDevice.PreviewResolution.Height); focusrect.Intersect(viewPortRect); PhotoCaptureDevice.FocusRegion = focusrect; // show a focus indicator FocusIndicator.SetValue(Shape.StrokeProperty, _notFocusedBrush); FocusIndicator.SetValue(Canvas.LeftProperty, uiTapPoint.X - _focusRegionSize.Width / 2); FocusIndicator.SetValue(Canvas.TopProperty, uiTapPoint.Y - _focusRegionSize.Height / 2); FocusIndicator.SetValue(VisibilityProperty, Visibility.Visible); CameraFocusStatus status = await PhotoCaptureDevice.FocusAsync(); if (status == CameraFocusStatus.Locked) { FocusIndicator.SetValue(Shape.StrokeProperty, _focusedBrush); _manuallyFocused = true; PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Exposure & AutoFocusParameters.Focus & AutoFocusParameters.WhiteBalance); } else { _manuallyFocused = false; PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None); } _focusSemaphore.Release(); } await Capture(); } catch (Exception exception) { Deployment.Current.Dispatcher.BeginInvoke(() => { new CustomMessageDialog( AppMessages.CaptureVideoFailed_Title, String.Format(AppMessages.CaptureVideoFailed, exception.Message), App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); }); } }
private async void TakeSnapShot() { lock (_lockObject) { _cameraInUse = true; TakingPictureText = AppResources.TakingPictureText; } try { CameraCaptureSequence seq = _cameraCaptureDevice.CreateCaptureSequence(1); if (!FrontCamera) { if (FlashOn) { _cameraCaptureDevice.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.On); } else { _cameraCaptureDevice.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off); } } if (SoundOn) { _cameraCaptureDevice.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, true); } else { _cameraCaptureDevice.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, false); } await _cameraCaptureDevice.SetCaptureResolutionAsync(SelectedResolution.CameraResolution); MemoryStream stream = new MemoryStream(); seq.Frames[0].CaptureStream = stream.AsOutputStream(); if (FocusOn) { await _cameraCaptureDevice.FocusAsync(); } await _cameraCaptureDevice.PrepareCaptureSequenceAsync(seq); await seq.StartCaptureAsync(); int countOfPictures = _mediaLibrary.SavedPictures.Count(); //Not sure what this is, but we need it to save to library stream.Seek(0, SeekOrigin.Begin); _mediaLibrary.SavePictureToCameraRoll("spycam" + countOfPictures, stream); stream.Position = 0; var imageSource = new BitmapImage(); imageSource.SetSource(stream); SetCenterXAndCenterY(imageSource); LastPictureTaken = imageSource; } catch (Exception ex) { } lock (_lockObject) { _cameraInUse = false; PictureCount = PictureCount + 1; TakingPictureText = string.Empty; } }
private async Task <Result> GetBarcodeAsync() { await device.FocusAsync(); return(DetectBarcodeAsync()); }