我正在使用WinRT应用程序,出于某种原因,我想使用FileSavePicker将XAML树保存为图像。目前我正在将图像保存在ApplicationData中,这对于之后的浏览非常繁忙。我想要的是,用户选择自己选择的目录和名称并保存图像。我现在正在使用以下代码:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MainGrid);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Image.png", creationCollisionOption.ReplaceExisting);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight, 96d, 96d,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
答案 0 :(得分:1)
像这样更改你的代码
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MainGrid);
var file = await DestinationFileFromUserAsync();
if (file != null)
{
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight, 96d, 96d,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
}
private async Task<StorageFile> DestinationFileFromUserAsync()
{
if (EnsureUnsnapped())
{
StorageFile file = null;
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("Images", new List<string>() { ".jpg", ".jpeg", ".png"});
savePicker.SuggestedFileName = "New Image";
file = await savePicker.PickSaveFileAsync();
return file;
}
else
{
return null;
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
return ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
}