.net 禁用StreamImageSource的图像缓存

ajsxfq5m  于 2022-12-20  发布在  .NET
关注(0)|答案(1)|浏览(112)

当我从Uri加载ImageSource时,我可以通过将CachingEnabled属性设置为false来禁用图像缓存。
在XAML中使用Image元素

<Image x:Name="image"/>

下面的代码将加载图像而不进行任何缓存。

var imageUri = "https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";

image.Source = new UriImageSource
{
    Uri = new Uri(imageUri),
    CachingEnabled = false
};

现在我想对StreamImageSource执行相同的操作:

var httpClient = new HttpClient();

image.Source = new StreamImageSource
{
    Stream = async cancellationToken =>
    {
        var response = await httpClient.GetAsync(imageUri, cancellationToken);
        return await response.Content.ReadAsStreamAsync(cancellationToken);
    }
};

似乎没有启用或禁用缓存的属性,我也不希望有任何缓存,但在我的Android设备上,应用程序将图像缓存文件写入FileSystem.CacheDirectory中名为image_manager_disk_cache的文件夹,可以通过

var imageCacheDirectory = Path.Combine(
    FileSystem.CacheDirectory, "image_manager_disk_cache");

if (Directory.Exists(imageCacheDirectory))
{
    foreach (var imageCacheFile in Directory.EnumerateFiles(imageCacheDirectory))
    {
        Debug.WriteLine(imageCacheFile);
    }
}

示例输出为:

[0:] /data/user/0/com.companyname.imagecachetest/cache/image_manager_disk_cache/journal
[0:] /data/user/0/com.companyname.imagecachetest/cache/image_manager_disk_cache/5bcc99fe6930c85add40cfc486ae9a5a0451c08d71c6d3cd679ea26ec0293b9b.0

如何为StreamImageSource禁用此图像缓存?
编辑:我猜这种缓存是由Glide库执行的,Android上.NET MAUI的图像实现使用了这个库。但是我找不到任何关于如何在MAUI应用程序中禁用Glide图像缓存的信息。

ltskdhd1

ltskdhd11#

在浏览. NET MAUI源代码时,我发现
src/Core/AndroidNative/maui/src/main/java/com/microsoft/maui/PlatformInterop.java
相关方法如下。
loadImageFromStream中,cachingEnabled参数总是被设置为true。这在我看来是错误的。我在GitHub上创建了一个问题:https://github.com/dotnet/maui/issues/9773.
二六一行

public static void loadImageFromStream(
    ImageView imageView, InputStream inputStream,
    ImageLoaderCallback callback) {

    RequestBuilder<Drawable> builder = Glide
        .with(imageView)
        .load(inputStream);
    loadInto(builder, imageView, true, callback); // true seems wrong here
}

二三二行

private static void loadInto(
    RequestBuilder<Drawable> builder, ImageView imageView,
    Boolean cachingEnabled, ImageLoaderCallback callback) {

    MauiCustomViewTarget target = new MauiCustomViewTarget(imageView, callback);
    prepare(builder, target, cachingEnabled, callback);
}

二一四线

private static void prepare(
    RequestBuilder<Drawable> builder, Target<Drawable> target,
    Boolean cachingEnabled, ImageLoaderCallback callback) {

    builder = builder
        .error(callback);

    if (!cachingEnabled) {
        builder = builder
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true);
    }

    builder
        .into(target);
}

相关问题