gpt4 book ai didi

android - BitmapFactory.Options.inTempStorage 字段

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:13 26 4
gpt4 key购买 nike

我有一个通过在 Canvas 上绘制位图图 block 实现的自定义离线 map 。我试图消除对象创建以减少 GC 运行,从而使 map 滚动更顺畅。我在 Allocation Tracker 中看到 BitmapFactory.decodeFile(...) 总是创建 byte[16400] 对象。我认为设置 BitmapFactory.Options 的 inTempStorage 字段会改变这一点:

byte[] buffer = new byte[16*1024];
// ...
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
options.inTempStorage = buffer;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

但即使使用这段代码,我仍然看到 decodeFile 创建了 byte[] 数组。那有什么问题呢?

最佳答案

简而言之,问题在于当您使用 BitmapFactory.decodeFile(String, Options) 时,Android 将独立于 options 分配一个 16 kB BufferedInputStream .inTempStorage.

更详细地说:BitmapFactory.decodeFile(String, Options)BitmapFactory.decodeStream(InputStream, Rect, Options) 的包装器,它使用 文件输入流。在 BitmapFactory.decodeStream(InputStream, Rect, Options) 的实现中,有 this code :

public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
// ...

// we need mark/reset to work properly
if (!is.markSupported()) {
is = new BufferedInputStream(is, 16 * 1024);
}

// ...
}

由于 FileInputStreammarkSupported() 返回 false,这意味着独立于 options.inTempStorage,如果您使用 BitmapFactory.decodeFile(String, Options),将为您创建一个带有 16 kB 缓冲区的 BufferedInputStream

为了避免这 16 kB 的分配,您可以尝试将 BitmapFactory.decodeStream(InputStream, Rect, Options) 直接与 InputStream 一起使用,其中 markSupported( ) 返回 true

我可以想到两个值得研究的备选方案:

  1. 使用您自己的具有较小缓冲区的 BufferedInputStream
  2. 使用 AssetManager.open(...) 返回的 AssetManager.AssetInputStream (有关如何使用它的信息,请参阅我的回答 here)。它的 markSupported() 返回 true

第一个选择可能没有多大帮助,您仍将分配一个 byte[] 数组,但至少它在您的控制之下。如果您的情况允许您使用这种方法,那么第二种选择可能是最有成效的。

关于android - BitmapFactory.Options.inTempStorage 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5523552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com