Here you can find the source of scaleBitmapIfNeededToSize(Bitmap bitmap, long size)
public static byte[] scaleBitmapIfNeededToSize(Bitmap bitmap, long size)
//License from project: Open Source License import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import org.ixming.android.utils.FrameworkLog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; public class Main{ static final String TAG = "sharebind_bitmaputil"; public static byte[] scaleBitmapIfNeededToSize(Bitmap bitmap, long size) { byte[] data = null; try {/* w w w .ja v a2 s.c o m*/ float width = bitmap.getWidth(); float height = bitmap.getHeight(); data = bmpToByteArray(bitmap, false); float des = data.length; des = des / size; if (des <= 1) { return data; } final float scale; if (des <= 2.5F) { scale = 0.95F; } else if (des <= 5.0F) { scale = 0.9F; } else if (des <= 7.5F) { scale = 0.85F; } else { scale = 0.8F; } while (true) { if (null == data || data.length <= size) { break; } Bitmap bitmapCopy = bitmap; width *= scale; height *= scale; bitmap = Bitmap.createScaledBitmap(bitmapCopy, (int) width, (int) height, true); bitmapCopy.recycle(); data = bmpToByteArray(bitmap, false); } } catch (Exception e) { data = null; FrameworkLog.e( TAG, "scaleBitmapIfNeededToSize Exception: " + e.getMessage()); } return data; } public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) { if (null == bmp) { return null; } ByteArrayOutputStream output = null; try { output = new ByteArrayOutputStream(); bmp.compress(CompressFormat.PNG, 100, output); if (needRecycle) { bmp.recycle(); } byte[] result = output.toByteArray(); return result; } catch (Exception e) { FrameworkLog.e(TAG, "bmpToByteArray Exception: " + e.getMessage()); return null; } finally { if (null != output) { try { output.close(); } catch (Exception ex) { } } } } }