Android Drawable.createFromStream分配了太多内存

Bri*_*fey 6 android bitmap out-of-memory

我通过执行以下操作从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;
Run Code Online (Sandbox Code Playgroud)

我的问题是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)
Run Code Online (Sandbox Code Playgroud)

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

wan*_*gii 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;
Run Code Online (Sandbox Code Playgroud)

3、计算一下,计算出样本大小,然后解码文件:

opt = new BitmapFactory.Options();
opt.inSampleSize = theSampleSizeYouWant;
img = BitmapFactory.decodeFile(filePath, opt)
Run Code Online (Sandbox Code Playgroud)

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