/*
*此方法本人用在项目里面,压缩出来的图片清晰度还可以,
*/
private String compressionBitmap(String path){// path 是传入需要压缩图片的路径
String pa = null;
try {
File f = new File(path);
Bitmap bm = ImageTools.getSmallBitmap(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
FileOutputStream fos = new FileOutputStream(new File(ImageTools.getAlbumDir(),
"small01_" + f.getName()));
int options = 100;
// 如果大于80kb则再次压缩,最多压缩三次
while (baos.toByteArray().length / 1024 > 80 && options != 10) {
baos.reset();
bm.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 30;
}
fos.write(baos.toByteArray());
fos.close();
baos.close();
pa = "/mnt/sdcard/doucheng_bitmap/"+"small01_"+f.getName();
} catch (Exception e) {
e.printStackTrace();
}
return pa;// pa 是压缩图片后图片的路径
}
// 根据路径获得图片并压缩返回bitmap
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
// 计算图片的缩放值
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
// 压缩后图片的路径
public static File getAlbumDir() {
File dir = new File("/mnt/sdcard/doucheng_bitmap/");
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}