Here we are using CameraCaptureUI class which provides a full window UI for capturing audio, video, and photos from a camera.
Step 1: Open a blank app and add a Button and a Image control either from the toolbox or by copying the following XAML code into your grid.
- <StackPanel Margin="10,40,0,0">
- <TextBlock Text="Simple Camera" FontSize="20"></TextBlock>
- <Button Name="myCamButton" Content="Start Camera" Height="40" Width="120" Click="myCamButton_Click"></Button>
- <Image Margin="0,20,0,0" Name="capturedImage" Height="300" Width="300"></Image>
- </StackPanel>
Step 2 : Add the following namespaces to your project which is needed in further C# code.
- using Windows.Media.Capture;
- using Windows.Storage;
- using Windows.Storage.Streams;
- using Windows.UI.Xaml.Media.Imaging;
Step 3: Copy and paste the following code to the cs page which will be called on button click event and will start the camera and the captured image will be displayed.
- CameraCaptureUI captureUI = new CameraCaptureUI();
- captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
-
- StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
-
- BitmapImage bitmapImage = new BitmapImage();
- using (IRandomAccessStream fileStream = await photo.OpenAsync(FileAccessMode.Read))
- {
- bitmapImage.SetSource(fileStream);
- }
- capturedImage.Source = bitmapImage;
Step 4: Run your application and test yourself.