我正在 Windows 10 SDK 上开发通用 Windows 应用程序,以便在图像中识别的面部上绘制矩形。
我正在使用Win2D编辑图片并在其上绘制矩形。我可以从图片库中读取文件,但是当我尝试在编辑后保存图像时,会出现以下错误:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
以下是我在图像上绘制矩形的方法:
private async void DrawRect()
{
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasBitmap bitmap = null;
CanvasRenderTarget offscreen = null;
Windows.Storage.StorageFile photofile = await KnownFolders.PicturesLibrary.GetFileAsync("image.jpg");
if(photofile != null)
{
using (var stream = await photofile.OpenReadAsync())
{
bitmap = await CanvasBitmap.LoadAsync(device, stream);
}
}
if(bitmap != null)
{
offscreen = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, 96);
using (var ds = offscreen.CreateDrawingSession())
{
ds.Clear(Colors.Transparent);
ds.DrawImage(bitmap);
ds.DrawRectangle(25, 35, 270, 352, Colors.Blue,4);
}
var photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("image2.jpg", CreationCollisionOption.ReplaceExisting);
if (photofile != null)
{
await offscreen.SaveAsync(photofile.Path);
}
//await offscreen.SaveAsync(photoFile.Path);*/
}
}
在最后一行 offscreen.SaveAsync 处抛出异常。
上述错误的堆栈跟踪是:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at IdentifyFacesApp.IdentifiedFaces.d__5.MoveNext()
我已经在appmanifest文件中设置了访问图片文件夹的权限。
我是否需要设置一些额外的权限才能将图像保存在磁盘中。
当我尝试将图像保存在任何其他位置时,也会发生同样的错误。
最佳答案
尝试通过流而不是路径访问文件:
var photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("image2.jpg", CreationCollisionOption.ReplaceExisting);
if (photofile != null)
{
using (var stream = await photofile.OpenAsync(FileAccessMode.ReadWrite))
{
await offscreen.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg);
}
}
在 UWP 中,如果您通过路径访问文件,在许多情况下您可能会遇到访问被拒绝的情况,应该通过StorageFile来完成。
关于c# - 在 UWP 中保存图像时访问被拒绝。访问被拒绝。 (HRESULT : 0x80070005 (E_ACCESSDENIED)) 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599136/