Alex Rivera | Logout

Android: Question about Bitmaps, memory usage, and scaling

Asked 2011-06-01T17:48:10.827
14

For readibility, I posted the code examples that my solutions refer to first, and thenI listed the explanations of my solutions in a numerical list.

I have been struggling with this for a while now. I have done much reading, asked questions on here, and experimented; but have not come up with a decent solution. I need to read variously sized images from input streams, and display them with as high of quality as my memory constraints allow. Below are the options I have considered, none of which seem great to me. Any help or input would be greatly appreciated.

 public class NativeTest extends Activity
 {
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       double nativeUsage = Debug.getNativeHeapAllocatedSize(); 
       Log.i("memory", nativeUsage+"");
    } 
 }


 double getAvailableMemory()
 {
    //current heap size 
     double heapSize =  Runtime.getRuntime().totalMemory();
    //amount available in heap 
    double heapRemaining = Runtime.getRuntime().freeMemory();   
    double nativeUsage  =  Debug.getNativeHeapAllocatedSize();
     double memoryAvailable = Runtime.getRuntime().maxMemory() - (heapSize - heapRemaining) - nativeUsage;
    return memoryAvailable;
 }

Bitmap createImageTrialAndError(InputStream stream)
{
    Bitmap image = null;
    int dowsample = 1;
    while(image == null)
    {
       try
       {    
        Options opts = new Options();
        opts.inSampleSize =  downsample;
        image = BitmapFactory.decodeStream(imgStream, null, opts);
       }
       catch (OutOfMemoryError ome)
       {
           downsample = downsample * 2;
           Log.i("out of mem", "try using: " + downsample); 
       }
    }

    return image;
}
  1. The ideal solution would be if Bitmap had a Bitmap.drawBitmap(inputstream...) method. This would allow me to draw from the inputstream without having to allocate memory for the Bit
Edit
Report

1 Answer

0

A simple and straightforward way is to use "inJustDecodeBounds" property of Options. Set this property to true for options object you created, then continue to decode stream.

The bitmap returned will be null, which means no memory is allocated to it, but you can read the dimensions of the bitmap and thus determine its size and adjust the inSampleSize ratio.

Later reset inJustDecodeBounds to false, by now you know the scale down factor, thus bitmap of required size can now be generated.

Hope this helps.

answered 2013-07-18T11:19:07.510

Your Answer