title: Reduce the size of a bitmap to a specified size in Android
body: <p>I want to reduce the size of a bitmap to 200kb exactly. I get an image from the sdcard, compress it and save it to the sdcard again with a different name into a different directory. Compression works fine (3 mb like image is compressed to around 100 kb). I wrote the following lines of codes for this:</p>
  
  <pre><code>String imagefile ="/sdcard/DCIM/100ANDRO/DSC_0530.jpg";
  Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
  
  //this method compresses the image and saves into a location in sdcard
      Bitmap ShrinkBitmap(String file, int width, int height){
  
           BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
              bmpFactoryOptions.inJustDecodeBounds = true;
              Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
  
              int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
              int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
  
              if (heightRatio &gt; 1 || widthRatio &gt; 1)
              {
               if (heightRatio &gt; widthRatio)
               {
                bmpFactoryOptions.inSampleSize = heightRatio;
               } else {
                bmpFactoryOptions.inSampleSize = widthRatio; 
               }
              }
  
              bmpFactoryOptions.inJustDecodeBounds = false;
              bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
  
              ByteArrayOutputStream stream = new ByteArrayOutputStream();   
              bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);   
              byte[] imageInByte = stream.toByteArray(); 
              //this gives the size of the compressed image in kb
              long lengthbmp = imageInByte.length / 1024; 
  
              try {
                  bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/compressed_new.jpg"));
              } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  
  
           return bitmap;
          }
  </code></pre>