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(); }
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); }
// Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { var resolution = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back).Last(); var task = PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution).AsTask(); task.Wait(); Camera = task.Result; Camera.SetPreviewResolutionAsync(resolution).AsTask().Wait(); }
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 Size GetBestPreviewResolution(CameraSensorLocation sensorLocation) { var previewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(sensorLocation); var result = new Size(640, 480); foreach (var previewResolution in previewResolutions) { if (previewResolution.Width * previewResolution.Height > result.Width * result.Height) { result = previewResolution; } } return(result); }
private async Task <Size> GetBestCaptureResolution(CameraSensorLocation sensorLocation, Size previewResolution) { // The last size in the AvailableCaptureResolutions is the lowest available var captureResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation); var previewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(sensorLocation); Size resolution = await Task.Factory.StartNew(() => captureResolutions.LastOrDefault( c => (c.Width > 1000.0 || c.Height > 1000.0) && (c.Width / c.Height).Equals(previewResolution.Width / previewResolution.Height))); if (resolution == default(Size)) { return(previewResolution); } return(resolution); }
private static Size GetPreviewSize(Size preferredSize, CameraSensorLocation loc) { IReadOnlyList <Size> previewSizes = PhotoCaptureDevice.GetAvailablePreviewResolutions(loc); Size selectedSize = Windows.Foundation.Size.Empty; foreach (Size size in previewSizes) { if (size.Equals(preferredSize)) { selectedSize = size; break; } } return(selectedSize.IsEmpty ? previewSizes[0] : selectedSize); }
// Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private async void Application_Activated(object sender, ActivatedEventArgs e) { var captureResolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).Last(); Camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, captureResolution); var previewResolution = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back).Last(); try { await Camera.SetPreviewResolutionAsync(previewResolution); } catch (Exception ex) { Console.WriteLine("Error setting camera preview resolution: {0}", e); } }
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); } }
public async Task InitAsync() { ThrowIfDisposed(); try { if (_inited) { throw new InvalidOperationException("already inited"); } // choose front or back CameraSensorLocation cameraLocation; if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back)) { var supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back); _initRes = GetBestResolution(supportedResolutions); cameraLocation = CameraSensorLocation.Back; } else if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front)) { var supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front); _initRes = GetBestResolution(supportedResolutions); cameraLocation = CameraSensorLocation.Front; } else { throw new CriticalCameraNotSupportedException(); } // open camera _device = await PhotoCaptureDevice.OpenAsync(cameraLocation, _initRes); #region retry when failed hack if (_device == null) { try { await Task.Delay(200); _device = await PhotoCaptureDevice.OpenAsync(cameraLocation, _initRes); } catch { } if (_device == null) { await Task.Delay(500); _device = await PhotoCaptureDevice.OpenAsync(cameraLocation, _initRes); } } #endregion // retry when failed ThrowIfDisposed(); // set flash mode, focus range... SetDeviceProperties(cameraLocation); var list = PhotoCaptureDevice.GetAvailablePreviewResolutions(cameraLocation); Windows.Foundation.Size resPreview = GetBestPreviewResolution(list, _initRes); await _device.SetPreviewResolutionAsync(resPreview); ThrowIfDisposed(); _previewSize = resPreview; // init auto focus timer OnAutoFocusPropertyChanged(); // init barcode reader OnAutoDetectBarcodePropertyChanged(); // init frame report and barcode detect timer StartFrameTimer(); _inited = true; } catch (ObjectDisposedException) { Dispose(); throw new CardCaptureDeviceDisposedException(); } catch (CriticalCameraNotSupportedException notSupportEx) { ThrowExceptionOrDisposed(notSupportEx, true); } catch { ThrowExceptionOrDisposed(new InitCameraFailedException(), true); } ThrowIfDisposed(); }