Esempio n. 1
0
        private async Task takePhoto_Click()
        {
            try
            {
                photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    PHOTO_FILE_NAME, CreationCollisionOption.GenerateUniqueName);

                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                //takePhoto.IsEnabled = true;
                //status.Text = "Take Photo succeeded: " + photoFile.Path;
                path = photoFile.Path;
                IRandomAccessStream photoStream = await photoFile.OpenReadAsync();

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.SetSource(photoStream);
                    captureImage.Source = bitmap;
                });

                TakeAndSendPicture(photoFile);
            }
            catch (Exception ex)
            {
                Cleanup();
            }
            finally
            {
            }
        }
Esempio n. 2
0
        private async void TakePhoto()
        {
            DeviceInformation cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Front);

            if (cameraDevice == null)
            {
                ErrorText.Text = "No camera";
                return;
            }

            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings {
                VideoDeviceId = cameraDevice.Id
            };

            MediaCapture mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync(settings);

            StorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("MyPhoto", CreationCollisionOption.GenerateUniqueName);

            ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();

            await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

            IRandomAccessStream photoStream = await photoFile.OpenReadAsync();

            BitmapImage bitmap = new BitmapImage();

            bitmap.SetSource(photoStream);
            ImageControl.Source = bitmap;
        }
Esempio n. 3
0
        private async void CreateGroupButtonMethod()
        {
            faceServiceClient = new FaceServiceClient("fbeb228a7f1943b69c3e6e2861f22ff0");

            //var client = new HttpClient();
            //var queryString = WebUtility.UrlEncode(string.Empty);
            string personGroupId = "group1";
            Guid   personId      = new Guid("a3f0bd5c-b917-41f7-b50f-ae6fb2e3c6a2");
            //// Request header
            //client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "fbeb228a7f1943b69c3e6e2861f22ff0");
            //var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/persongroups/" + personGroupId + "/persons/"+ personId +"/persistedFaces" ;

            //HttpResponseMessage response;

            MediaCapture mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            photo = await KnownFolders.PicturesLibrary.CreateFileAsync(
                "capture1.jpg", CreationCollisionOption.ReplaceExisting);

            ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
            await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photo);

            //Request body
            Stream image = await photo.OpenStreamForReadAsync();

            await faceServiceClient.AddPersonFaceAsync(personGroupId, personId, image);

            await faceServiceClient.TrainPersonGroupAsync(personGroupId);


            //var faces = await faceServiceClient.DetectAsync(image);
            //var faceIds = faces.Select(face => face.FaceId).ToArray();

            //var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds);
            //foreach (var identifyResult in results)
            //{
            //    if (identifyResult.Candidates.Length == 0)
            //    {

            //    }
            //    else
            //    {
            //        var candidateId = identifyResult.Candidates[0].PersonId;
            //        var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId);

            //    }
            //}
            //string body = JsonConvert.SerializeObject(new
            //{
            //    url =  photo.Path,
            //});
            //byte[] byteData = Encoding.UTF8.GetBytes(body);

            //using (var content = new ByteArrayContent(byteData))
            //{
            //    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            //    response = await client.PostAsync(uri, content);
            //}
        }
        private async void takePhoto_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnTakePhoto.IsEnabled = false;
                captureImage.Source    = null;
                //store the captured image
                photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    PHOTO_FILE_NAME, CreationCollisionOption.GenerateUniqueName);

                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                btnTakePhoto.IsEnabled = true;
                txtLocation.Text       = "Take Photo succeeded: " + photoFile.Path;
                //display the image
                IRandomAccessStream photoStream = await photoFile.OpenReadAsync();

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(photoStream);
                captureImage.Source = bitmap;
                Picker_SelectedFile = photoFile;
                SelectFile();
            }
            catch (Exception ex)
            {
                txtLocation.Text = ex.Message;
                Cleanup();
            }
        }
Esempio n. 5
0
        async private void CapturePhoto_Click(object sender, RoutedEventArgs e)
        {
            ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
            StorageFile             file      = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                "TestPhoto.jpg",
                CreationCollisionOption.GenerateUniqueName);

            await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);

            BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));


            if (i == 0)
            {
                imagePreivew.Source = bmpImage;
                i++;
            }
            else if (i == 1)
            {
                imagePreivew2.Source = bmpImage;
                i++;
            }
            else if (i == 2)
            {
                imagePreivew3.Source = bmpImage;
                i++;
            }
            else
            {
                imagePreivew.Source = bmpImage;
                i = 1;
            }
        }
Esempio n. 6
0
        async public void OnCapturesCommand(object param)
        {
            MediaCapture takePhotoManager = new MediaCapture();
            await takePhotoManager.InitializeAsync();

            ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
            IStorageFile            file      = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                "Photo.jpg", CreationCollisionOption.GenerateUniqueName);

            await takePhotoManager.CapturePhotoToStorageFileAsync(imgFormat, file);

            //Windows.Storage.StorageFile file = await cameraUI.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(fileStream);

                IGraphInfo graph = this.Info as IGraphInfo;
                NodeVM     node  = new NodeVM();
                node.OffsetX    = ((this.Info as IGraph).ScrollSettings.ScrollInfo.ViewportWidth) / 2;
                node.OffsetY    = ((this.Info as IGraph).ScrollSettings.ScrollInfo.ViewportHeight) / 2;
                node.UnitHeight = 100;
                node.UnitWidth  = 100;
                node.Content    = new Image()
                {
                    Source = bitmap, Stretch = Stretch.Fill
                };
                (Nodes as ObservableCollection <NodeVM>).Add(node);
            }
        }
Esempio n. 7
0
        private async void TakePhotoAsync()
        {
            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync();

            //mediaCapture.Failed += MediaCapture_Failed;

            // Prepare and capture photo
            // 캡쳐한 사진을 바로 XAML에서 보여줌
            var lowLagCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));

            var capturedPhoto = await lowLagCapture.CaptureAsync();

            var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;

            await lowLagCapture.FinishAsync();

            //임시로 저장된 거를 XAML에서 표시
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }

            var source = new SoftwareBitmapSource();
            await source.SetBitmapAsync(softwareBitmap);

            // Set the source of the Image control
            imageControl.Source = source;
        }
Esempio n. 8
0
        private void CaptureCameraSnapshot()
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                animCameraTimer.Stop();
                animCameraTimer.Begin();
            });

            if (_mediaCapture.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming)
            {
                return;
            }
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            try
            {
                IAsyncAction action = _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                action.Completed = (result, status) =>
                {
                    if (status == AsyncStatus.Completed)
                    {
                        OnCapturePhotoCompleted(stream, result, status);
                    }
                };
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
        async private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var vm = this.DataContext as CameraCapturePageViewModel;
                var imageEncodingProps = ImageEncodingProperties.CreatePng();
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(imageEncodingProps, stream);

                    _bytes = new byte[stream.Size];
                    var buffer = await stream.ReadAsync(_bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                    _bytes = buffer.ToArray(0, (int)stream.Size);

                    if (vm.ImageSource == null)
                    {
                        vm.ImageSource = new BitmapImage();
                    }
                    stream.Seek(0);
                    await vm.ImageSource.SetSourceAsync(stream);

                    Retake.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    Take.Visibility   = Windows.UI.Xaml.Visibility.Collapsed;
                    await _mediaCapture.StopPreviewAsync();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 10
0
        private async void CounterCallback(object sender, object e)
        {
            counter--;
            Counter.Text = counter.ToString();
            if (counter == 0)
            {
                dt.Stop();
                if (DFace == null)
                {
                    return;
                }
                var ms = new MemoryStream();
                await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream());

                Point p; Size sz;
                ExpandFaceRect1(DFace.FaceBox, out p, out sz);
                var cb = await CropBitmap.GetCroppedBitmapAsync(ms.AsRandomAccessStream(), p, sz, 1);

                Faces.Add(cb);
                var res = await CallCognitiveFunction(ms);

                ResultImage.Source = new BitmapImage(new Uri(res));
                await WriteableBitmapToStorageFile(cb);

                Counter.Visibility = Visibility.Collapsed;
            }
        }
Esempio n. 11
0
        private async void UploadPhoto()
        {
            uploadTimer.Stop();
            photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(capturedPhotoFile, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

            ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();

            try
            {
                await mediaCaptureManager.CapturePhotoToStorageFileAsync(imageProperties, photoStorageFile);

                var cloudStorageAccount = CloudStorageAccount.Parse(AzureStorageConnString);
                var blobClient          = cloudStorageAccount.CreateCloudBlobClient();
                var container           = blobClient.GetContainerReference("photos");
                await container.CreateIfNotExistsAsync();

                var fileName  = "photo" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
                var blockBlob = container.GetBlockBlobReference(fileName);
                await blockBlob.UploadFromFileAsync(photoStorageFile);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            uploadTimer.Start();
        }
        public async Task <MediaCapture> Initialize()
        {
            var cameraDeviceInfos = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)).Where(d => d.IsEnabled && d.EnclosureLocation != null);

            var frontCamDeviceInfo = cameraDeviceInfos.FirstOrDefault(d => d.EnclosureLocation.Panel == Panel.Front);

            var mediaCaptureInitialization = new MediaCaptureInitializationSettings
            {
                PhotoCaptureSource = PhotoCaptureSource.Auto,
                AudioDeviceId      = string.Empty,
                VideoDeviceId      = frontCamDeviceInfo.Id
            };

            mediaCapture = new MediaCapture();
            await mediaCapture.InitializeAsync(mediaCaptureInitialization);

            mediaCapture.VideoDeviceController.PrimaryUse = CaptureUse.Photo;
            mediaCapture.SetPreviewRotation(VideoRotation.Clockwise270Degrees);

            // Create photo encoding properties as JPEG and set the size that should be used for photo capturing
            imgEncodingProperties = ImageEncodingProperties.CreateJpeg();
            //imgEncodingProperties.Width = 640;
            //imgEncodingProperties.Height = 480;

            return(mediaCapture);
        }
Esempio n. 13
0
        async Task <BitmapImage> TakePictureAsync()
        {
            // https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/basic-photo-video-and-audio-capture-with-mediacapture
            var medCapture = _lstMedCapture[_cameratoUse];
            var imgFmt     = ImageEncodingProperties.CreateJpeg();
            var llCapture  = await medCapture.PrepareLowLagPhotoCaptureAsync(imgFmt);

            var photo = await llCapture.CaptureAsync();

            var bmImage = new BitmapImage();

            await bmImage.SetSourceAsync(photo.Frame);

            await llCapture.FinishAsync();

            return(bmImage);

            //var camCapUI = new CameraCaptureUI();
            //camCapUI.PhotoSettings.AllowCropping = true;
            //camCapUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
            //var storageFile = await camCapUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
            //var bmImage = new BitmapImage();
            //if (storageFile != null)
            //{
            //    using (var strm = await storageFile.OpenReadAsync())
            //    {
            //        bmImage.SetSource(strm);
            //    }
            //}
        }
        private async Task TakePhoto()
        {
            // Set properties of image(jpeg) and Capture a image into a new stream
            ImageEncodingProperties properties = ImageEncodingProperties.CreateJpeg();

            using (IRandomAccessStream ras = new InMemoryRandomAccessStream())
            {
                await this.capture.CapturePhotoToStreamAsync(properties, ras);

                await ras.FlushAsync();

                // Load the image into a BitmapImage set stream to 0 for next photo
                ras.Seek(0);
                var picLocation = new BitmapImage();
                picLocation.SetSource(ras);

                //place into listview
                var img = new Image()
                {
                    Width = 200, Height = 158
                };
                img.Source    = picLocation;
                Image1.Source = picLocation;
                //Clone the stream and use this to run api call
                rasClone = ras.CloneStream();
            }
        }
Esempio n. 15
0
        public async Task <byte[]> CapturePhotoWithOrientationAsync()
        {
            var captureStream = new InMemoryRandomAccessStream();
            var outputStream  = new InMemoryRandomAccessStream();

            try
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);
            }
            catch (Exception ex)
            {
                _loggingService.Warning("Exception when taking a photo: {Ex}", ex);
                await _dialogService.ShowAsync("Could not take a photo. Please try again.");

                return(new byte[0]);
            }

            var decoder = await BitmapDecoder.CreateAsync(captureStream);

            var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

            var cameraOrientation      = _cameraRotationHelper.GetCameraCaptureOrientation();
            var simplePhotoOrientation = _cameraRotationHelper.MirrorOrientation(cameraOrientation);
            var photoOrientation       = _cameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(simplePhotoOrientation);
            var properties             = new BitmapPropertySet {
                { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
            };
            await encoder.BitmapProperties.SetPropertiesAsync(properties);

            await encoder.FlushAsync();

            var rawBytes = await _bitmapConverter.GetBytesFromStream(outputStream);

            return(rawBytes);
        }
Esempio n. 16
0
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            Debug.WriteLine("Taking photo...");
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            try
            {
                var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.ReplaceExisting);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);

                var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

                await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);

                Debug.WriteLine("Photo saved!");
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Takes a photo to and saves to a StorageFile
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PhotoButton_Click(object sender, RoutedEventArgs e)
        {
            if (_previewer.IsPreviewing)
            {
                // Disable the photo button while taking a photo
                PhotoButton.IsEnabled = false;

                var stream = new InMemoryRandomAccessStream();

                try
                {
                    // Take and save the photo
                    var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);

                    await _previewer.MediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);

                    rootPage.NotifyUser("Photo taken, saved to: " + file.Path, NotifyType.StatusMessage);
                }
                catch (Exception ex)
                {
                    // File I/O errors are reported as exceptions.
                    rootPage.NotifyUser("Exception when taking a photo: " + ex.Message, NotifyType.ErrorMessage);
                }

                // Done taking a photo, so re-enable the button
                PhotoButton.IsEnabled = true;
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Основная функция, срабатывающая по таймеру
        /// Распознаёт эмоции
        /// </summary>
        async void GetEmotions(object sender, object e)
        {
            if (!IsFacePresent)
            {
                return;
            }
            dt.Stop();

            var ms = new MemoryStream();

            try
            {
                // Запоминаем фотографию в поток в памяти
                await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream());
            }
            catch { dt.Start(); return; }

            ms.Position = 0L;
            var Emo = await Oxford.RecognizeAsync(ms);

            // ^^^ основной вызов распознавателя эмоций
            if (Emo != null && Emo.Length > 0)
            // если обнаружено одно и более лицо
            {
                var Face = Emo[0]; // берем первое (нулевое) лицо
                                   // Face.Scores - запись с различными эмоциями (Fear,Surprise,...)

                Info.Text = ((int)(100 * Face.Scores.Happiness)).ToString();
            }
            dt.Start(); // перезапускаем таймер
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            // While taking a photo, keep the video button enabled only if the camera supports simultaneosly taking pictures and recording video
            VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;

            // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
            VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;

            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                Debug.WriteLine("Photo taken!");

                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await ReencodeAndSavePhotoAsync(stream, photoOrientation);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }

            // Done taking a photo, so re-enable the button
            VideoButton.IsEnabled = true;
            VideoButton.Opacity   = 1;
        }
Esempio n. 20
0
        public async Task CaptureToFile()
        {
            //<SnippetCaptureToFile>
            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
            //</SnippetCaptureToFile>
        }
Esempio n. 21
0
        private async void takePhoto_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                takePhoto.IsEnabled   = false;
                recordVideo.IsEnabled = false;
                captureImage.Source   = null;

                photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    PHOTO_FILE_NAME, CreationCollisionOption.GenerateUniqueName);

                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                takePhoto.IsEnabled = true;
                status.Text         = "Take Photo succeeded: " + photoFile.Path;

                IRandomAccessStream photoStream = await photoFile.OpenReadAsync();

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(photoStream);
                captureImage.Source = bitmap;
            }
            catch (Exception ex)
            {
                status.Text = ex.Message;
                Cleanup();
            }
            finally
            {
                takePhoto.IsEnabled   = true;
                recordVideo.IsEnabled = true;
            }
        }
Esempio n. 22
0
        //</SnippetHelperOrientationChanged>

        //<SnippetCapturePhotoWithOrientation>
        private async Task CapturePhotoWithOrientationAsync()
        {
            var captureStream = new InMemoryRandomAccessStream();

            try
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
                return;
            }


            var decoder = await BitmapDecoder.CreateAsync(captureStream);

            var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpeg", CreationCollisionOption.GenerateUniqueName);

            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(
                    _rotationHelper.GetCameraCaptureOrientation());
                var properties = new BitmapPropertySet {
                    { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
                };
                await encoder.BitmapProperties.SetPropertiesAsync(properties);

                await encoder.FlushAsync();
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Takes a picture from the webcam
        /// </summary>
        /// <returns>StorageFile of image</returns>
        public async Task <StorageFile> TakePicture()
        {
            try
            {
                //captureImage is our Xaml image control (to preview the picture onscreen)
                CaptureImage.Source = null;

                //gets a reference to the file we're about to write a picture into
                StorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                    "RaspPiSecurityPic.jpg", CreationCollisionOption.GenerateUniqueName);

                //use the MediaCapture object to stream captured photo to a file
                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await MediaCap.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                //show photo onscreen
                IRandomAccessStream photoStream = await photoFile.OpenReadAsync();

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(photoStream);
                CaptureImage.Source = bitmap;

                AppStatus.Text = "Took Photo: " + photoFile.Name;

                return(photoFile);
            }
            catch (Exception ex)
            {
                //write the exception on screen
                AppStatus.Text = "Error taking picture: " + ex.Message;

                return(null);
            }
        }
        /// <summary>
        /// Creates an instance of the AdvancedPhotoCapture, configures it to capture HDR images, and registers for its events
        /// </summary>
        /// <returns></returns>
        private async Task EnableHdrAsync()
        {
            // No work to be done if there already is an AdvancedCapture
            if (_advancedCapture != null)
            {
                return;
            }

            // Explicitly choose HDR mode
            var settings = new AdvancedPhotoCaptureSettings {
                Mode = AdvancedPhotoMode.Hdr
            };

            // Configure the mode
            _mediaCapture.VideoDeviceController.AdvancedPhotoControl.Configure(settings);

            // Prepare for an advanced capture
            _advancedCapture = await _mediaCapture.PrepareAdvancedPhotoCaptureAsync(ImageEncodingProperties.CreateJpeg());

            Debug.WriteLine("Enabled HDR mode");

            // Register for events published by the AdvancedCapture
            _advancedCapture.AllPhotosCaptured += AdvancedCapture_AllPhotosCaptured;
            _advancedCapture.OptionalReferencePhotoCaptured += AdvancedCapture_OptionalReferencePhotoCaptured;
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
            VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;

            // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
            VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;

            var stream = new InMemoryRandomAccessStream();

            Debug.WriteLine("Taking photo...");
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            try
            {
                var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);

                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);

                Debug.WriteLine("Photo saved!");
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }

            // Done taking a photo, so re-enable the button
            VideoButton.IsEnabled = true;
            VideoButton.Opacity   = 1;
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakeNormalPhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");

                // Generate a filename based on the current time
                var fileName = String.Format("SimplePhoto_{0}.jpg", DateTime.Now.ToString("HHmmss"));

                // Get the orientation of the camera at the time of capture
                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                Debug.WriteLine("Photo taken!");

                await ReencodeAndSavePhotoAsync(stream, fileName, photoOrientation);
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }
        }
Esempio n. 27
0
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            CloudBlockBlob blockBlob = createBlob();

            MediaCapture mediaCaptureManager = new MediaCapture();

            mediaCaptureManager.InitializeAsync().ToObservable()
            .ObserveOnDispatcher()
            .SelectMany(_ =>
            {
                previewElement.Source = mediaCaptureManager;
                return(mediaCaptureManager.StartPreviewAsync().ToObservable());
            })
            .Subscribe(_ =>
            {
                Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync("tmp.jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting).ToObservable()
                .Repeat()
                .Delay(TimeSpan.FromSeconds(5))
                .Subscribe(photoStorageFile =>
                {
                    Task.Run(async() => {
                        await mediaCaptureManager.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);
                        await blockBlob.UploadFromFileAsync(photoStorageFile);
                    }).Wait();
                }, ex => Debug.WriteLine(ex.Message));
            });
        }
Esempio n. 28
0
        /// <summary>
        /// Detect face by using local function.
        /// </summary>
        private async Task <InMemoryRandomAccessStream> DetectFaceAsync()
        {
            var imgFormat = ImageEncodingProperties.CreateJpeg();

            while (true)
            {
                try
                {
                    var stream = new InMemoryRandomAccessStream();
                    await mediaCapture.CapturePhotoToStreamAsync(imgFormat, stream);

                    var image = await ImageConverter.ConvertToSoftwareBitmapAsync(stream);

                    detectedFaces = await faceDetector.DetectFacesAsync(image);

                    if (detectedFaces.Count == 0)
                    {
                        continue;
                    }
                    else if (detectedFaces.Count != 1)
                    {
                        Message = "too many faces!";
                    }
                    else
                    {
                        return(stream);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Central button clicked to take a picture
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            await StopCapture();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync(
                Path.Combine(Protocol.NewFaceFolder, UserManager.Instance.CurrentProfile.Name + ".jpg"),
                CreationCollisionOption.ReplaceExisting);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
            PhotoRegistred();
        }
Esempio n. 30
0
        /// <summary>
        /// Start video recording
        /// </summary>
        /// <returns></returns>
        private async Task StartVideoRecordingAsync()
        {
            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => PhotoButton.IsEnabled = false);

                if (_mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported)
                {
                    ImageEncodingProperties imageEncodingProperties = ImageEncodingProperties.CreateJpeg();
                    _lowLagPhotoCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(imageEncodingProperties);

                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => PhotoButton.IsEnabled = true);
                }

                var mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                var folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("Cam360", CreationCollisionOption.OpenIfExists);

                var file = await folder.CreateFileAsync("test.mp4", CreationCollisionOption.GenerateUniqueName);

                await _mediaCapture.StartRecordToStorageFileAsync(mediaEncodingProfile, file);
            }
            catch (Exception ex)
            {
                string errorMessage = string.Format("StartVideoRecording did not complete: {0}", ex.Message);
                Debug.Write(errorMessage);
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    await new MessageDialog(errorMessage).ShowAsync();
                });
            }
        }