android自帶的壓縮圖片是用bitmap.compress。需要注意的是這裏壓縮的只是文件大小,因爲載入到bitmap裏面時還會解壓,所以在打印大小會發現壓縮前後bitmap的大小是沒變的。
bitmap存在一個很大的問題就是oom,這個問題同樣在使用bitmap壓縮時存在。這裏網上普遍使用的一個方法是,先讀取文件的配置屬性,然後根據需求載入一張符合需求的縮略圖,然後對縮略圖進行壓縮。這裏帶來的一個問題是,縮略圖改變了圖片的大小,所以會導致圖片出現模糊現象。
public Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// 獲取當前最大可用內存
options.inSampleSize = calculateInSampleSize(options, 1080, 1920);
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);
if (bm == null) {
return null;
}
int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
} catch (Exception e) {
Log.i("", e.toString());
} finally {
try {
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
return bm;
}