title: OutOfMemoryError although I'm down scale the bitmaps
body: <p>I use small resource images (max 25kb, max 256x256) and load some larger images from the internet with picasso. The picasso loading never failed until now. But the resource image loading does sometimes.</p>
  
  <p>For the resource images I use the code appended (<code>setBitmap</code>), but although I down scale the images, on some devices my app still produces a <code>OutOfMemoryError</code> when calling <code>BitmapFactory.decodeResource</code>. Does anyone have an idea, where to look next?</p>
  
  <pre><code>private static void setBitmap(final ImageView iv, final int resId)
  {
      iv.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
      {
          public boolean onPreDraw()
          {
              iv.getViewTreeObserver().removeOnPreDrawListener(this);
              iv.setImageBitmap(decodeSampledBitmapFromResource(iv.getContext().getResources(), resId, iv.getMeasuredWidth(), iv.getMeasuredHeight()));
              return true;
          }
      });
  }
  
  private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int w, int h)
  {
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeResource(res, resId, options);
  
      options.inSampleSize = calculateInSampleSize(options, w, h);
  
      options.inJustDecodeBounds = false;
      return BitmapFactory.decodeResource(res, resId, options);
  }
  
  private static int calculateInSampleSize(BitmapFactory.Options options, int w, int h)
  {
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;
  
      if (height &gt; h || width &gt; w)
      {
  
          final int halfHeight = height / 2;
          final int halfWidth = width / 2;
  
          while ((halfHeight / inSampleSize) &gt; h &amp;&amp; (halfWidth / inSampleSize) &gt; w)
          {
              inSampleSize *= 2;
          }
      }
  
      L.d(ImageTools.class, "inSampleSize | height | width: " + inSampleSize + " | " + height + " | " + width);
  
      return inSampleSize;
  }
  </code></pre>