/// <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; }
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 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; } }
/// <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; }
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 } }
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); }
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); }
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; }
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); }
// Gets the configuration of the specified camera private async Task <CameraConfig> GetCameraConfiguration( CameraType cameraType, CameraSensorLocation sensorLocation) { CameraConfig cameraConfig = null; PhotoCaptureDevice photoCaptureDevice = null; FlashState flash = FlashState.Off; List <CameraResolution> resolutions = new List <CameraResolution>(); try { // Read supported resolutions System.Collections.Generic.IReadOnlyList <Windows.Foundation.Size> SupportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation); resolutions = (from resolution in SupportedResolutions select new CameraResolution { Width = resolution.Width, Height = resolution.Height }).ToList(); // Read flash support. // Opening camera is required to read flash, request to open with min resolution var minResolution = SupportedResolutions.OrderBy(size => size.Width).First(); photoCaptureDevice = await PhotoCaptureDevice.OpenAsync(sensorLocation, minResolution); Enum.TryParse <FlashState>( photoCaptureDevice.GetProperty(KnownCameraPhotoProperties.FlashMode).ToString(), true, out flash); // Create the camera config cameraConfig = new CameraConfig { Type = (int)cameraType, Sizes = resolutions, Flash = flash != FlashState.Off ? true : false }; } catch (Exception e) { Logger.Error("Error in Camera get configuration. Reason - " + e.Message); } finally { if (photoCaptureDevice != null) { try { photoCaptureDevice.Dispose(); } catch { } } } return(cameraConfig); }
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 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); }
/// <summary> /// Initializes camera. /// </summary> /// <param name="sensorLocation">Camera sensor to initialize</param> private async Task InitializeCamera(CameraSensorLocation cameraSensorLocation) { Windows.Foundation.Size initialResolution = new Windows.Foundation.Size(Constant.DefaultCameraResolutionWidth, Constant.DefaultCameraResolutionHeight); Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(Constant.DefaultCameraResolutionWidth, Constant.DefaultCameraResolutionHeight); // Find out the largest 4:3 capture resolution available on device IReadOnlyList <Windows.Foundation.Size> availableResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(cameraSensorLocation); 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(cameraSensorLocation, initialResolution); await device.SetCaptureResolutionAsync(captureResolution); await device.SetPreviewResolutionAsync(previewResolution); _photoCaptureDevice = device; IReadOnlyList <object> supportedFlashmodes = PhotoCaptureDevice.GetSupportedPropertyValues(CameraSensorLocation.Back, KnownCameraPhotoProperties.FlashMode); if (supportedFlashmodes.Count > 1) { _photoCaptureDevice.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashMode.Off); } else { TxtBlock_Flash.Visibility = Visibility.Collapsed; } SetOrientation(this.Orientation); }
public static IDictionary <string, Size> GetCameraSize(Size preferredPreviewSize, CameraSensorLocation loc) { IReadOnlyList <Size> captureSizes = PhotoCaptureDevice.GetAvailableCaptureResolutions(loc); Size previewSize = GetPreviewSize(preferredPreviewSize, loc); // The aspect ratios of capture & preview resolutions have to match Size captureSize = captureSizes.Where(x => (x.Width * previewSize.Height == x.Height * previewSize.Width)).First(); Debug.WriteLine("Capture resolution: {0}x{1}", captureSize.Width, captureSize.Height); Debug.WriteLine("Preview resolution: {0}x{1}", previewSize.Width, previewSize.Height); return(new Dictionary <string, Size>() { { "previewSize", previewSize }, { "captureSize", captureSize } }); }
// 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); } }
// Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private async void Application_Launching(object sender, LaunchingEventArgs e) { var captureResolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).Last(); Texture = new Texture(new Uri(@"Assets/Textures/texture1.png", UriKind.Relative), new Uri(@"Assets/Textures/texture1-thumb.jpg", UriKind.Relative)); try { Camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, captureResolution); await Camera.SetPreviewResolutionAsync(captureResolution).AsTask(); } catch (Exception ex) { Console.WriteLine("Error setting camera preview resolution: {0}", e); } }
/// <summary> /// Synchronously initializes the photo capture device for a high resolution photo capture. /// Viewfinder video stream is sent to a VideoBrush element called ViewfinderVideoBrush, and /// device hardware capture key is wired to the CameraButtons_ShutterKeyHalfPressed and /// CameraButtons_ShutterKeyPressed methods. /// </summary> private void InitializeCamera() { Windows.Foundation.Size captureResolution; var deviceName = DeviceStatus.DeviceName; if (deviceName.Contains("RM-875") || deviceName.Contains("RM-876") || deviceName.Contains("RM-877")) { captureResolution = new Windows.Foundation.Size(7712, 4352); // 16:9 //captureResolution = new Windows.Foundation.Size(7136, 5360); // 4:3 } else if (deviceName.Contains("RM-937") || deviceName.Contains("RM-938") || deviceName.Contains("RM-939")) { captureResolution = new Windows.Foundation.Size(5376, 3024); // 16:9 //captureResolution = new Windows.Foundation.Size(4992, 3744); // 4:3 } else { captureResolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(SENSOR_LOCATION).First(); } var task = PhotoCaptureDevice.OpenAsync(SENSOR_LOCATION, captureResolution).AsTask(); task.Wait(); _device = task.Result; _device.SetProperty(KnownCameraGeneralProperties.PlayShutterSoundOnCapture, true); if (_flashButton != null) { SetFlashState(_flashState); } AdaptToOrientation(); ViewfinderVideoBrush.SetSource(_device); if (PhotoCaptureDevice.IsFocusSupported(SENSOR_LOCATION)) { Microsoft.Devices.CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed; } Microsoft.Devices.CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed; }
protected override void PopulateOptions() { IReadOnlyList <Size> cameraResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(Device.SensorLocation); Size currentResolution = Device.CaptureResolution; foreach (Size resolution in cameraResolutions) { string optionName = string.Format("{0}x{1}", resolution.Width, resolution.Height); var option = new ArrayParameterOption <Size>(resolution, optionName); Options.Add(option); if (resolution == currentResolution) { SelectedOption = option; } } }
/// <summary> /// Reads supported capture resolutions from Parameter.Device and populates /// ArrayParameter.Options accordingly. Sets the SelectedOption as well. /// </summary> protected override void PopulateOptions() { IReadOnlyList <Windows.Foundation.Size> supportedValues = PhotoCaptureDevice.GetAvailableCaptureResolutions(Device.SensorLocation); Windows.Foundation.Size value = Device.CaptureResolution; ArrayParameterOption option = null; foreach (Windows.Foundation.Size i in supportedValues) { option = new ArrayParameterOption(i, i.Width + " x " + i.Height); Options.Add(option); if (i.Equals(value)) { SelectedOption = option; } } }
/// <summary> /// Reads supported capture resolutions from Parameter.Device and populates /// ArrayParameter.Options accordingly. Sets the SelectedOption as well. /// </summary> protected override void PopulateOptions() { IReadOnlyList <Windows.Foundation.Size> supportedValues = PhotoCaptureDevice.GetAvailableCaptureResolutions(Device.SensorLocation); Windows.Foundation.Size value = Device.CaptureResolution; ArrayParameterOption option = null; foreach (Windows.Foundation.Size i in supportedValues) { option = new ArrayParameterOption(i, i.Width + " x " + i.Height); Options.Add(option); if (i.Equals(value)) { SelectedOption = option; } } // The phone does support these resolutions, though it isn't given by the above? Aha: // http://developer.nokia.com/resources/library/Lumia/imaging/working-with-high-resolution-photos/capturing-high-resolution-photos.html var deviceName = DeviceStatus.DeviceName; if (deviceName.Contains("RM-875") || deviceName.Contains("RM-876") || deviceName.Contains("RM-877")) { Windows.Foundation.Size[] unofficialValues = { new Windows.Foundation.Size(7712, 4352), new Windows.Foundation.Size(7136, 5360) }; foreach (Windows.Foundation.Size i in unofficialValues) { option = new ArrayParameterOption(i, i.Width + " x " + i.Height); Options.Add(option); if (i.Equals(value)) { SelectedOption = option; } } } }
/// <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(DefaultCameraResolutionWidth, DefaultCameraResolutionHeight); Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(DefaultCameraResolutionWidth, DefaultCameraResolutionHeight); // 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 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; }
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(); }
public IReadOnlyList <Size> GetAvailablePhotoCaptureResolutions(CameraSensorLocation cameraSensorLocation) { return(PhotoCaptureDevice.GetAvailableCaptureResolutions(cameraSensorLocation)); }
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); } }
//Code for initialization, capture completed, image availability events; also setting the source for the viewfinder. protected async override void OnNavigatedTo(NavigationEventArgs e) //当页面变为框架中的活动页面时调用。 { var resolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back); resolution = resolutions.Aggregate((x, y) => x.Height * x.Width < y.Height * y.Width ? x : y); resolutionsListBox.ItemsSource = resolutions; EndpointAddress address; if (App.LocalAddress.StartsWith("192.168")) { address = new EndpointAddress("http://192.168.173.1:8000/phone"); } else { address = new EndpointAddress("http://desk.gqqnbig.me:8000/phone"); } factory = new ChannelFactory <IPhoneService>(new BasicHttpBinding(), address); //factory.Opened += factory_Opened; phoneService = factory.CreateChannel(address); imageSeqeuenceNumber = 0; if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back)) { cam = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution); phoneService.BeginStartSession(DateTime.UtcNow.GetUnixTimestamp() - App.TimeDifference, (int)resolution.Width, (int)resolution.Height, StartSessionCompleted, 0); cam.SetProperty(KnownCameraPhotoProperties.FlashMode, FlashState.Off); //cam.SetProperty(KnownCameraPhotoProperties.SceneMode, CameraSceneMode.Landscape); cam.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Infinity); cam.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Focus); await cam.SetPreviewResolutionAsync(resolution); viewfinderBrush.SetSource(cam); //CameraButtons.ShutterKeyPressed += ShutterButton_Click; } else { MessageBox.Show("Camera is not available. Exiting..."); Application.Current.Terminate(); return; } //var videoCaptureDevice = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First()); //videoCaptureDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On); //videoCaptureDevice.sta PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled; //timer = new DispatcherTimer(); //timer.Interval = TimeSpan.FromSeconds(0.2); //timer.Tick += (sender, e1) => //{ // ShutterButton_Click(null, null); //}; //timer.Start(); }