【问题标题】:Failed to allocate using bitmap - Android使用位图分配失败 - Android
【发布时间】:2017-05-23 14:41:17
【问题描述】:

我尝试在 UI 上应用一些图像。我使用 bitmap 来实现这一点,因为我没有任何空间可以使用简单的 setImageResource 。 问题是分配失败。

java.lang.OutOfMemoryError: 无法分配 93600012 字节分配,其中 16765312 个可用字节和 70MB 直到 OOM

如果你能帮我解决这个问题,我会很高兴。

int imgResource = item.getIcon(); // for example imgResource = R.drawable.test
Drawable drawable = context.getResources().getDrawable(imgResource); //Here I get the error 
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
holder.iv.setImageBitmap(bitmap);

谢谢!

【问题讨论】:

  • 图片有多大? (宽 x 高)
  • @SteveSmith 这段代码是函数的一部分,函数获取25张图片,每张图片都不一样。
  • 是否需要同时显示所有 25 张图片?如果没有,您可能需要在它们完成后回收它们。
  • 我猜你正在尝试将图像加载到列表中,那么你为什么不试试Picasso

标签: java android bitmap allocation


【解决方案1】:

试试这个方法。添加android:largeHeap="true"

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

使用此方法并传递上下文和图像文件名:

public Bitmap getAssetImage(Context context, String filename) throws IOException {
    AssetManager assets = context.getResources().getAssets();
    InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
    Bitmap bitmap = BitmapFactory.decodeStream(buffer);
    return bitmap;
   // return new BitmapDrawable(context.getResources(), bitmap);
}

【讨论】:

  • 我试试看,蝙蝠这不是处理这个问题的“最佳”答案,因为它仍然充满了所有的内存。
  • 我试试看但是现在所有的图像都是白色的。你知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 2016-05-01
  • 2011-12-12
  • 2011-08-23
  • 2014-03-03
  • 2017-12-04
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多