如何在 Android 中减少图像的内存使用

How to reduce memory usage of image in Android

我有一个屏幕,我必须在屏幕上显示两个相似的图像。这两个图像的大小都是动态的,但它们覆盖了大部分屏幕。当我在我的应用程序中导航到此屏幕时,我在 AndroidStudio 的内存监视器中看到一个 12MB 的尖峰,这意味着这两个图像都在使用该 12MB,因为该屏幕上没有其他 UI 元素并且这两个图像相似takes takes equal amount of screen space,我猜每个显示时消耗 6MB 内存。这两个图像的尺寸均为 1174 x 1174 像素,在 res 目录中大小为 396KB。

我尝试过使用 Glide,但当这些图像也通过 Glide 加载时,我看到了相同的内存峰值。如果应用程序试图占用比可用内存更多的内存并且在我的应用程序的其他部分大量使用图像,即使 Glide 也无能为力。所以总是存在内存紧缩,我在显示这两个图像的应用程序中遇到很多 OutOfMemory 异常。

所以我的问题是如何减少这些图像的内存使用量?另外为什么res文件夹中的图片大小为396KB却占用6MB内存?

我猜你没有压缩你的图片,使用 https://github.com/zetbaitsu/Compressor 非常擅长图片压缩。我也猜你确实使用了 Glide 缓存策略。

然而,Glide 会缓存原始的全分辨率图像以及该图像的较小版本。例如,如果您请求一张 1000x1000 像素的图像,而您的 ImageView 是 500x500 像素,Glide 会将这两个版本的图像放入缓存中。

  1. DiskCacheStrategy.NONE 不缓存任何内容,正如所讨论的那样
  2. DiskCacheStrategy.SOURCE 仅缓存原始全分辨率图像。在我们上面的示例中,这将是 1000x1000 像素的
  3. DiskCacheStrategy.RESULT 只缓存最终图像,减少后 分辨率(以及可能的转换)(默认行为)
  4. DiskCacheStrategy.ALL 缓存图像的所有版本

To answer your answer you need to manually keep track of the cache volume in android.Try forcing an garbage collection,Normally, VMs perform garbage collection only when absolutely needed, since it’s expensive. However, it can be useful to force garbage collection in certain circumstances. For example, when locating memory leaks, if you want to determine whether a large object was successfully released already, you can initiate garbage collection much more aggressively than usual.

希望这对您有所帮助。