public void NullSource () { VideoBrush vb = new VideoBrush (); Assert.Throws<NullReferenceException> (delegate { vb.SetSource ((MediaElement) null); }, "MediaElement"); Assert.Throws<NullReferenceException> (delegate { vb.SetSource ((CaptureSource) null); }, "CaptureSource"); }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); // Delayed due to Camera init bug in WP71 SDK Beta 2 // See http://forums.create.msdn.com/forums/p/85830/516843.aspx Dispatcher.BeginInvoke(() => { // Initialize the webcam photoCamera = new PhotoCamera(); photoCamera.Initialized += PhotoCameraInitialized; CameraButtons.ShutterKeyHalfPressed += PhotoCameraButtonHalfPress; isInitialized = false; isDetecting = false; // Fill the Viewport Rectangle with the VideoBrush var vidBrush = new VideoBrush(); vidBrush.SetSource(photoCamera); Viewport.Fill = vidBrush; // Start timer dispatcherTimer = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(50)}; dispatcherTimer.Tick += (sender, e1) => Detect(); dispatcherTimer.Start(); }); }
void Load() { if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) { var devices = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices(); foreach (var device in devices) { var videoItem = new VideoItem(); videoItem.Name = device.FriendlyName; var source = new CaptureSource(); source.VideoCaptureDevice = device; var videoBrush = new VideoBrush(); videoBrush.SetSource(source); videoItem.Brush = videoBrush; this.sources.Add(source); this.sourceItems.Add(videoItem); } this.videoItems.ItemsSource = this.sourceItems; this.StartAll(); } }
public void StartWebCam() { _captureSource = new CaptureSource(); _captureSource.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(_captureSource_CaptureImageCompleted); _captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); try { // Start capturing if (_captureSource.State != CaptureState.Started) { // Create video brush and fill the WebcamVideo rectangle with it var vidBrush = new VideoBrush(); vidBrush.Stretch = Stretch.Uniform; vidBrush.SetSource(_captureSource); WebcamVideo.Fill = vidBrush; // Ask user for permission and start the capturing if (CaptureDeviceConfiguration.RequestDeviceAccess()) { _captureSource.Start(); } } } catch (InvalidOperationException) { InfoTextBox.Text = "Web Cam already started - if not, I can't find it..."; } catch (Exception) { InfoTextBox.Text = "Could not start web cam, do you have one?"; } }
void MainPage_Loaded(object sender, RoutedEventArgs e) { captureSource = new CaptureSource { VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice() }; var videoBrush = new VideoBrush(); videoBrush.SetSource(captureSource); Viewport.Fill = videoBrush; markerDetector = new CaptureSourceMarkerDetector(); var marker = Marker.LoadFromResource("Bola.pat", 64, 64, 80); markerDetector.Initialize(captureSource, 1d, 4000d, marker); markerDetector.MarkersDetected += (obj, args) => { Dispatcher.BeginInvoke(() => { var results = args.DetectionResults; if (results.HasResults) { var centerAtOrigin = Matrix3DFactory. CreateTranslation( -Imagem.ActualWidth* 0.5, -Imagem. ActualHeight* 0.5, 0); var scale = Matrix3DFactory.CreateScale (0.5, -0.5, 0.5); var world = centerAtOrigin* scale* results[0]. Transformation; var vp = Matrix3DFactory. CreateViewportTransformation (Viewport.ActualWidth, Viewport.ActualHeight); var m = Matrix3DFactory. CreateViewportProjection (world, Matrix3D.Identity, markerDetector. Projection, vp); Imagem.Projection = new Matrix3DProjection {ProjectionMatrix = m}; } }); }; }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { // Initialize the webcam captureSource = new CaptureSource(); captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // Fill the Viewport Rectangle with the VideoBrush var vidBrush = new VideoBrush(); vidBrush.SetSource(captureSource); Viewport.Fill = vidBrush; }
// Constructor public MainPage() { InitializeComponent(); c = new CaptureSource(); c.VideoCaptureDevice = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices().First(); var vidBrush = new VideoBrush(); vidBrush.SetSource(c); ViewPort.Fill = vidBrush; }
public void LoadCamera(ICameraCaptureDevice camera) { if (VideoBrush == null && camera != null) { RunOnUIThread(() => { VideoBrush = new VideoBrush(); VideoBrush.Stretch = Stretch.Uniform; VideoBrush.SetSource(camera); Rectangle.Fill = VideoBrush; }); } }
private void ConnectWebcamToDevice() { if (!CaptureDeviceConfiguration.AllowedDeviceAccess) { if(!CaptureDeviceConfiguration.RequestDeviceAccess()) return; } _cam.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); var brush = new VideoBrush {Stretch = Stretch.Uniform}; brush.SetSource(_cam); CamDisplay.Fill = brush; }
/// <summary> /// 获得VideoBrush对象 /// </summary> /// <returns></returns> public VideoBrush GetVideoBrush() { VideoBrush vBrush = new VideoBrush(); if (_vcDevice != null) { _cSource.VideoCaptureDevice = _vcDevice; vBrush.SetSource(_cSource);//注意,不能在这里直接开启摄像头,必须等到所有设置准备就绪 } else { Console.WriteLine("尚未找到捕捉设备!请确保设备正确安装!"); } return vBrush; }
public void InitializeVideoRecorder() { try { //fileName = string.Format(@"\Purposecode\Video{0}.mp4", DateTime.Now.ToString("yyyyMMddHHmmss")); fileName = string.Format("Video{0}.mp4", DateTime.Now.ToString("yyyyMMddHHmmss")); if (captureSource == null) { // Create the VideoRecorder objects. captureSource = new CaptureSource(); fileSink = new FileSink(); videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // Add eventhandlers for captureSource. captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed); // Initialize the camera if it exists on the device. if (videoCaptureDevice != null) { // Create the VideoBrush for the viewfinder. videoRecorderBrush = new VideoBrush(); videoRecorderBrush.SetSource(captureSource); // Display the viewfinder image on the rectangle. viewfinderRectangle.Fill = videoRecorderBrush; StopPlaybackRecording.IsEnabled = false; // Start video capture and display it on the viewfinder. captureSource.Start(); // Set the button state and the message. UpdateUI(ButtonState.Initialized, "Tap record to start recording..."); } else { // Disable buttons when the camera is not supported by the device. UpdateUI(ButtonState.CameraNotSupported, "Camera is not supported.."); } } } catch (Exception ex) { var test = ex.Message; } } //InitializeVideoRecorder()
private void StartRecordig() { if (m_captureSource == null) { m_captureSource = new CaptureSource(); m_captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); m_captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice(); m_sink = new FileSink(); m_sink.CaptureSource = m_captureSource; m_sink.IsolatedStorageFileName = m_capturedFileName; } VideoBrush brush = new VideoBrush(); brush.SetSource(m_captureSource); CameraPreview.Fill = brush; m_captureSource.Start(); }
private void StartCapture_Click(object sender, RoutedEventArgs e) { _captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); _captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice(); VideoBrush videoBrush = new VideoBrush(); videoBrush.Stretch = Stretch.Uniform; videoBrush.SetSource(_captureSource); _videoStream = new MemoryStream(); RiffAviFileWriter aviFileWriter = new RiffAviFileWriter(_videoStream); _videoSink = new BufferQueueVideoSink(aviFileWriter) { CaptureSource = _captureSource }; if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) _captureSource.Start(); Video.Fill = videoBrush; }
public void displayPreview(String camName, Rectangle videoPanel) { // create a new VideoBrush videoBrush = null; videoBrush = new VideoBrush(); videoBrush.Stretch = Stretch.Uniform; // connect the new VideoBrush to the new device foreach (Webcam wc in webcams) { if (wc.toString().Equals(camName)) { videoBrush.SetSource(wc.getSrc()()); break; } } // connect the VideoPanel to the new VideoBrush videoPanel.Fill = videoBrush; }
private void InitializeVideoRecorder() { if (_captureSource == null) { _captureSource = new CaptureSource(); _fileSink = new FileSink(); _videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); _captureSource.CaptureFailed += OnCaptureSourceOnCaptureFailed; _captureSource.CaptureImageCompleted += CaptureSourceOnCaptureImageCompleted; if (_videoCaptureDevice != null) { _videoBrush = new VideoBrush(); _videoBrush.SetSource(_captureSource); ViewFinderRectangle.Fill = _videoBrush; _captureSource.Start(); } } }
/// <summary> /// Initialize the Capture Device /// </summary> private void InitializeCaptureDevice() { //set the video capture device if (captureSource == null) { captureSource = new CaptureSource(); captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice(); sink = new FileSink(); sink.CaptureSource = captureSource; sink.IsolatedStorageFileName = m_capturedFileName; } //set the video preview var brush = new VideoBrush(); brush.SetSource(captureSource); cameraPreview.Fill = brush; }
private void BtnCapture_Click(object sender, RoutedEventArgs e) { try { // 开始捕捉 if (captureSource.State != CaptureState.Started) { captureSource.Stop(); // 创建 video brush 并填充到 rectangle VideoBrush vidBrush = new VideoBrush(); vidBrush.Stretch = Stretch.UniformToFill; vidBrush.SetSource(captureSource); focusRectangle.Viewport.Fill = vidBrush; // 询问是否接入 if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) { focusRectangle.Viewport.MaxHeight = focusRectangle.Viewport.MaxWidth = ZoomInOut.Maximum = 400; ZoomInOut.Value = 270; ZoomInOut.Minimum = 16; ZoomInOut.ValueChanged += new RoutedPropertyChangedEventHandler<double>(focusRectangle.ViewportSlider_ValueChanged); captureSource.Start(); BtnCapture.Text = "打开摄像头"; BtnUploadImage.IsEnabled = BtnAdvanceMode.IsEnabled = true; } } else { captureSource.Stop(); BtnCapture.Text = "关闭摄像头"; BtnUploadImage.IsEnabled = BtnAdvanceMode.IsEnabled = false; } } catch (Exception ex) { Utils.ShowMessageBox("Error using webcam", ex.Message); } }
private void UserControlLoaded(object sender, RoutedEventArgs e) { // Initialize the webcam captureSource = new CaptureSource {VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice()}; // Desired format is 640 x 480 (good tracking results and performance) captureSource.VideoCaptureDevice.DesiredFormat = new VideoFormat(PixelFormatType.Unknown, 640, 480, 60); captureSource.CaptureImageCompleted += CaptureSourceCaptureImageCompleted; // Fill the Viewport Rectangle with the VideoBrush var vidBrush = new VideoBrush(); vidBrush.SetSource(captureSource); Viewport.Fill = vidBrush; // Conctruct the Detector arDetector = new BitmapMarkerDetector { Threshold = 200, JitteringThreshold = 1 }; // Load the marker patterns. It has 16x16 segments and a width of 80 millimeters slarMarker = Marker.LoadFromResource("data/Marker_SLAR_16x16segments_80width.pat", 16, 16, 80); // Capture or transform periodically CompositionTarget.Rendering += (s, e2) => { if (captureSource.State == CaptureState.Started) { captureSource.CaptureImageAsync(); } else { Game.SetWorldMatrix(Balder.Math.Matrix.Identity); } if (Game.ParticleSystem.Particles != null && Game.ParticleSystem.Particles.Count > 0) { } }; }
public void InitializeVideoRecorder() { if (_captureSource == null) { // Create the VideoRecorder objects. _captureSource = new CaptureSource(); _fileSink = new FileSink(); _videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // Add eventhandlers for captureSource. _captureSource.CaptureFailed += OnCaptureFailed; // Initialize the camera if it exists on the phone. if (_videoCaptureDevice != null) { // Create the VideoBrush for the viewfinder. _videoRecorderBrush = new VideoBrush(); _videoRecorderBrush.SetSource(_captureSource); // Display the viewfinder image on the rectangle. viewfinderRectangle.Fill = _videoRecorderBrush; // Start video capture and display it on the viewfinder. _captureSource.Start(); // Set the button state and the message. UpdateUI(ButtonState.Initialized, "Tap record to start recording..."); } else { // Disable buttons when the camera is not supported by the phone. UpdateUI(ButtonState.NoChange, "Camera Not Supported."); } } }
private void btCapture_Click(object sender, RoutedEventArgs e) { if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) { VideoCaptureDevice webcam=cboWebcams.SelectedItem as VideoCaptureDevice; if(webcam==null) CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); if (webcam != null) { capture.Stop(); capture.VideoCaptureDevice = webcam; capture.Start(); VideoBrush brush = new VideoBrush(); brush.SetSource(capture); brush.Stretch = Stretch.Uniform; captureRect.Fill = brush; } else MessageBox.Show("Nessuna webcam disponibile"); } }
void InitializeCamera(CameraType cameraType) { // Camera resolution data gathering requires the camera to be initialized var camera = new PhotoCamera(cameraType); using (var mutex = new ManualResetEvent(false)) { camera.Initialized += (sender, e) => { try { CollectCameraCaps(sender, e); } finally { mutex.Set(); } }; var dummyBrush = new VideoBrush(); dummyBrush.SetSource(camera); // Needed for the camera.Initialized event to fire. mutex.WaitOne(); } }
private async Task InitializePhotoCaptureDevice(CameraSensorLocation sensorLocation, Size size, Size previewSize) { PhotoCaptureDevice = await PhotoCaptureDevice.OpenAsync(sensorLocation, size); await PhotoCaptureDevice.SetPreviewResolutionAsync(previewSize); CompositeTransform = new CompositeTransform(); CompositeTransform.CenterX = .5; CompositeTransform.CenterY = .5; CompositeTransform.Rotation = PhotoCaptureDevice.SensorRotationInDegrees - (Orientation == PageOrientation.LandscapeLeft ? 90 : 0) + (Orientation == PageOrientation.LandscapeRight ? 90 : 0); if (sensorLocation == CameraSensorLocation.Front) { CompositeTransform.ScaleX = -1; } VideoBrush = new VideoBrush(); VideoBrush.RelativeTransform = CompositeTransform; VideoBrush.Stretch = Stretch.Fill; VideoBrush.SetSource(PhotoCaptureDevice); }
/// <summary> /// Initializes VideoRecorder /// </summary> public void InitializeVideoRecorder() { if (captureSource == null) { captureSource = new CaptureSource(); fileSink = new FileSink(); videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); if (videoCaptureDevice != null) { videoRecorderBrush = new VideoBrush(); videoRecorderBrush.SetSource(captureSource); viewfinderRectangle.Fill = videoRecorderBrush; captureSource.Start(); this.UpdateUI(VideoState.Initialized); } else { this.UpdateUI(VideoState.CameraNotSupported); } } }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { mCamera = new PhotoCamera(CameraType.Primary); mVideoBrush = new VideoBrush(); mVideoBrush.SetSource(mCamera); mVideoBrush.Stretch = Stretch.Uniform; runtime.RegisterCleaner(delegate() { mCamera.Dispose(); mCamera = null; }); // this should be set according to the orientation of // the device I guess. mVideoBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 }; ioctls.maCameraFormat = delegate(int _index, int _fmt) { System.Windows.Size dim; if (GetCameraFormat(_index, out dim) == false) return MoSync.Constants.MA_CAMERA_RES_FAILED; core.GetDataMemory().WriteInt32(_fmt + MoSync.Struct.MA_CAMERA_FORMAT.width, (int)dim.Width); core.GetDataMemory().WriteInt32(_fmt + MoSync.Struct.MA_CAMERA_FORMAT.height, (int)dim.Height); return MoSync.Constants.MA_CAMERA_RES_OK; }; ioctls.maCameraFormatNumber = delegate() { IEnumerable<System.Windows.Size> res = mCamera.AvailableResolutions; if (res == null) return 0; IEnumerator<System.Windows.Size> resolutions = res.GetEnumerator(); resolutions.MoveNext(); int number = 0; while (resolutions.Current != null) { number++; } return number; }; ioctls.maCameraStart = delegate() { return 0; }; ioctls.maCameraStop = delegate() { return 0; }; ioctls.maCameraSetPreview = delegate(int _widgetHandle) { // something like // videoBrush = ((CameraViewFinder)runtime.GetModule<MoSyncNativeUIModule>.GetWidget(_widgetHandle)).GetBrush(); // videoBrush.SetSource(mCamera) IWidget w = runtime.GetModule<NativeUIModule>().GetWidget(_widgetHandle); if (w.GetType() != typeof(MoSync.NativeUI.CameraPreview)) { return MoSync.Constants.MA_CAMERA_RES_FAILED; } NativeUI.CameraPreview prev = (NativeUI.CameraPreview)w; System.Windows.Controls.Canvas canvas = prev.GetViewFinderCanvas(); MoSync.Util.RunActionOnMainThreadSync(() => { canvas.Background = mVideoBrush; }); return 0; }; ioctls.maCameraSelect = delegate(int _cameraNumber) { CameraType cameraType = CameraType.Primary; if(_cameraNumber == MoSync.Constants.MA_CAMERA_CONST_BACK_CAMERA) { cameraType = CameraType.Primary; } else if(_cameraNumber == MoSync.Constants.MA_CAMERA_CONST_FRONT_CAMERA) { cameraType = CameraType.FrontFacing; } if(mCamera==null || mCamera.CameraType != cameraType) { mCamera = new PhotoCamera(cameraType); if(mVideoBrush == null) mVideoBrush = new VideoBrush(); mVideoBrush.SetSource(mCamera); } return 0; }; ioctls.maCameraNumber = delegate() { // front facing and back facing is the standard I believe. return 2; }; ioctls.maCameraSnapshot = delegate(int _formatIndex, int _placeHolder) { AutoResetEvent are = new AutoResetEvent(false); System.Windows.Size dim; if (GetCameraFormat(_formatIndex, out dim) == false) return MoSync.Constants.MA_CAMERA_RES_FAILED; mCamera.Resolution = dim; if (mCameraSnapshotDelegate != null) mCamera.CaptureImageAvailable -= mCameraSnapshotDelegate; mCameraSnapshotDelegate = delegate(object o, ContentReadyEventArgs args) { MoSync.Util.RunActionOnMainThreadSync(() => { Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeHolder); Stream data = args.ImageStream; Memory dataMem = new Memory((int)data.Length); dataMem.WriteFromStream(0, data, (int)data.Length); res.SetInternalObject(dataMem); }); are.Set(); }; mCamera.CaptureImageAvailable += mCameraSnapshotDelegate; mCamera.CaptureImage(); are.WaitOne(); return 0; }; ioctls.maCameraSetProperty = delegate(int _property, int _value) { return 0; }; ioctls.maCameraSelect = delegate(int _camera) { return 0; }; ioctls.maCameraGetProperty = delegate(int _property, int _value, int _bufSize) { String property = core.GetDataMemory().ReadStringAtAddress(_property); if (property.Equals(MoSync.Constants.MA_CAMERA_MAX_ZOOM)) { core.GetDataMemory().WriteStringAtAddress( _value, "0", _bufSize); } return 0; }; ioctls.maCameraRecord = delegate(int _stopStartFlag) { return 0; }; }
async void ActivateCamera() { if (_dev == null) { if (AudioVideoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back)) { _dev = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First()); _videoBrush = new VideoBrush(); _videoBrush.SetSource(_dev); MainPage_OrientationChanged(null, null); this.videoRect.Fill = _videoBrush; StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await localFolder.CreateFileAsync("CameraMovie.mp4", CreationCollisionOption.ReplaceExisting); _path = storageFile.Path; _sst = await storageFile.OpenAsync(FileAccessMode.ReadWrite); await _dev.StartRecordingToStreamAsync(_sst); } } }
/// <summary> /// Creates a <see cref="VideoBrush" /> containing the current image. /// </summary> /// <returns>A <see cref="VideoBrush" /> containing the current image.</returns> public VideoBrush CreateVideoBrush() { var videoBrush = new VideoBrush(); videoBrush.SetSource(_photoCamera); return videoBrush; }
void InitializeCamera() { camera = new PhotoCamera(CameraType.Primary); camera.Initialized += camera_Initialized; camera.CaptureImageAvailable += camera_CaptureImageAvailable; camera.CaptureCompleted += camera_CaptureCompleted; CameraButtons.ShutterKeyPressed += cameraButtons_ShutterKeyPressed; // create and rotate the brush since our orientation does not match the cameras default orientation. var brush = new VideoBrush(); brush.SetSource(camera); brush.RelativeTransform = new RotateTransform { CenterX = 0.5, CenterY = 0.5, Angle = camera.Orientation }; photoContainer.Fill = brush; }
/// <summary> /// Initializes video preview and updates the <see cref="PreviewBrush"/> accordingly. /// </summary> /// <param name="previewFormatSelector"> /// Function that chooses the most suitable preview format from the provided collection. /// </param> /// <returns>Awaitable task.</returns> /// <exception cref="ArgumentNullException"><paramref name="previewFormatSelector"/> is <see langword="null"/>.</exception> /// <exception cref="InvalidOperationException">No suitable video preview formats found.</exception> public async Task StartPreviewAsync(Func<IEnumerable<VideoEncodingProperties>, VideoEncodingProperties> previewFormatSelector) { if (previewFormatSelector == null) { throw new ArgumentNullException("previewFormatSelector"); } Tracing.Trace("CameraController: Starting video preview."); if (!string.IsNullOrEmpty(this.PreviewVideoPort)) { Tracing.Trace("CameraController: Video preview is already started."); return; } try { // Set the video preview format. VideoEncodingProperties previewFormat = await this.DoSetMediaFormatAsync(MediaStreamType.VideoPreview, previewFormatSelector); MediaCapturePreviewSink previewSink = new MediaCapturePreviewSink(); VideoBrush videoBrush = new VideoBrush(); videoBrush.SetSource(previewSink); MediaEncodingProfile profile = new MediaEncodingProfile { Audio = null, Video = previewFormat }; await this.MediaCapture.StartPreviewToCustomSinkAsync(profile, previewSink); this.PreviewFormat = previewFormat; this.PreviewResolution = new Size(previewFormat.Width, previewFormat.Height); this.PreviewBrush = videoBrush; this.PreviewVideoPort = previewSink.ConnectionPort; //// //// Update camera properties. //// this.Rotation = this.MediaCapture.GetPreviewRotation(); this.FocusSupported = this.MediaCapture.VideoDeviceController.FocusControl.Supported; this.FocusAtPointSupported = this.MediaCapture.VideoDeviceController.RegionsOfInterestControl.AutoFocusSupported && this.MediaCapture.VideoDeviceController.RegionsOfInterestControl.MaxRegions > 0; this.ContinuousAutoFocusSupported = this.MediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Continuous); this.FlashSupported = this.MediaCapture.VideoDeviceController.FlashControl.Supported; if (this.FocusSupported) { this.ConfigureAutoFocus(continuous: false); if (this.MediaCapture.VideoDeviceController.FocusControl.FocusChangedSupported) { this.MediaCapture.FocusChanged += this.MediaCaptureFocusChanged; } } this.NotifyPropertiesChanged(); } catch (Exception e) { Tracing.Trace("CameraController: StartPreviewAsync: 0x{0:X8}\r\n{1}", e.HResult, e); throw; } Tracing.Trace("CameraController: Video preview started."); }
private void InitializeCamera() { if (_capture == null) { _capture = new CaptureSource(); _capture.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); _capture.AudioCaptureDevice = null; _capture.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(_capture_CaptureImageCompleted); } if (_capture != null) { _capture.Stop(); _capture.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); _capture.AudioCaptureDevice = null; VideoBrush videoBrush = new VideoBrush(); videoBrush.Stretch = Stretch.Fill; videoBrush.SetSource(_capture); rectVideo.Fill = videoBrush; if ((CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())) { _capture.Start(); } } }
//Code for camera initialization event, and setting the source for the viewfinder protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { MI_Width = (int)MainImage.Width; MI_Height = (int)MainImage.Height; MI_Left = (int)MainImage.Margin.Left; MI_Top = (int)MainImage.Margin.Top; MI_Right = (int)MainImage.Margin.Right; MI_Bottom = (int)MainImage.Margin.Bottom; MI_Buffer = new byte[MI_Height * MI_Width]; // 180 * 242 = 43560 digFinder = new DigitFinder(); digRecognizer = new DigitRecognizer9(); InitState(); if (ShowDebugData.IsChecked == true) IfShowDebugDataChecked(); else IfShowDebugDataUnchecked(); //base.OnNavigatedTo(e); // Check to see if the camera is available on the device. if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) || (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) { // Initialize the default camera. cam = new PhotoCamera(); //Event is fired when the PhotoCamera object has been initialized cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized); //Set the VideoBrush source to the camera viewfinderBrush = new VideoBrush(); viewfinderRectangle.Fill = viewfinderBrush; viewfinderBrush.SetSource(cam); Dispatcher.BeginInvoke(() => { // Start timer dispatcherTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; dispatcherTimer.Tick += (sender, e1) => Recognize(); dispatcherTimer.Start(); } ); } else { // The camera is not supported on the device. this.Dispatcher.BeginInvoke(delegate() { // Write message. txtDebug.Text = "A Camera is not available on this device."; }); } }