简体   繁体   中英

How does C# interface with Visual Studio to access image files?

I have images imported into a folder in my Solution and I am using SkiaSharp graphics, but I want to use the images from the folder in my solution to create a bitmap which would then be drawn on my canvas. My question is how do I do this?

My code currently is this:

21           SKImage image = SKImage.FromEncodedData(@"C:\RPS Sim\Objects\Images\rock.png");
22           SKBitmap bm = SKBitmap.FromImage(image);
23           canvas.DrawBitmap(bm, new SKPoint(posMov.x,posMov.y));

When I run this code, I get the following error:

System.ArgumentNullException
  HResult=0x80004003
  Message=Value cannot be null.
Parameter name: image
  Source=SkiaSharp
  StackTrace:
   at SkiaSharp.SKBitmap.FromImage(SKImage image)
   at RPS_Sim.Objects.Rock..ctor(Single x, Single y, Single speed, Single size) in C:\RPS Sim\Objects\Rock.cs:line 22
   at RPS_Sim.MainPage..ctor() in C:\RPS Sim\MainPage.xaml.cs:line 33
   at RPS_Sim.App..ctor() in C:\RPS Sim\App.xaml.cs:line 13
   at RPS_Sim.UWP.MainPage..ctor() in C:\RPS Sim\RPS Sim.UWP\MainPage.xaml.cs:line 24

I've not been able to find good sources for understanding how Visual Studio and C# access files, so any help is appreciated.

File paths in my code are accurate, but they have been edited here so as to not hold personal information

First, UWP apps run in a sandbox, and UWP apps are isolated from the system. If you want to get files in a UWP application, you need to use Windows Runtime APIs, such as Windows.Storage Namespace . Your behavior is because you are using .net API ( SKImage.FromEncodedData ) to get file by Path, but it is not allowed in UWP app.

Second, UWP applications have some limitations when accessing system resources such as files. By default, UWP apps can access certain locations, such as the application data location. If you want to access other places like the picture gallery, you need to declare a capability in your UWP app's mainfest file or Open files and folders with a picker . More info here: File Access Permissions.

If you really need to access files where UWP apps can't, or you want to get files by path, you need to use the restricted feature - broadFileSystemAccess . Add this capability in your app's manifest file and enable it in Settings > Privacy > Filesystem after deploying your app.

After getting the file, use the StorageFile.OpenAsync method to get the stream. Then convert the stream to System.IO.Stream , and call the result Stream in SKImage.FromEncodedData to get the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM