Java tutorial
//package com.java2s; //License from project: Apache License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.ByteArrayOutputStream; public class Main { public static byte[] compressBitmap(byte[] data, float size) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); if (bitmap == null || getSizeOfBitmap(bitmap) <= size) { return data; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); int quality = 100; while ((baos.toByteArray().length / 1024f) > size) { quality -= 5; baos.reset(); if (quality <= 0) { break; } bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos); } byte[] byteData = baos.toByteArray(); return byteData; } private static long getSizeOfBitmap(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); long length = baos.toByteArray().length / 1024; return length; } }