/// <summary>
        /// Initialises the camera and resolves the resolution for both the
        /// full resolution and preview images.
        /// </summary>
        private async void InitializeCameraAsync()
        {
            if (CameraState != CameraStates.NotInitialized)
            {
                Debug.WriteLine(DebugTag + "InitializeCameraAsync(): Invalid state");
                return;
            }

            Debug.WriteLine(DebugTag + "InitializeCameraAsync() ->");
            CameraState = CameraStates.Initializing;
            ProgressIndicator.IsActive = true;
            MessageDialog messageDialog = null;

#if WINDOWS_PHONE_APP
            DeviceInformationCollection devices;
            devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            if (devices.Count == 0)
            {
                ProgressIndicator.IsActive = false;
                CameraState   = CameraStates.NotInitialized;
                messageDialog = new MessageDialog(
                    _resourceLoader.GetString("FailedToFindCameraDevice/Text"),
                    _resourceLoader.GetString("CameraInitializationFailed/Text"));
                await messageDialog.ShowAsync();

                return;
            }

            // Use the back camera
            DeviceInformation info = devices[0];
            _cam = true;

            foreach (var devInfo in devices)
            {
                if (devInfo.Name.ToLowerInvariant().Contains("back"))
                {
                    info = devInfo;
                    _cam = false; // Set this to true if you use front camera
                    break;
                }
            }

            MyCaptureElement.FlowDirection = _cam ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
#endif
            _mediaCapture = new MediaCapture();

            try
            {
#if WINDOWS_PHONE_APP
                await _mediaCapture.InitializeAsync(
                    new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                    AudioDeviceId        = string.Empty,
                    VideoDeviceId        = info.Id
                });
#else
                await _mediaCapture.InitializeAsync();
#endif
            }
            catch (Exception ex)
            {
                messageDialog = new MessageDialog(ex.ToString(), _resourceLoader.GetString("CameraInitializationFailed/Text"));
            }

            MyCaptureElement.Source = _mediaCapture;

            if (messageDialog != null)
            {
                /* Add commands and set their callbacks; both buttons use the
                 * same callback function instead of inline event handlers
                 */
                if (messageDialog.Commands != null)
                {
                    messageDialog.Commands.Add(new UICommand(_resourceLoader.GetString("Retry/Text"), CommandInvokedHandler));
                    messageDialog.Commands.Add(new UICommand(_resourceLoader.GetString("Cancel/Text"), CommandInvokedHandler));
                }

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                await messageDialog.ShowAsync();
            }
            else
            {
                // Get the resolution
                uint width  = 0;
                uint height = 0;
                IMediaEncodingProperties propertiesToSet = null;
                AppUtils.GetBestResolution(_mediaCapture, ref width, ref height, ref propertiesToSet);

                if (width > 0 && height > 0)
                {
                    _dataContext.SetFullResolution((int)width, (int)height);
                    int previewWidth  = (int)FilterEffects.DataContext.DefaultPreviewResolutionWidth;
                    int previewHeight = 0;
                    AppUtils.CalculatePreviewResolution((int)width, (int)height, ref previewWidth, ref previewHeight);
                    _dataContext.SetPreviewResolution(previewWidth, previewHeight);
                }

                if (propertiesToSet != null)
                {
                    await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(
                        MediaStreamType.Photo, propertiesToSet);

                    Debug.WriteLine(DebugTag + "Capture resolution set to " + width + "x" + height + "!");
                }
                else
                {
                    Debug.WriteLine(DebugTag + "Failed to set capture resolution! Using fallback resolution.");
                    var fallbackResolution = new Size(
                        FilterEffects.DataContext.DefaultPreviewResolutionWidth,
                        FilterEffects.DataContext.DefaultPreviewResolutionHeight);
                    _dataContext.PreviewResolution = fallbackResolution;
                    _dataContext.FullResolution    = fallbackResolution;
                }

                _mediaCapture.SetPreviewMirroring(false);
                await _mediaCapture.StartPreviewAsync();
            }

#if WINDOWS_PHONE_APP
            // In case front camera is used, we need to handle the rotations
            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();
            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;
            DisplayInfo_OrientationChanged(displayInfo, null);
#endif
            CameraState = CameraStates.Initialized;
            ProgressIndicator.IsActive = false;
            CaptureButton.IsEnabled    = true;
            Debug.WriteLine(DebugTag + "InitializeCameraAsync() <-");
        }
Exemplo n.º 2
0
        private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
        {
            await _photoCaptureManager.StopPreviewAsync();

            var openPicker = new Windows.Storage.Pickers.FileOpenPicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary,
                ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail
            };

            // Filter to include a sample subset of file types
            openPicker.FileTypeFilter.Clear();

            foreach (string postfix in _supportedImageFilePostfixes)
            {
                openPicker.FileTypeFilter.Add(postfix);
            }

            // Open the file picker
            Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

            // File is null if user cancels the file picker
            if (file != null)
            {
                var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Reset the streams
                _dataContext.ResetStreams();

                var image = new BitmapImage();
                image.SetSource(fileStream);
                int width  = image.PixelWidth;
                int height = image.PixelHeight;
                var bitmap = new WriteableBitmap(width, height);
                _dataContext.SetFullResolution(width, height);

                int previewWidth  = (int)FilterEffects.DataContext.DefaultPreviewResolutionWidth;
                int previewHeight = 0;
                AppUtils.CalculatePreviewResolution(width, height, ref previewWidth, ref previewHeight);
                _dataContext.SetPreviewResolution(previewWidth, previewHeight);

                bool success = false;

                try
                {
                    // Jpeg images can be used as such.
                    Stream stream = fileStream.AsStream();
                    stream.Position = 0;
                    stream.CopyTo(_dataContext.FullResolutionStream);
                    success = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(DebugTag
                                    + "Cannot use stream as such (not probably jpeg): " + ex.Message);
                }

                if (!success)
                {
                    // TODO: Test this part! It may not work.
                    //
                    // Image format is not jpeg. Can be anything, so first
                    // load it into a bitmap image and then write as jpeg.
                    bitmap.SetSource(fileStream);
                    var           inStream = (IRandomAccessStream)_dataContext.FullResolutionStream.AsInputStream();
                    BitmapEncoder encoder  = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inStream);

                    Stream outStream = bitmap.PixelBuffer.AsStream();
                    var    pixels    = new byte[outStream.Length];
                    await outStream.ReadAsync(pixels, 0, pixels.Length);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)width, (uint)height, 96.0, 96.0, pixels);
                    await encoder.FlushAsync();
                }

                await AppUtils.ScaleImageStreamAsync(
                    _dataContext.FullResolutionStream,
                    _dataContext.FullResolution,
                    _dataContext.PreviewResolutionStream,
                    _dataContext.PreviewResolution);

                _dataContext.WasCaptured = false;
                Frame.Navigate(typeof(PreviewPage));
            } // if (file != null)
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        private async void InitializeCameraAsync()
        {
            MessageDialog messageDialog = null;

            try
            {
                await _photoCaptureManager.InitializeAsync();

                CapturePreview.Source = _photoCaptureManager;
            }
            catch (Exception ex)
            {
                messageDialog = new MessageDialog(ex.ToString(), Strings.CameraInitializationFailed);
            }

            if (messageDialog != null)
            {
                /* Add commands and set their callbacks; both buttons use the
                 * same callback function instead of inline event handlers
                 */
                if (messageDialog.Commands != null)
                {
                    messageDialog.Commands.Add(new UICommand(Strings.Retry, CommandInvokedHandler));
                    messageDialog.Commands.Add(new UICommand(Strings.Cancel, CommandInvokedHandler));
                }

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 0;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                await messageDialog.ShowAsync();
            }
            else
            {
                // Get the resolution
                if (_photoCaptureManager.VideoDeviceController != null)
                {
                    var  mediaEncodingPropertiesList = _photoCaptureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);
                    uint width  = 0;
                    uint height = 0;
                    IMediaEncodingProperties propertiesToSet = null;

                    for (int i = 0; i < mediaEncodingPropertiesList.Count; ++i)
                    {
                        IMediaEncodingProperties mediaEncodingProperties =
                            mediaEncodingPropertiesList.ElementAt(i);
                        uint foundWidth  = 0;
                        uint foundHeight = 0;

                        try
                        {
                            var properties = mediaEncodingProperties as ImageEncodingProperties;
                            if (properties != null)
                            {
                                foundWidth  = properties.Width;
                                foundHeight = properties.Height;
                            }
                            else
                            {
                                var encodingProperties = mediaEncodingProperties as VideoEncodingProperties;
                                if (encodingProperties != null)
                                {
                                    foundWidth  = encodingProperties.Width;
                                    foundHeight = encodingProperties.Height;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(DebugTag + "Failed to resolve available resolutions: " + ex.Message);
                        }

                        Debug.WriteLine(DebugTag + "Available resolution: "
                                        + foundWidth + "x" + foundHeight);

                        //if (encodingProperties.Width * encodingProperties.Height > width * height) // Use this to get the resolution with the most pixels
                        if (foundWidth > width) // Use this to get the widest resolution
                        {
                            width           = foundWidth;
                            height          = foundHeight;
                            propertiesToSet = mediaEncodingProperties;
                        }
                    }

                    if (width > 0 && height > 0)
                    {
                        _dataContext.SetFullResolution((int)width, (int)height);
                        int previewWidth  = (int)FilterEffects.DataContext.DefaultPreviewResolutionWidth;
                        int previewHeight = 0;
                        AppUtils.CalculatePreviewResolution((int)width, (int)height, ref previewWidth, ref previewHeight);
                        _dataContext.SetPreviewResolution(previewWidth, previewHeight);
                    }

                    if (propertiesToSet != null)
                    {
                        await _photoCaptureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, propertiesToSet);

                        Debug.WriteLine(DebugTag + "Capture resolution set to "
                                        + width + "x" + height + "!");
                    }
                    else
                    {
                        Debug.WriteLine(DebugTag + "Failed to set capture resolution! Using fallback resolution.");
                        var fallbackResolution = new Size(
                            FilterEffects.DataContext.DefaultPreviewResolutionWidth,
                            FilterEffects.DataContext.DefaultPreviewResolutionHeight);
                        _dataContext.PreviewResolution = fallbackResolution;
                        _dataContext.FullResolution    = fallbackResolution;
                    }
                }

                // Start the camera
                await _photoCaptureManager.StartPreviewAsync();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Reads the given image file and writes it to the buffers while also
        /// scaling a preview image.
        ///
        /// Note that this method can't handle null argument!
        /// </summary>
        /// <param name="file">The selected image file.</param>
        /// <returns>True if successful, false otherwise.</returns>
        private async Task <bool> HandleSelectedImageFileAsync(StorageFile file)
        {
            System.Diagnostics.Debug.WriteLine(DebugTag + "HandleSelectedImageFile(): " + file.Name);
            var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            DataContext dataContext = DataContext.Instance;

            // Reset the streams
            dataContext.ResetStreams();

            var image = new BitmapImage();

            image.SetSource(fileStream);
            int width  = image.PixelWidth;
            int height = image.PixelHeight;

            dataContext.SetFullResolution(width, height);

            int previewWidth  = (int)FilterEffects.DataContext.DefaultPreviewResolutionWidth;
            int previewHeight = 0;

            AppUtils.CalculatePreviewResolution(width, height, ref previewWidth, ref previewHeight);
            dataContext.SetPreviewResolution(previewWidth, previewHeight);

            bool success = false;

            try
            {
                // JPEG images can be used as such
                Stream stream = fileStream.AsStream();
                stream.Position = 0;
                stream.CopyTo(dataContext.FullResolutionStream);
                success = true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(DebugTag
                                                   + "Cannot use stream as such (not probably in JPEG format): " + e.Message);
            }

            if (!success)
            {
                try
                {
                    await AppUtils.FileStreamToJpegStreamAsync(fileStream,
                                                               (IRandomAccessStream)dataContext.FullResolutionStream.AsInputStream());

                    success = true;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(DebugTag
                                                       + "Failed to convert the file stream content into JPEG format: "
                                                       + e.ToString());
                }
            }

            if (success)
            {
                await AppUtils.ScaleImageStreamAsync(
                    dataContext.FullResolutionStream,
                    dataContext.FullResolution,
                    dataContext.PreviewResolutionStream,
                    dataContext.PreviewResolution);

                dataContext.WasCaptured = false;
            }

            return(success);
        }