将照片保存到应用的缓存UWP c#

时间:2016-08-24 09:26:52

标签: c# caching camera uwp

我正在使用MediaCapture API进行捕获。但我不知道如何将照片保存到应用程序的缓存中,而不是设备上的文件夹。

private async void btnPhoto_Click(object sender, RoutedEventArgs e)
{
    // This is where we want to save to.
    var storageFolder = KnownFolders.SavedPictures;

    // Create the file that we're going to save the photo to.
    var file = await storageFolder.CreateFileAsync("sample.jpg", CreationCollisionOption.GenerateUniqueName);

    // Update the file with the contents of the photograph.         
    await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);
}

用户最多可以拍摄5张照片并将其发送到服务器,因此无需在设备上保存照片。我该如何实施呢?

2 个答案:

答案 0 :(得分:0)

使用ApplicationData.LocalFolder保存图片。

答案 1 :(得分:0)

  

但我不知道如何将照片保存到应用程序的缓存中,而不是设备上的文件夹。

我建议您使用ApplicationData.TemporaryFolder创建临时StorageFile:

var file=await ApplicationData.Current.TemporaryFolder.CreateFileAsync("sample.jpg", CreationCollisionOption.GenerateUniqueName);

它将为磁盘中的缓存创建临时文件。系统维护任务将随时自动删除这些文件。用户也可以删除这些文件使用磁盘清理。

如果你真的不想在磁盘上创建任何文件。您可以使用InMemoryRandomAccessStream缓存照片:

var stream = new InMemoryRandomAccessStream();
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

如果您想在自己的应用中展示照片,请将照片保存到SoftwareBitmap

//save the photo to softwareBitmap:
var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));
var capturePhoto = await lowLagCapture.CaptureAsync();
SoftwareBitmap softwareBitmap = capturePhoto.Frame.SoftwareBitmap;
await lowLagCapture.FinishAsync();

//load the image in image tag:
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);
mainPageImage.Source = source;//mainPageImage is the image tag name