YMC
YMC

Reputation: 5462

Image from AppDataDirectory failed to be displayed in the Image view

When my .net maui app starts it loads some images from the cloud and stores to FileSystem.AppDataDirectory folder. Then in offline mode it supposed to take them from the folder to display in the Image view, but the code does not work (binding will be used, but for the demo sake it's hardcoded):

    <Image WidthRequest="30" HeightRequest="30">
        <Image.Source>
            <FileImageSource File="/data/user/0/mytestapp/files/Icontest.svg" />
        </Image.Source>
    </Image>

Same image works fine if loaded from the cloud when I replace File source to Url source.

/data/user/0/mytestapp/files/ is what FileSystem.AppDataDirectory call returns, I just added file name to the end

Any idea if it's supported at all to load image files from the folder?

note: caching with url source does not serve the app requirements.

Upvotes: 0

Views: 917

Answers (2)

Liyun Zhang - MSFT
Liyun Zhang - MSFT

Reputation: 14244

At first, the Image control can't get the file from the device's external storage directly. The FileImageSource is used to get the image file in the project which is set as embedded resource.

So you can need to use a stream to read the file and then use the ImageSource.FromStream to set the image source. Such as:

var memoryStream = new MemoryStream();
using (var source = System.IO.File.OpenRead(path))
{
   source.CopyTo(memoryStream);
}
image.Source = ImageSource.FromStream(() => memoryStream)

But there is a bug about ImageSource is not work when set Image.Source to file in external storage. Even the image file has been read as a stream, the image will not display. You can follow up this issue on the github.

Upvotes: 1

H.A.H.
H.A.H.

Reputation: 3897

SVG get pre-rendered and ship with your app. You have to reference them as PNG in your XAML. (On IOS, it wont even display if you use .svg) But this is not it.

Once replace your SVG resources with PNG. You will hit another problem.

The android will cache your files in your file system, and there is nothing you can do about it: https://github.com/dotnet/maui/issues/9773

There are two work arounds:

  1. Change the name of the file every time, so it is never found.
  2. Clear the cache by deleting everything from here: Path.Combine(FileSystem.CacheDirectory, "image_manager_disk_cache");

I think the negative effects of both workarounds are obvious. Fingers crossed that it gets fixed next year.

Upvotes: 1

Related Questions