Win10 保存Element到相册

时间:2024-01-20 17:22:35

保存控件到相册

private async void saveImg_Click(object sender, RoutedEventArgs e)
{
StorageFolder savedPics = KnownFolders.SavedPictures;

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(GridImage);
IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
StorageFile newfile = await savedPics.CreateFileAsync(string.Format(
"{0}_{1}.jpg",
DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"),
Guid.NewGuid()),CreationCollisionOption.ReplaceExisting);
using (var writeStream = await newfile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder jpgencode = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, writeStream);
byte[] data = buffer.ToArray();
jpgencode.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
96d,96d,data);
await jpgencode.FlushAsync();
}

}

打开相册 相机等

private async void openCamera_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
string Text = "Picked photo: " + file.Name;

using (var outputStream = await file.OpenReadAsync())
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(outputStream);

//GridImage is Grid
GridImage.Background = new ImageBrush() { ImageSource = bmp };
}
}
}

未验证

private async Task SaveWriteableBitmapAsJpeg(WriteableBitmap bmp, string fileName)
{
// Create file in Pictures library and write jpeg to it
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
var outputFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
await EncodeWriteableBitmap(bmp, writeStream, BitmapEncoder.JpegEncoderId);
}
}

private async Task EncodeWriteableBitmap(WriteableBitmap bmp, IRandomAccessStream writeStream, Guid encoderId)
{
// Copy buffer to pixels
byte[] pixels;
using (var stream = bmp.PixelBuffer.AsStream())
{
pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
}

// Encode pixels into stream
var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
(uint)bmp.PixelWidth, (uint)bmp.PixelHeight,
96, 96, pixels);
await encoder.FlushAsync();
}

最后在Package.appxmanifest里添加权限

<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="picturesLibrary"/>
</Capabilities>