我的应用程序从 SD 卡解码大量位图,因此我想重用现有位图以减少 GC 工作。我看到来自 Android Training 的示例和 this video它非常适合 BitmapFactory.decodeResource , 但不适用于 BitmapFactory.decodeFile .我使用下一个代码:
private void testBitmapReusing() {
BitmapFactory.Options options = newOptions();
Bitmap bitmap = decode(options);
options.inBitmap = bitmap;
bitmap = decode(options);
}
private BitmapFactory.Options newOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inMutable = true;
return options;
}
private Bitmap decode(BitmapFactory.Options options) {
return BitmapFactory.decodeFile("/mnt/sdcard/sun.jpg", options);
// return BitmapFactory.decodeResource(getResources(), R.drawable.sun, options);
}
注释代码 (BitmapFactory.decodeResource
) 按预期工作,它使用现有位图解码新位图。但是未注释的代码 (BitmapFactory.decodeFile
) 不会解码新的位图。它只是写入日志消息“E/BitmapFactory:无法解码流:java.lang.IllegalArgumentException:解码到现有位图时出现问题”
那么我的错误在哪里呢?
更新 我意识到我的失败。我尝试解码 GIF 图像,但不可能重用 GIF 格式的位图。 docs says :
The source content must be in jpeg or png format (whether as a resource or as a stream)
最佳答案
它可能不是您要直接查找的内容,但替代方法是创建一个 Map(例如 HashMap)并在调用资源时立即将其添加到其中。像这样:
HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();
public Bitmap loadBitmap(String location) {
if (map.containsKey(location))
return map.get(location);
Bitmap bmp = yourDecodeMethod(location);
map.put(location, bmp);
return bmp;
}
这与我不想每次都重新加载资源时使用的方式相同。抱歉,如果这不是您想做的,我已尽力了解您的实际目标:)
祝你好运!
关于android - 为 BitmapFactory.decodeFile 和 BitmapFactory.Options.inBitmap 重用位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412875/