UWP 保存Image的图片到本地文件

时间:2024-06-20 16:07:44

上一篇说显示一张图片到Image控件,比较简单。

那个假设我Image控件有图片了,想保存到本地,这个就要花心思了,不过也不复杂的。。。

        var rtb = new RenderTargetBitmap();
await rtb.RenderAsync(imgCover); var saveFile = new FileSavePicker();
saveFile.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
saveFile.FileTypeChoices.Add("JPEG files", new List<string>() { ".jpg" });
saveFile.SuggestedFileName = “Test”;
StorageFile sFile = await saveFile.PickSaveFileAsync();
if (sFile == null)
return; var pixels = await rtb.GetPixelsAsync();
using (IRandomAccessStream stream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
,
,
bytes); await encoder.FlushAsync();
}
imgCover是Image控件。