Android examples for Graphics:Bitmap Compress
compress Bitmap
//package com.java2s; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class Main { public static Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); if (baos.toByteArray().length / 1024 > 800) {//1M,BitmapFactory.decodeStream baos.reset();//baosbaos image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//50%baos }// w ww . j av a 2 s. com ByteArrayInputStream isBm = new ByteArrayInputStream( baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); //options.inJustDecodeBounds true newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; //800*480 float hh = 800f;//800f float ww = 480f;//480f // int be = 1;//be=1 if (w > h && w > ww) {// be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// //options.inJustDecodeBounds false isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); return compressImage(bitmap);// } public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 80, baos);//100baos int options = 100; while (baos.toByteArray().length / 1024 > 100) { //100kb, baos.reset();//baosbaos image.compress(Bitmap.CompressFormat.JPEG, options, baos);//options%baos options -= 10;//10 } ByteArrayInputStream isBm = new ByteArrayInputStream( baos.toByteArray());//baosByteArrayInputStream Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//ByteArrayInputStream return bitmap; } }