title: How to avoid an out of memory error while using bitmaps in Android
body: <p>I am using bitmaps. When the code runs it shows an out of memory error. How can the error be avoided. My code follows. Thanks in advance.</p>
  
  <pre><code>Bitmap myBitmap = Image.decodeSampledBitmapFromUri(path, 250, 500); 
  img_cook[index].setImageBitmap(myBitmap); 
  
  public static Bitmap decodeSampledBitmapFromUr(String path, int reqWidth,
              int reqHeight) {
  
      Bitmap bm = null;
  
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(path, options);
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
      options.inJustDecodeBounds = false;
      bm = BitmapFactory.decodeFile(path, options);
  
      return bm;
  }
  
  public static int calculateInSampleSize(BitmapFactory.Options options,
          int reqWidth, int reqHeight) {
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;
  
      if (height &gt; reqHeight || width &gt; reqWidth) {
          if (width &gt; height) {
           inSampleSize = Math.round((float)height / (float)reqHeight);    
          } else {
           inSampleSize = Math.round((float)width / (float)reqWidth);    
          }   
         }
  </code></pre>