How to choose optimum image size to not exceed VM budget?
In my app users choose images and program lets users to make changes on images. S开发者_JS百科ince there are a lot of different android devices out there my program crashes on some of devices which less heap size. I want to calculate the best fit dimensions for user's phone so it won't crash because of VM budget. I have added a screenshot from "Picsay Pro" which is making exactly what i am looking for. I do know about the "BitmapFactory.Options" my only problem is to find a way to decide image dimensions which won't let crash the app because of VM budget.
Calculate the Free Space Remaining on the phone:
long freeMemory = (Runtime.getRuntime().maxMemory()) - (Debug.getNativeHeapAllocatedSize());
where,
Runtime.getRuntime().maxMemory() - returns the Total Heap Limit size (in Bytes).
Debug.getNativeHeapAllocatedSize() - returns the Amount of Data already used by your application (in Bytes).
Calculate the size of the Bitmap you are using by this formula,
long Bytes_allocated = (height of the Image) * (width of the Image) * 4;
Compare freeMemory
and Bytes_allocated
to select the appropiate size for your application.
I actually ended up compressing images on the phone for two reasons. One was upload speeds and another one was heap problems. You can try doing something similar, or at least post the stack trace!
Android outofmemory error bitmap size exceeds vm budget in 2.3.3
i think this compression technique could help
So far I've not found any reliable way to deal with image size vs available memory. The problem is the memory becomes fragmented very quickly, so that you could have 10 MB free, but no contiguous space for a 2 MB image. What is really needed is the size of the largest free space, but there doesn't appear to be any way to get this. Better would be a way to defragment memory, but no such function exist for this either.
Still if your available memory is less than the image, you can be sure you're going to crash if you attempt to use it, so it has some merit to at least check before you use it.
With late-2012 tablets now having 1920x1280 resolution, we now need 20MB of continuous memory for a single background image! It appears some of these tablets are now allowing heaps up to 256MB, but while tossing more VM space seemingly solves it, we really need a memory defragmenter or a way to reserve space.
There is one trick that might help if the image size is not scaled or modified, and each changed image is the same size AND you are limiting your app to Android 3.0+:
Options opt2 = new BitmapFactory.Options();
opt2.inBitmap = mBitmap; // reuse mBitmap to reduce out of memory errors
mBitmap = BitmapFactory.decodeResource(getResources(), myDrawable, opt2);
This will reuse the same memory area mBitmap for the image.
精彩评论