Compressing a bitmap to JPG format Android example

Codec, compress(), CompressFormat, quality, decodeByteArray(), Android example source code with image.

public class MainActivity extends Activity {
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(new SampleView(this));
	private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,
			int quality) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		src.compress(format, quality, os);
		byte[] array = os.toByteArray();
		return BitmapFactory.decodeByteArray(array, 0, array.length);
	private static class SampleView extends View {
		public SampleView(Context context) {
		protected void onDraw(Canvas canvas) {
			Paint paint = new Paint();
                        //  you need to insert some image flower_blue into res/drawable folder
			Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.flower_blue);
                        // Best of quality is 80 and more, 3 is very low quality of image 
			Bitmap bJPGcompress = codec(b, Bitmap.CompressFormat.JPEG, 3);
                   // get dimension of bitmap getHeight()  getWidth()
		   int h = b.getHeight();
           canvas.drawBitmap(b, 10,10, paint);
           canvas.drawBitmap(bJPGcompress, 10,10 + h + 10, paint);

jpg compression android

This entry was posted in Android Examples Code, Bitmap, drawing and tagged , , . Bookmark the permalink.

Comments are closed.