public ViewModelMain(ref CaptureElement cameraControlView) { CameraControl = cameraControlView; TakePhotoManager = new MediaCapture(); var task = CameraTest_task(); var task2 = PictureLoading_task(); CameraViewCommand = new Pomocnicze.RelayCommand(pars => CameraViewButton()); ImageListCommand = new Pomocnicze.RelayCommand(pars => ShowImagesList_async()); ShareCommand = new Pomocnicze.RelayCommand(pars => ShareButton()); PictureTapCommand = new Pomocnicze.RelayCommand(pars => SetNextPicture()); Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested +=BackRequested; DataTransferManager ShareManager = DataTransferManager.GetForCurrentView(); ShareManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.ShareImageHandler); CameraButtonName = "Camera View"; ImageListButtonName = "Images List"; ShareButtonName = "Share"; ShareButtonIsEnable = true; }
public async Task InitializePreview(CaptureElement captureElement) { captureManager = new MediaCapture(); var cameraID = await GetCameraID(Panel.Back); if (cameraID == null) { return; } 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(captureElement); }
public FaceTrackerProxy (Canvas canvas, MainPage page, CaptureElement capture, MediaCapture mediacapture ) { if (this.faceTracker == null) { this.faceTracker = FaceTracker.CreateAsync().AsTask().Result; } rootPage = page; VisualizationCanvas = canvas; this.VisualizationCanvas.Children.Clear(); mediaCapture = mediacapture; var deviceController = mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; currentState = ScenarioState.Streaming; // Ensure the Semaphore is in the signalled state. this.frameProcessingSemaphore.Release(); // Use a 66 milisecond interval for our timer, i.e. 15 frames per second TimeSpan timerInterval = TimeSpan.FromMilliseconds(200); this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval); }
public UposleniciViewModel(CaptureElement previewControl) { //incijalicacija uredjaja eksterniServis = new ExterniServis(); CreateUposlenik = new Uposlenik(); rfid = new Rfid(); rfid.InitializeReader(RfidReadSomething); Camera = new CameraHelper(previewControl); Camera.InitializeCameraAsync(); DodajUposlenika = new RelayCommand<object>(dodajUposlenika, (object parametar) => true); Uslikaj = new RelayCommand<object>(uslikaj, (object parametar) => true); }
public async Task InitPreview(CaptureElement captureElement) { this.CameraCaptureElement = captureElement; this.CameraMediaCapture = new MediaCapture(); // Initialize capture settings for Video mode MediaCaptureInitializationSettings settings = new Windows.Media.Capture.MediaCaptureInitializationSettings(); settings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview; // Select proper Video device to match back camera (depending on whether or not the device has front+back cameras or only back camera) DeviceInformationCollection Videodevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (Videodevices.Count == 0) { // No camera available captureElement.Tag = "NoCamera"; return; } else { this.CameraCaptureElement.Tag = "CameraFound"; if (Videodevices.Count == 1) { settings.VideoDeviceId = Videodevices[0].Id; // Videodevices[0].Id; -> back camera } else { settings.VideoDeviceId = Videodevices[1].Id; // Videodevices[0].Id; -> front camera, Videodevices[1].Id; -> back camera } } // Set settings and source on Camera await this.CameraMediaCapture.InitializeAsync(settings); SetResolution(); // Adjust camera preview orientation DisplayInformation displayInfo = DisplayInformation.GetForCurrentView(); displayInfo.OrientationChanged += DisplayInfo_OrientationChanged; DisplayInfo_OrientationChanged(displayInfo, null); this.CameraCaptureElement.Source = this.CameraMediaCapture; // Start Camera preview await this.CameraMediaCapture.StartPreviewAsync(); }
public async Task InitialAsync(CaptureElement captureElement, MediaEncodingProfile profile = null, bool BackCamera = false) { if (initialized) Dispose(true); initialized = true; this.captureElement = captureElement; this.activeProfile = profile; if (CameraDeviceList == null) await EnumerateCameras(); mediaCapture = null; mediaCapture = new MediaCapture(); IsBackCamera = BackCamera; captureInitSettings = InitCaptureSettings(IsBackCamera); await mediaCapture.InitializeAsync(captureInitSettings); mediaCapture.VideoDeviceController.DesiredOptimization = MediaCaptureOptimization.LatencyThenQuality; mediaCapture.CameraStreamStateChanged += MediaCapture_CameraStreamStateChanged; mediaCapture.Failed += MediaCapture_Failed; mediaCapture.FocusChanged += MediaCapture_FocusChanged; mediaCapture.PhotoConfirmationCaptured += MediaCapture_PhotoConfirmationCaptured; mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded; mediaCapture.ThermalStatusChanged += MediaCapture_ThermalStatusChanged; await SetResolutionAsync(); if (Manager.DeviceService.CurrentDevice() == DeviceTypes.Mobile) { if (IsBackCamera) { mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees); } else { mediaCapture.SetPreviewRotation(VideoRotation.Clockwise270Degrees); } } activeProfile = CreateProfile(); mediaCapture.VideoDeviceController.PrimaryUse = CaptureUse.Video; captureElement.Source = mediaCapture; }
void SetupUserInterface () { takePhotoButton = new AppBarButton { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Icon = new SymbolIcon (Symbol.Camera) }; var commandBar = new CommandBar (); commandBar.PrimaryCommands.Add (takePhotoButton); captureElement = new CaptureElement (); captureElement.Stretch = Stretch.UniformToFill; var stackPanel = new StackPanel (); stackPanel.Children.Add (captureElement); page = new Page (); page.BottomAppBar = commandBar; page.Content = stackPanel; page.Unloaded += OnPageUnloaded; }
public ViewModelMain(ref CaptureElement ce) { camera_source = ce; takephotoManager = new MediaCapture(); var task = CameraTest(); CameraViewCommand = new Pomocnicze.RelayCommand(pars => CameraViewButton()); ImageListCommand = new Pomocnicze.RelayCommand(pars => ImageListButton()); ShareCommand = new Pomocnicze.RelayCommand(pars => ShareButton()); TheTapCommand = new Pomocnicze.RelayCommand(pars => NastepnyObrazek()); var wczytywanie_obr = wczytywanie_obrazka(); Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested +=App_BackRequested; DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.ShareImageHandler); CameraButtonName = "Camera View"; ImageListButtonName = "Images List"; ShareButtonName = "Share"; ShareButtonIsEnable = true; }
private async void OnFrameworkElementLoaded(FrameworkElement frameworkElement) { m_PreviewVideoElement = (CaptureElement)frameworkElement; await StartPreviewAsync(); }
public CameraFeedUtility(CaptureElement captureElement, CoreDispatcher dispatcher) { this.captureElement = captureElement; this.dispatcher = dispatcher; }
/// <summary> /// Starts the preview /// </summary> private async Task StartPreviewAsync() { if (_cap == null) { _cap = new CaptureElement(); } _cap.Source = _mediaCapture; // Start the preview await _mediaCapture.StartPreviewAsync(); }
/// <summary> /// Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. /// In simplest terms, this means the method is called just before a UI element displays in your app. /// Override this method to influence the default post-template logic of a class. /// </summary> protected override void OnApplyTemplate() { base.OnApplyTemplate(); _captureElement = (CaptureElement)GetTemplateChild(CaptureElementName); if (MediaCapture != null) { _captureElement.Source = MediaCapture; } _webCamSelectorPopup = GetTemplateChild(WebCamSelectorPopupName) as Popup; _webCamSelector = GetTemplateChild(WebCamSelectorName) as Selector; _recordingIndicator = GetTemplateChild(RecordingIndicatorName) as LayoutPanel; _recordingAnimation = GetTemplateChild(RecordingAnimationName) as Storyboard; _countdownControl = GetTemplateChild(CountdownControlName) as CountdownControl; _flashAnimation = GetTemplateChild(FlashAnimationName) as Storyboard; }
/// <summary> /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform /// </summary> /// <param name="previewResolution">The resolution at which the preview is running</param> /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param> /// <returns></returns> private static Rect GetPreviewStreamRectInControl(Size previewResolution, CaptureElement previewControl) { var result = new Rect(); // In case this function is called before everything is initialized correctly, return an empty result if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 || previewResolution.Height < 1 || previewResolution.Width < 1) { return result; } var streamWidth = previewResolution.Width; var streamHeight = previewResolution.Height; // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension) result.Width = previewControl.ActualWidth; result.Height = previewControl.ActualHeight; // If UI is "wider" than preview, letterboxing will be on the sides if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight)) { var scale = previewControl.ActualHeight / streamHeight; var scaledWidth = streamWidth * scale; result.X = (previewControl.ActualWidth - scaledWidth) / 2.0; result.Width = scaledWidth; } else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom { var scale = previewControl.ActualWidth / streamWidth; var scaledHeight = streamHeight * scale; result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0; result.Height = scaledHeight; } return result; }
/// <summary> /// Loads the camera. /// </summary> /// <param name="capturePreview">The capture preview.</param> public async Task LoadCamera(CaptureElement capturePreview) { _capturePreviewElement = capturePreview; try { await _cameraEngine.InitCamera(); await _cameraEngine.StartPreviewAsync(); } catch (CameraNotFoundException) { await _dialogService.ShowNotification("CameraNotFound_Message", "CameraNotFound_Title"); } catch (Exception) { await _dialogService.ShowNotification("GenericError_Message", "GenericError_Title"); } }
/// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); #if WINDOWS_PHONE_APP if (MediaCapture != null) { await MediaCapture.StartPreviewAsync(); MediaCapture.Dispose(); MediaCapture = null; PreviewElement.Source = null; PreviewElement = null; } #endif // TODO: Save application state and stop any background activity deferral.Complete(); }
public async Task InitAsync(CaptureElement captureElement) { await _mediaCapture.InitializeAsync(); captureElement.Source = _mediaCapture; await _mediaCapture.StartPreviewAsync(); }
public override void Initialize(VideoCaptureInitializeArgs captureArgs) { Preview = new CaptureElement(); }
public CameraHelper(CaptureElement previewControl) { PreviewControl = previewControl; }
public MediaCapturePreviewer(CaptureElement previewControl, CoreDispatcher dispatcher) { _previewControl = previewControl; _dispatcher = dispatcher; }
public void Dispose(bool threadSafe) { //Called at run time by user, use to clear managed resource if (threadSafe) { if (isRecording) { //try //{ // await StopRecordingAsync(); //} } if (isPreviewing) { //try //{ // await StopPreviewAsync(); //} } if (this.captureElement != null) { this.captureElement.Source = null; this.captureElement = null; } if (lowlag != null) { //try //{ // await lowlag.FinishAsync(); //} lowlag = null; } } else { //Clear unmanaged resource here } if (this.mediaCapture != null) { mediaCapture.CameraStreamStateChanged -= MediaCapture_CameraStreamStateChanged; mediaCapture.Failed -= MediaCapture_Failed; mediaCapture.FocusChanged -= MediaCapture_FocusChanged; mediaCapture.PhotoConfirmationCaptured -= MediaCapture_PhotoConfirmationCaptured; mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded; mediaCapture.ThermalStatusChanged -= MediaCapture_ThermalStatusChanged; mediaCapture.Dispose(); this.mediaCapture = null; } //Hack to prevent green screen GC.Collect(); }
private async void StartPreview(CaptureElement captureElement) { captureElement.Visibility = Visibility.Visible; captureElement.Source = captureManager; await captureManager.StartPreviewAsync(); isPreviewing = true; if (GetDisplayAspectRatio() == DisplayAspectRatio.FifteenByNine) { GetFifteenByNineBounds(); } }
private async void ScanButton(object sender, object e) { string result = null; try { Waiter(true); var tcs = new TaskCompletionSource<object>(); StackPanel sp = new StackPanel() { Margin = new Thickness(20) }; #if WINDOWS_PHONE if (Device == null) { Windows.Foundation.Size initialResolution = new Windows.Foundation.Size(640, 480); wbm = new WriteableBitmap(640, 480); Device = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, initialResolution); Device.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, Device.SensorLocation == CameraSensorLocation.Back ? Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees); Device.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Macro); Device.SetProperty(KnownCameraPhotoProperties.SceneMode, CameraSceneMode.Macro); Device.SetProperty(KnownCameraPhotoProperties.FocusIlluminationMode, FocusIlluminationMode.Off); } Rectangle previewRect = new Rectangle() { Height = 480, Width = 360 }; VideoBrush previewVideo = new VideoBrush(); previewVideo.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = (Device.SensorLocation == CameraSensorLocation.Back ? Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees) }; previewVideo.SetSource(Device); previewRect.Fill = previewVideo; Grid combiner = new Grid() { Height = previewRect.Height, Width = previewRect.Width }; combiner.Children.Add(previewRect); Grid.SetColumnSpan(previewRect, 3); Grid.SetRowSpan(previewRect, 3); int windowSize = 100; combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) }); combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(windowSize) }); combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) }); var maskBrush = new SolidColorBrush(Color.FromArgb(80, 0, 0, 0)); Canvas v1 = new Canvas() { Background = maskBrush }; Canvas v2 = new Canvas() { Background = maskBrush }; Canvas v3 = new Canvas() { Background = maskBrush }; Canvas v4 = new Canvas() { Background = maskBrush }; combiner.Children.Add(v1); Grid.SetRow(v1, 0); Grid.SetColumnSpan(v1, 3); combiner.Children.Add(v2); Grid.SetRow(v2, 2); Grid.SetColumnSpan(v2, 3); combiner.Children.Add(v3); Grid.SetRow(v3, 1); Grid.SetColumn(v3, 0); combiner.Children.Add(v4); Grid.SetRow(v4, 1); Grid.SetColumn(v4, 2); sp.Children.Add(combiner); BackgroundWorker bw = new BackgroundWorker(); DateTime last = DateTime.Now; bw.WorkerSupportsCancellation = true; bw.DoWork += async (s2, e2) => { var reader = new BarcodeReader(); while (!bw.CancellationPending) { if (DateTime.Now.Subtract(last).TotalSeconds > 2) { await Device.FocusAsync(); last = DateTime.Now; } try { Device.GetPreviewBufferArgb(wbm.Pixels); Debug.WriteLine(DateTime.Now.Millisecond); var codeVal = reader.Decode(wbm); if (codeVal != null) { result = codeVal.Text; e2.Cancel = true; tcs.TrySetResult(null); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } }; bw.RunWorkerAsync(); #else var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (cameras.Count < 1) { return; } var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras.Last().Id }; var imageSource = new MediaCapture(); await imageSource.InitializeAsync(settings); CaptureElement previewRect = new CaptureElement() { Width = 640, Height = 360 }; previewRect.Source = imageSource; sp.Children.Add(previewRect); await imageSource.StartPreviewAsync(); bool keepGoing = true; Action a = null; a = async () => { if (!keepGoing) return; var stream = new InMemoryRandomAccessStream(); await imageSource.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); stream.Seek(0); var tmpBmp = new WriteableBitmap(1, 1); await tmpBmp.SetSourceAsync(stream); var writeableBmp = new WriteableBitmap(tmpBmp.PixelWidth, tmpBmp.PixelHeight); stream.Seek(0); await writeableBmp.SetSourceAsync(stream); Result _result = null; var barcodeReader = new BarcodeReader { // TryHarder = true, AutoRotate = true }; try { _result = barcodeReader.Decode(writeableBmp); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } stream.Dispose(); if (_result != null) { result = _result.Text; Debug.WriteLine(_result.Text); keepGoing = false; tcs.TrySetResult(null); } else { var x = RunOnUIThread(a); } }; await RunOnUIThread(a); #endif CustomMessageBox messageBox = new CustomMessageBox() { Title = "Scan Tag", Message = "", Content = sp, LeftButtonContent = "OK", RightButtonContent = "Cancel", IsFullScreen = false, }; messageBox.Unloaded += (s2, e2) => { tcs.TrySetResult(null); }; messageBox.Show(); await tcs.Task; messageBox.Dismiss(); #if WINDOWS_PHONE bw.CancelAsync(); #else keepGoing = false; await imageSource.StopPreviewAsync(); #endif Debug.WriteLine("result: '" + result + "'"); string loc = null; string building = null; string floor = null; string room = null; if (!string.IsNullOrEmpty(result)) { var s = result.Split(new char[] { '?' }, 2); if (s.Length == 2) { var paramList = s[1].Split('&') .Select(p => p.Split(new char[] { '=' }, 2)) .Where(p => p.Length == 2); loc = pick(paramList, "cp"); building = pick(paramList, "bld"); floor = pick(paramList, "flr"); room = pick(paramList, "rm"); } } GeoCoord? locVal = GeoCoord.Parse(loc); if (!string.IsNullOrEmpty(building) && !string.IsNullOrEmpty(floor)) { await ShowMap(RoomInfo.Parse(building + "/" + (room == null ? floor : room)), locVal); } } finally { Waiter(false); } }
public CameraService(CaptureElement el) { _captureElement = el; }
/// <summary> /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform /// </summary> /// <param name="previewResolution">The resolution at which the preview is running</param> /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param> /// <param name="displayOrientation">The orientation of the display, to account for device rotation and changing of the CaptureElement display ratio compared to the camera stream</param> /// <returns></returns> public static Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation) { var result = new Rect(); // In case this function is called before everything is initialized correctly, return an empty result if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 || previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0) { return result; } var streamWidth = previewResolution.Width; var streamHeight = previewResolution.Height; // For portrait orientations, the width and height need to be swapped if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped) { streamWidth = previewResolution.Height; streamHeight = previewResolution.Width; } // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension) result.Width = previewControl.ActualWidth; result.Height = previewControl.ActualHeight; // If UI is "wider" than preview, letterboxing will be on the sides if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight)) { var scale = previewControl.ActualHeight / streamHeight; var scaledWidth = streamWidth * scale; result.X = (previewControl.ActualWidth - scaledWidth) / 2.0; result.Width = scaledWidth; } else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom { var scale = previewControl.ActualWidth / streamWidth; var scaledHeight = streamHeight * scale; result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0; result.Height = scaledHeight; } return result; }
public async Task StartCameraAsync(CaptureElement captureElement) { await _camera.InitAsync(captureElement); }