从Mediacapture UWP将图像保存到文件夹时,可以使用Filewatcher检测照片吗?

时间:2019-07-25 06:30:39

标签: c# uwp

当我在程序中拍摄照片并将其保存在Picturelibrary filewatcher中时不起作用,但是当我将图像复制并粘贴到Picturelibrary filewatcher中时,其工作正常。 请帮助我解决我的问题。 抱歉,我的技能太差

//相机预览

私有异步void BtnCamera_Click_1(对象发送者,RoutedEventArgs e)         {

        DisplayRequest displayRequest = new DisplayRequest();
        Windows.Media.Capture.MediaCapture mediaCapture;
        mediaCapture = new MediaCapture();
        var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
        var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
        await mediaCapture.InitializeAsync(settings);
        displayRequest.RequestActive();
        PreviewControl.Source = mediaCapture;
        await mediaCapture.StartPreviewAsync();
        var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
        var storageFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
        BtnCamera.Visibility = (BtnCamera.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible);
        PauseBtn.Visibility = (PauseBtn.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible);
    }

//保存图片

私有异步无效BtnSave_Click(对象发送者,RoutedEventArgs e)         {

        //var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
        var rtb = new RenderTargetBitmap();
        await rtb.RenderAsync(ImageHolder); // Render control to RenderTargetBitmap

        // Get pixels from RTB
        IBuffer pixelBuffer = await rtb.GetPixelsAsync();
        byte[] pixels = pixelBuffer.ToArray();

        // Support custom DPI
        DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
        var stream = new InMemoryRandomAccessStream();
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, // RGB with alpha
                             BitmapAlphaMode.Premultiplied,
                             (uint)rtb.PixelWidth,
                             (uint)rtb.PixelHeight,
                             displayInformation.RawDpiX,
                             displayInformation.RawDpiY,
                             pixels);

        // Write data to the stream
        stream.Seek(0);
        await encoder.FlushAsync();
        using (var dataReader = new DataReader(stream.GetInputStreamAt(0)))
        {
            StorageFolder folder = KnownFolders.PicturesLibrary;
            StorageFile file = await folder.CreateFileAsync("snapshot" + DateTime.Now.ToString("MM-dd-yyyy ss.fff") + ".jpg", CreationCollisionOption.GenerateUniqueName);
            await dataReader.LoadAsync((uint)stream.Size);
            byte[] buffer = new byte[(int)stream.Size];
            dataReader.ReadBytes(buffer);
            await FileIO.WriteBytesAsync(file, buffer);
            //await file.CopyAsync(folder, "ProfilePhoto.jpg", NameCollisionOption.GenerateUniqueName);
            //await file.DeleteAsync();


        }

// fileWatcher

异步void EnableChangeTracker()         {

        StorageLibrary picsLib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
        StorageLibraryChangeTracker picTracker = picsLib.ChangeTracker;
        picTracker.Enable();
        List<string> supportExtension = new List<string>();
        supportExtension.Add(".png");
        supportExtension.Add(".jpg");

        StorageFolder photos = KnownFolders.PicturesLibrary;
        // Create a query containing all the files your app will be tracking
        QueryOptions option = new QueryOptions(CommonFileQuery.DefaultQuery, supportExtension);
        option.FolderDepth = FolderDepth.Shallow;
        // This is important because you are going to use indexer for notifications
        option.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
        StorageFileQueryResult resultSet = photos.CreateFileQueryWithOptions(option);
        // Indicate to the system the app is ready to change track
        await resultSet.GetFilesAsync();
        // Attach an event handler for when something changes on the system

        resultSet.ContentsChanged += Query_ContentsChangedAsync;
    }




 async void Query_ContentsChangedAsync(IStorageQueryResultBase sender, object args)
    {

    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {




             ImgList.Clear();
             GetFiles();



         });




    }

1 个答案:

答案 0 :(得分:0)

您的代码中有两个问题。

  1. 如果要使用MediaCapture拍摄照片并将其保存到图片库中。实际上,您实际上不需要使用DataReaderRenderTargetBitmap来执行这些额外的操作。仅使用BitmapEncoderBitmapDecoder就足够了。请参见CameraManualControls示例中的“ TakePhotoAsync”方法。如果您说必须使用RenderTargetBitmap,请忽略此建议。
  2. 在图片库中保存新图片时,每次仍然需要调用await resultSet.GetFilesAsync()方法来触发“ ContentsChanged”事件。

因此,更改后的代码如下所示:

private StorageFileQueryResult resultSet;

private async Task EnableChangeTracker()
{
    StorageLibrary picsLib = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
    StorageLibraryChangeTracker picTracker = picsLib.ChangeTracker;
    picTracker.Enable();
    List<string> supportExtension = new List<string>();
    supportExtension.Add(".png");
    supportExtension.Add(".jpg");

    StorageFolder photos = KnownFolders.PicturesLibrary;
    // Create a query containing all the files your app will be tracking
    QueryOptions option = new QueryOptions(CommonFileQuery.DefaultQuery, supportExtension);
    option.FolderDepth = FolderDepth.Shallow;
    // This is important because you are going to use indexer for notifications
    option.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
    resultSet = photos.CreateFileQueryWithOptions(option);
    // Indicate to the system the app is ready to change track

    // Attach an event handler for when something changes on the system
    resultSet.ContentsChanged += ResultSet_ContentsChanged;

    await resultSet.GetFilesAsync();
}
var rtb = new RenderTargetBitmap();
        await rtb.RenderAsync(ImageHolder); // Render control to RenderTargetBitmap

        // Get pixels from RTB
        IBuffer pixelBuffer = await rtb.GetPixelsAsync();
        byte[] pixels = pixelBuffer.ToArray();

        // Support custom DPI
        DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
        StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync("snapshot" + DateTime.Now.ToString("MM-dd-yyyy ss.fff") + ".jpg", CreationCollisionOption.GenerateUniqueName);
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, // RGB with alpha
                                 BitmapAlphaMode.Premultiplied,
                                 (uint)rtb.PixelWidth,
                                 (uint)rtb.PixelHeight,
                                 displayInformation.RawDpiX,
                                 displayInformation.RawDpiY,
                                 pixels);
            await encoder.FlushAsync();
        }
        await resultSet.GetFilesAsync();