1) try to decode the linked image first
You will get the actual image size to prevent OOM problem. Dont ever decode an image first !!!
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(bitmapByteArray, 0, bitmapByteArray.length, options);'
options.outWidth and options.outHight are what you want.
2) calculate sample size
using the following code from http://hi-android.info/src/com/android/camera/Util.java.html . If you find that outWidth and outHeight are too large to have an OOM problem, just set outWidth and outHeight to a smaller size. This will give you the approximate size that the decoded image will have for these outWidth and outHeight. The bitmap options here are the same as what you use in step 1.
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) {
3) Use the calculated sample size
Once you get the sample size, use it to decode the real image data.
options.inTempStorage = new byte[16*1024]; options.inPreferredConfig = (config == null)?BitmapUtil.DEFAULT_CONFIG:config; options.inSampleSize = BitmapUtil.computeSampleSize(bitmapWidth, bitmapHeight, bitmapWidth < bitmapHeight?targetHeight:targetWidth, bitmapWidth < bitmapHeight?targetWidth:targetHeight, 1); options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = false; options.inDither = true; result = BitmapFactory.decodeByteArray(bitmapByteArray, 0, bitmapByteArray.length, options);
~ If this is still a problem with OOM, you can try to reduce outWidth and outHeight. bitmap uses the built-in heap, not the java heap. Therefore, it is difficult to determine how much memory is left to decode a new image.
~~ If you need to set outWidth and outHeight too low, then you might have a memory leak somewhere in your code. try freeing up any object from memory that you are not using. eg bitmap.release();
~~~ above is just a sample code. adjust what you need.