Android Drawable.createFromStream allocates too much memory

I am creating a Drawable from an http stream by following these steps.

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; 

My problem is that Drawable.createFromStream allocates a lot more memory than it should. The image I'm trying to load is 13k, but a call to createfromstream allocates a 16mb buffer that causes an error from memory.

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

Anyone else run into this issue?

+4
source share
1 answer

The usual practice of uploading external images to android is to reduce the selection of images according to the size of the ImageView hosting.

steps: 1, download the original image.

2, use the BitmapFactory.decodeFile (filePath, options) method to get the width and height of the image.

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

3, do your math, train with the sample and decrypt the file:

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

Android programming is like hell. The android team does not seem to understand what Java is. the codes smell like MS C, in which you first need to pass the structure in order to get its size, make the memory allocation yourself, transfer it again and get the result. There are almost thousands of small traps that you must pay close attention to in order to display an image from the web. (Remember to use the recyle () method to clear the memory after the image is no longer needed. android gc sucks)

+1
source

Source: https://habr.com/ru/post/1347959/


All Articles