title: BitmapFactory.decodeFile out of memory with images 2400x2400
body: <p>I need to send an image from a file to a server. The server request the image in a resolution of 2400x2400. </p>
  
  <p>What I'm trying to do is:</p>
  
  <p>1) Get a Bitmap using BitmapFactory.decodeFile using the correct inSampleSize.</p>
  
  <p>2) Compress the image in JPEG with a quality of 40%</p>
  
  <p>3) Encode the image in base64</p>
  
  <p>4) Sent to the server</p>
  
  <p>I cannot achieve the first step, it throws an out of memory exception. I'm sure the inSampleSize is correct but I suppose even with inSampleSize the Bitmap is huge (around 30 MB in DDMS). </p>
  
  <p>Any ideas how can do it? Can I do these steps without created a bitmap object? I mean doing it on filesystem instead of RAM memory.</p>
  
  <p>This is the current code:</p>
  
  <pre><code>// The following function calculate the correct inSampleSize
  Bitmap image = Util.decodeSampledBitmapFromFile(imagePath, width,height);   
  // compressing the image
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.JPEG, 40, baos);
  // encode image
  String encodedImage = Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
  
  
  public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
      // Raw height and width of image
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;
  
      if (height &gt; reqHeight || width &gt; reqWidth) {
  
          // Calculate ratios of height and width to requested height and width
          final int heightRatio = Math.round((float) height / (float) reqHeight);
          final int widthRatio = Math.round((float) width / (float) reqWidth);
  
          // Choose the smallest ratio as inSampleSize value, this will guarantee
          // a final image with both dimensions larger than or equal to the
          // requested height and width.
          inSampleSize = heightRatio &lt; widthRatio ? heightRatio : widthRatio;
      }
  
      return inSampleSize;
  }
  
  public static Bitmap decodeSampledBitmapFromFile(String path,int reqWidth, int reqHeight) {
  
      // First decode with inJustDecodeBounds=true to check dimensions
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(path, options);
  
      // Calculate inSampleSize
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
  
      // Decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;
      return BitmapFactory.decodeFile(path,options);
  }
  </code></pre>