【问题标题】:Android Drawable.createFromStream allocated too much memoryAndroid Drawable.createFromStream 分配了太多内存
【发布时间】:2011-08-04 22:58:06
【问题描述】:

我正在通过执行以下操作从 http 流创建 Drawable。

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);

    HttpResponse response = client.execute(get);

    InputStream is = response.getEntity().getContent();

    Drawable drawable = Drawable.createFromStream(is, "offers task");

    return drawable;

我的问题是 Drawable.createFromStream 分配的内存比它应该分配的多得多。我尝试下载的图像是 13k,但 createfromstream 调用分配了 16mb 缓冲区,导致内存不足错误。

E/AndroidRuntime( 8038): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=9066KB, Allocated=7325KB, Bitmap Size=16647KB)

还有其他人遇到过这个问题吗?

【问题讨论】:

  • 我也遇到了同样的问题,还没有找到解决办法。
  • 我遇到的问题实际上是 htc 迅雷没有垃圾收集任何东西然后最终耗尽内存的问题。即使在所有位图上调用 recycle() 也永远不会从本机堆中释放出来。该问题已通过固件更新解决。

标签: android bitmap out-of-memory


【解决方案1】:

在android上加载外部图像的常见做法是根据托管ImageView的大小对图像进行下采样。

步骤: 1、下载原图。

2、使用BitmapFactory.decodeFile(filePath, options)方法获取图片的宽高。

BitmapFactory.Options opt = new BitmapFactory.Options();
BitmapFactory.decodeFile(filePath, opt);
int width = opt.outWidth;
int height = opt.outHeight;

3,做你的数学,锻炼一个 sampleSize,解码文件:

opt = new BitmapFactory.Options();
opt.inSampleSize = theSampleSizeYouWant;
img = BitmapFactory.decodeFile(filePath, opt)

android 编程就像地狱一样。 android 团队似乎不了解 java 的真正含义。这些代码闻起来像 MS C,在其中你需要首先传递一个结构来获取它的大小,自己进行内存分配,再次传递它并得到结果。几乎有成千上万的小陷阱,您必须格外注意才能显示来自网络的图像。 (不要忘记在不再需要图像后使用 recyle() 方法清除内存。android gc 很烂)

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 2015-12-04
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多