title: Decoding bitmaps in Android with the right size
body: <p>I decode bitmaps from the SD card using <code>BitmapFactory.decodeFile</code>. Sometimes the bitmaps are bigger than what the application needs or that the heap allows, so I use <code>BitmapFactory.Options.inSampleSize</code> to request a subsampled (smaller) bitmap.</p>
  
  <p>The problem is that the platform does not enforce the exact value of inSampleSize, and I sometimes end up with a bitmap either too small, or still too big for the available memory. </p>
  
  <p>From <a href="http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize" rel="noreferrer">http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize</a>:</p>
  
  <blockquote>
    <p>Note: the decoder will try to fulfill
    this request, but the resulting bitmap
    may have different dimensions that
    precisely what has been requested.
    Also, powers of 2 are often
    faster/easier for the decoder to
    honor.</p>
  </blockquote>
  
  <p>How should I decode bitmaps from the SD card to get a bitmap of the exact size I need while consuming as little memory as possible to decode it? </p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Current source code:</p>
  
  <pre><code>BitmapFactory.Options bounds = new BitmapFactory.Options();
  this.bounds.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(filePath, bounds);
  if (bounds.outWidth == -1) { // TODO: Error }
  int width = bounds.outWidth;
  int height = bounds.outHeight;
  boolean withinBounds = width &lt;= maxWidth &amp;&amp; height &lt;= maxHeight;
  if (!withinBounds) {
      int newWidth = calculateNewWidth(int width, int height);
      float sampleSizeF = (float) width / (float) newWidth;
      int sampleSize = Math.round(sampleSizeF);
      BitmapFactory.Options resample = new BitmapFactory.Options();
      resample.inSampleSize = sampleSize;
      bitmap = BitmapFactory.decodeFile(filePath, resample);
  }
  </code></pre>