从 Glide 库中的缓存中删除图像

问题描述:

我在我的一个项目中使用 Glide 来显示文件中的图像.

I am using Glide in one of my projects to show image from file.

以下是我如何显示图像的代码:

Below is my code how I am showing the image:

Glide.with(DemoActivity.this)
     .load(Uri.parse("file://" + imagePath))
     .into(mImage);

此位置的图像 (imagePath) 不断变化.默认情况下,Glide 缓存它在 ImageView 中显示的图像.正因为如此,Glide 会显示缓存中的第一张图片,用于该位置的新图片.

The image at this location(imagePath) keeps on changing. By default Glide cache the image it shows in the ImageView. Because of this, the Glide was showing the first image from cache for new images at that location.

如果我将位置 imagePath 处的图像更改为其他具有相同名称的图像,则 Glide 将显示第一个图像而不是新图像.

If I change the image at location imagePath with some other image having same name then the Glide is showing the first image instead of new one.

两个查询是:

  1. 是否可以始终从文件中获取图像而不缓存?这样问题就解决了.

  1. Is it possible to always the image from File and not cache? This way problem will be solved.

是否可以在获取新替换的图像之前从缓存中清除图像?这也将解决问题.

Is it possible to clear image from cache before getting newly replaced image? This will also solve the problem.

我就是这样解决这个问题的.

This is how I solved this problem.

方法 1:当 URL 随图片变化而变化时

Glide.with(DemoActivity.this)
    .load(Uri.parse("file://" + imagePath))
    .diskCacheStrategy(DiskCacheStrategy.NONE)
    .skipMemoryCache(true)
    .into(mImage);

diskCacheStrategy() 可用于处理磁盘缓存,您可以使用 skipMemoryCache() 方法跳过内存缓存.

diskCacheStrategy() can be used to handle the disk cache and you can skip the memory cache using skipMemoryCache() method.

方法二:URL不变,图片却变了

如果您的 URL 保持不变,那么您需要使用签名来缓存图像.

If your URL remains constant then you need to use Signature for image cache.

Glide.with(yourFragment)
     .load(yourFileDataModel)
     .signature(new StringSignature(yourVersionMetadata))
     .into(yourImageView);

Glide signature() 为您提供了将附加数据与缓存密钥混合的能力.

Glide signature() offers you the capability to mix additional data with the cache key.

  • 如果您要从媒体商店获取内容,则可以使用 MediaStoreSignature.MediaStoreSignature 允许您将媒体商店项目的日期修改时间、mime 类型和方向混合到缓存键中.这三个属性可靠地捕获编辑和更新,允许您缓存媒体商店缩略图.
  • 对于保存为文件的内容,您也可以StringSignature 混合文件日期修改时间.
  • You can use MediaStoreSignature if you are fetching content from media store. MediaStoreSignature allows you to mix the date modified time, mime type, and orientation of a media store item into the cache key. These three attributes reliably catch edits and updates allowing you to cache media store thumbs.
  • You may StringSignature as well for content saved as Files to mix the file date modified time.