I am working on universal windows app on Windows 10 SDK to draw rectangle on faces recognized in the image.
I am using Win2D to edit the pictures and draw rectangle on it. I am able to read files from the Pictures library but when I try to save the image after editing it gives the following error:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
The following is the method I used to draw rectangle on the image:
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);*/
}
}
The exception is thrown at the last line offscreen.SaveAsync.
The stack trace for the above error is:
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()
I have set the permissions for accessing the pictures folders in the appmanifest file.
Do I need to set some additional permissions to save the image in the disk.
The same error occurs when I tried to save the image in any other location.
Try to access the file by the stream, not the path:
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);
}
}
In UWP if you access files via path, you will likely get Access Denied in many cases, it should be done via StorageFile.
来源:https://stackoverflow.com/questions/42599136/access-denied-while-saving-image-in-uwp-access-is-denied-exception-from-hresul