Bitmap size exceeds VM budget, not understanding why - android

I've looked all over for "Bitmap size exceeds VM budget" problems, but none of the solutions seem applicable for me. I am not understanding why my program sometimes throws this error because they way I'm using it doesn't seem to cause any possible memory leaks. My stack traces are pointing to the BitmapFactory.decodeResource() method. I've got a background image that I'm using to draw on a Canvas and this is how I've been initializing it:
Bitmap backgroundImage = BitmapFactory.decodeResource(getResources(),
R.drawable.background);
backgroundImage = resizeImage(backgroundImage, w, h);
This is how I've been using it:
canvas.drawBitmap(backgroundImage, 0, 0, paint);
I thought that putting backgroundImage = null in the onDestroy method would help, but that did nothing. There is not other reference to the background image resource in my program except in an XML file, but I don't think that affects it. Could someone explain to me why this is happening and how to fix it?
By the way, there is not screen orientation changes involved in this app.

You need to free the bitmap pixels when you're done with it. You mentioned that you set its value to null, but that only makes it eligible for GC, it does not explicitly tell the VM that you're done with those pixels, and that now is a good time to free them.
Before you set it to null, simply call Bitmap#recycle() on the Bitmap:
protected void onDestroy() {
if (this.backgroundImage != null) {
this.backgroundImage.recycle();
this.backgroundImage = null;
}
}
Additionally, you may be wasting resources in your resizeImage() method, which you did not provide code for. It's much more efficient to do proper down-sampling of the Bitmap at decode-time, rather than loading the full-size Bitmap, and then scaling it down from there.
The general technique is to use the 3-argument version of BitmapFactory.decodeResource(), with BitmapFactory.Options#inJustDecodeBounds for a first-time-pass in order to get the width/height of the Bitmap (although in your case, since it comes from the app's resources, there's no reason you should even have to do that.. but I'll explain it anyway); then determine a proper samplesize based on the target size, and decode the bitmap a second time. That usually results in much less memory usage, especially for very large images (e.g., with inSampleSize set to 2, it decodes the full-size Bitmap, but only allocates enough memory for a Bitmap of half the original size, downscaling the Bitmap in the process).

Related

Should I trust the Garbage Collector after calling Bitmap.recycle()?

I have some code which is loading an image into an OpenGL texture. In the process, I end up loading 3 bitmaps, since I need to load the original bitmap (sized appropriately for the display) and reorient the bitmap based on EXIF data. I'm very quickly calling .recycle() on each bitmap, but I'm noticing that my memory doesn't seem to change.
Here's what the Memory Monitor shows:
As you can see, after loading the image I'm using about 60MB of memory. When I rotate the device that drops off a bit then comes back up. That leads me to think there is no leak, since the memory never goes above that.
When I click the GC button in the memory analyzer, my memory footprint drops dramatically to around 8 MB. This makes sense as the three bitmaps created during the process were recycled, so can be garbage collected. Then you can see that when I rotate again and the activity is rebuilt, the memory jumps right back up.
Here's my code to show you why so many bitmaps are created and when they're recycled.
void layoutImage() {
...
Bitmap bitmap = loadOrientedConstrainedBitmapWithBackouts(...);
imageTexture = new GLTexture(bitmap);
bitmap.recycle(); // recycle bitmap 2
}
Bitmap loadOrientedConstrainedBitmapWithBackouts(Context context, Uri uri, int maxSize) {
...
Bitmap bitmap = loadBitmapWithBackouts(context, uri, sampleSize); // create bitmap 1
...
Bitmap out = orientBitmap(bitmap, orientation); // create bitmap 2
bitmap.recycle(); // recycle bitmap 1
return out;
}
Bitmap orientBitmap(Bitmap source, int orientation) {
...
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight, matrix, true); // create bitmap 3
}
I'm not really sure that this is a problem, so to speak, since the memory isn't climbing (so no leak), but I'm curious when it stays so high. Since forcing a garbage collection clears it just fine, should I assume that if the system needs that memory it will be collected on the next GC pass? It's been running the whole time I've been writing this and is still sitting comfortably at 60 MB.
Question 1: Can I just trust that the garbage collector will take that memory back if needed?
Also, if we're supposed to be so judiciously recycling our bitmaps, why do so many of the Bitmap methods say things like "The new bitmap may be the same object as source, or a copy may have been made." Do I really have to check the equality every time I use those methods to recycle the bitmap if it's a different object?
Question 2: When using Bitmap creation methods, that may or may not return the same bitmap or a copy, do I need to check source and output equality to recycle the source if it's a copy?
Edit:
I have tried analyzing this with MAT, using a heap dump at peak usage (should be 60 MB), but it only reports 18.2 MB of usage and nothing unusual looking. Could they be reading things differently?
Question 1: Can I just trust that the garbage collector will take that memory back if needed?
Yes. If the incoming references are cleared, the garbage collector will take the memory when it is needed (typically for a new allocation). Calling recycle() doesn't help this process along or make it happen any faster.
The recycle() method exists because Bitmap objects were not counted against the heap until Android 3.0; so the method was helpful to assist the GC since it didn't otherwise have a record of that memory counted against its heap. In 3.0+, the memory is tracked against the heap so this extra bookkeeping isn't necessary anymore.
Question 2: When using Bitmap creation methods, that may or may not return the same bitmap or a copy, do I need to check source and output equality to recycle the source if it's a copy?
The createBitmap() method will return the same object if:
The source is immutable
x and y are both zero
width and height match the source width and height
No transformation matrices have been applied
Since it looks like you are passing in a transformation matrix, you will always get a copy unless the matrix is identity for some reason. But again, no real need to recycle() unless you are still supporting 2.x versions.

Resize an image on Android

after googling a lot I have not yet found a way to resize an image preserving quality.
I have my image - stored by camera in full resolution - in
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/my_directory/my_file_name.jpg";
Now, I need to resize it preserving aspect ratio and then save to another path.
What's the best way to do this without occurring the error "Out of memory on a xxxxxxx-byte allocation."?
I continue to retrieve this error on Samsung devices, I tried in every way, even with the library Picasso.
Thanks!
1st things 1st: depending on device and bitmap size, no matter what magic code you do, it will crash! Specially cheap Samsung phones that usually have no more than 16mb of RAM to the VM.
You can use this code How to get current memory usage in android? to check on amount of memory available and deal with it properly.
When doing those calculations, remember that bitmaps are uncompressed images, that means, even thou the JPG might be 100kb, the Bitmap might take several MB.
You'll use the code shown here https://developer.android.com/training/displaying-bitmaps/load-bitmap.html to read the bitmap boundaries, and do an approximate scale down as close as possible to the size you actually need, or enough to make the device not crash. That's why it's important to properly measure the memory.
That 1st code takes virtually no RAM as it creates from the disk, making it smaller by simply skipping pixels from the image. That's why it's approximate, it only does in power of 2 the scaling.
Then you'll use the standard API to scale down to the size you actually need https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap, int, int, boolean)
so the pseudo code for it, will be:
try{
Info info = getImageInfo(File);
int power2scale = calculateScale(info, w, h);
Bitmap smaller = preScaleFromDisk(File, power2scale);
Bitmap bitmap = Bitmap.createScaledBitmap(smaller, w, h, f);
} catch(OutOfMemoryError ooe){
// call GC
// sleep to let GC run
// try again with higher power2scale
}

Avoiding Out of Memory Error with Bitmap Factory, Even When Resizing Isn't an Issue?

I've researched at least 10 similar topics on SO, however, none have reached a definitive answer for me allowing me to avoid the Out of Memory error Bitmaps are known for.
Taking into consideration the advice from these previous questions, I constructed the following method setBipmapFromPath to produce an optimally sized (both in dimensions and kilobytes) wallpaper image from a file path. This method works fine on a large RAM device like my G2, however, it crashes in an emulator with 1.5GB of RAM using a 256kb picture.
I welcome any criticism that will help me prevent the Out of Memory error. My hope is to also ensure the image can still act as a proper background image, as in, fill the screen of the device reasonably without insane stretch marks.
My methods:
public void recycleWallpaperBitmap() {
if (mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
}
private void setBitmapFromPath() {
// Recycle the bitmap just in case.
recycleWallpaperBitmap();
String path = mProfileManager.getWallpaperPath();
if (path != null) {
WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int displayWidth = display.getWidth(); // deprecated
int displayHeight = display.getHeight(); // deprecated
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
mBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(path, options),
displayWidth, displayHeight);
}
}
This method works fine on a large RAM device like my G2, however, it crashes in an emulator with 1.5GB of RAM using a 256kb picture.
It will fail on the G2 as well, depending on where and when you call this method. Your "256kb" picture will take up several MB of heap space, and there is no assurance that you have that amount of heap space available in a single contiguous block.
Also, I would not use a class and method designed for creating thumbnails will be suitable for creating wallpaper-sized images.
I welcome any criticism that will help me prevent the Out of Memory error.
Use inSampleSize on your BitmapFactory.Options to downsample the image to closer to the right size while it is being read in.
Then, dump your use of ThumbnailUtils and allow your ImageView to scale it the rest of the way, to avoid making yet another copy of the image.
Bonus points for using inBitmap instead of junking and re-allocating your Bitmap every time, since the screen size is not changing, and therefore your wallpaper dimensions are not changing.
These techniques and more are covered in the developer documentation.

When (if at all) should I use Bitmap.recycle()?

According to Android Developers site, the Bitmap.recycle() method definition is:
Free the native object associated with this bitmap, and clear the reference to the pixel data
I've developed some applications which are creating / decoding a lot of bitmaps, and put the result bitmap objects to ImageViews. Sometimes I've got the famous exceptions such as:
bitmap size excceded vm budget
and
out of memory error
Also I'm sure I don't have any memory leaks that can cause that.
After a lot of searches, I discoverd the "recycle" method, and used it to free the bitmap's native memory when no longer needed. It seems like it helped a lot.
I'm asking if that's something I'm supposed to do on this situation, because
I know the system is doing this anyway without calling it explicitly (is it? maybe I'm wrong).
Should I use this method in situations like this?
In what situations should I use this method?
Should I use this method at all?
thanks in advance.
UPDATE:
google posted this guide recently, which says:
On Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.
in what situations should I use this method?
The Bitmaps are GC'ed by GC whenever it decides.But in some situations it may get delayed.
And always remember thumb rule in java (Maybe it applies to othe P.L also).The speed of recycling objects by GC may not be same as speed of creating objects.So sometimes the GC is slow to in recycling.
so recycle() means If you want to free memory ASAP you should call recycle()
should I use this method at all??
This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.But if you are facing the issues like bitmap size exceeded vm budget or out of memory error then you need to use this.
I do use it in operations where i know that bitmap is not going to be used anymore.
public static Bitmap getMaskedContactImage (Context context, Bitmap contactImageBitmap, int maskToBeApplied) {
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), maskToBeApplied);
Bitmap output = Bitmap.createBitmap(mask.getWidth(),mask.getHeight(), Config.ARGB_8888);
final Rect finalRect = new Rect(0, 0, contactImageBitmap.getWidth(), contactImageBitmap.getHeight());
final Rect originRect = new Rect(0, 0, mask.getWidth(), mask.getHeight());
Canvas canvas = new Canvas(output);
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.BLACK);
xferPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawBitmap(contactImageBitmap, finalRect, originRect, null);
canvas.drawBitmap(mask, originRect, originRect, xferPaint);
contactImageBitmap.recycle();
mask.recycle();
return output;
}
In places like that one, im sure im not going to use the mask or the contactImage.
I found a really good resource for Bitmap processing that can be helpfull Displaying bitmaps.
Regards,
Alex

Android Development: Bitmaps on surfaceview leak Memory or too big?

My game uses surfaceview(I know I should use GL).
I draw alot of bitmaps to my game character world controll so on. And i run into this when I opened my LogDog:
08-05 10:17:29.151: ERROR/dalvikvm(24048): Out of memory: Heap Size=5379KB, Allocated=2735KB, Bitmap Size=20576KB, Limit=32768KB
I dont know if it is leak or what.
My Allocation Tracker shows:
like 30:
138 96 char[] 9 android.content.res.AssetManager getCookieName
Then
Tons of:
32 80 android.graphics.BitmapFactory$Options 9 android.graphics.BitmapFactory decodeResource
And last:
Like 30:
141 56 android.graphics.Bitmap 9 android.graphics.BitmapFactory nativeDecodeAsset
And also some more of simular ones.
Here is some code that I think drains my memory:
player = BitmapFactory.decodeResource(getResources(), R.raw.ghostright);
world = BitmapFactory.decodeResource(getResources(), R.raw.lvl2);
thumb = BitmapFactory.decodeResource(getResources(), R.raw.thumb);
resized = Bitmap.createScaledBitmap(player, width/10, width/6, false);
player = resized;
resized = Bitmap.createScaledBitmap(world, height*10, height, false);
world = resized;
resized = Bitmap.createScaledBitmap(thumb, height/6, height/6, false);
thumb = resized;
I heard that I should use resycle but I dont know where because I always use the bitmaps
//Simon
PS: I really need help -.-
I use a lot of bitmaps on SurfaceView too and don't have this problem.
When it comes to animated sprites, you can use a sprite sheet rather than load them individually frame by frame.
You don't need to use the reference "resized" you can just say:
player = Bitmap.createScaledBitmap(player, width/10, width/6, true);
the old bitmap will lose its reference and be collected by GC. Note that I placed TRUE for bitmap filtering when rescaling to make a better quality.
On some devices onSizeChanged can happen two times which may resize bitmaps twice, if that is where you are doing your scaling.
The format of loaded bitmaps does metter whether it is ARGB_4444 or ARGB_8888 etc So you may need to explore this option and if you can use a format which requires less memory yet it has a good enough quality for your game. Of course the rule is not to load images into memory bigger than they are needed and when they are needed.
It dosen't have to be a memory leak, it could just be that you have so large bitmaps that they want to allocate to much memory. Here's a good method to determine how much memory a bitmap is going to take: W*H*8. So if you have a bitmap that's 300*300 px it's 300*300*8 = 720 kb.
Figure out how much allocated heap you have at any given time and see if it increases with time even though you know that you're not allocating new bitmaps. If so, then yes, you have a memory leak. If, however, your app crashes right on startup, then you are probably just exceeding heap limit.

Categories

Resources