Search code examples
windows-phonewindows-phone-8.1

Cannot display captured photo


I am trying to build a camera app. I am able to take the photo and save it.

But heres the twist. If I save the photo in ApplicationData.Current.LocalFolder , I am able to display it in Image control. But when I save it in KnownFolders.CameraRoll the Image control doesnt load the photo.

The photo is displayed in the phone's gallery (Photos), so its not that the file is not created. I've added Pictures Library capability too. Theres not even an exception!

    async private void Capture_Photo_Click(object sender, RoutedEventArgs e)
    {
        //Create JPEG image Encoding format for storing image in JPEG type
        ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();

        //create storage file in local app storage
        //StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Photo.jpg",CreationCollisionOption.ReplaceExisting);

        //// create storage file in Picture Library
        StorageFile file = await KnownFolders.CameraRoll.CreateFileAsync("Photo.jpg", CreationCollisionOption.GenerateUniqueName);


        // take photo and store it on file location.
        await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);

        // Get photo as a BitmapImage using storage file path.
        BitmapImage img = new BitmapImage();

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

        // show captured image on Image UIElement.
        imagePreivew.Source = bmpImage;
    }

Solution

  • It's different when access the file PicturLibrary. We need to load the file stream with required access mode by calling StorageFile.OpenAsync(FileAccessMode).

    Change your code to the following you work:

    async private void Capture_Photo_Click(object sender, RoutedEventArgs e)
    {
            //Create JPEG image Encoding format for storing image in JPEG type
            ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
    
            //create storage file in local app storage
            //StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Photo.jpg",CreationCollisionOption.ReplaceExisting);
    
            //// create storage file in Picture Library
            StorageFile file = await KnownFolders.CameraRoll.CreateFileAsync("Photo.jpg", CreationCollisionOption.GenerateUniqueName);
    
    
            // take photo and store it on file location.
            await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);
    
            var picstream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
    
    
            BitmapImage img = new BitmapImage();
    
            img.SetSource(picstream);
    
            imagePreivew.Source = img;
    }