整理和学习一下最近项目里用到的图片压缩方法,在网上找的资料,记录下以免忘记。
inJustDecodeBounds:
当这个值置为true时,解码时将不会返回bitmap,只会返回这个bitmap的尺寸,又不会将其加载到内存时。这是一个非常有用的属性。
/**
* 根据路径获得突破并压缩返回bitmap用于显示
* @param filePath 图片的路径
* @param reqWidth 要求的图片的像素
* @param reqHeight 要求的图片的像素
* @return
*/
public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
outWidth和outHeight:
表示这个Bitmap的宽和高,一般和inJustDecodeBounds一起使用来获得Bitmap的宽高,但是不加载到内存。
inSampleSize:是一个int,当它小于1的时候,将会被当做1处理,如果大于1,那么就会按照比例(1 / inSampleSize)缩小bitmap的宽和高、降低分辨率,大于1时这个值将会被处置为2的倍数。例如,width=100,height=100,inSampleSize=2,那么就会将bitmap处理为,width=50,height=50,宽高降为1 / 2,像素数降为1 / 4。
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 String bitmapToString(String filePath) {
Bitmap bm = getSmallBitmap(filePath,1080,768);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
图片保存比较简单;弄清思路就可以:
String savePath = Environment.getExternalStorageDirectory().toString()+"/testPicture2";
String imageName = System.currentTimeMillis() + ".jpg";
File file = new File(savePath);
if (!file.exists()){
file.mkdirs();
}
File file1 = new File(savePath, imageName);
try {
BufferedOutputStream bufferedOutputStream = null;
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file1));
base64ToBitmap(imageString).compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream);
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}