相關(guān)的壓縮和保存圖片代碼如下:
/**
* 根據(jù)路徑獲取bitmap(壓縮后)
*
* @param srcPath 圖片路徑
* @param width 最大寬(壓縮完可能會大于這個,這邊只是作為大概限制,避免內(nèi)存溢出)
* @param height 最大高(壓縮完可能會大于這個,這邊只是作為大概限制,避免內(nèi)存溢出)
* @param size 圖片大小,單位kb
* @return 返回壓縮后的bitmap
*/
public static Bitmap getCompressBitmap(String srcPath, float width, float height, int size) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時把options.inJustDecodeBounds 設(shè)回true了
newOpts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
int scaleW = (int) (w / width);
int scaleH = (int) (h / height);
int scale = scaleW < scaleH ? scaleH : scaleW;
if (scale <= 1) {
scale = 1;
}
newOpts.inSampleSize = scale;// 設(shè)置縮放比例
// 重新讀入圖片,注意此時已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
// 壓縮好比例大小后再進行質(zhì)量壓縮
return compressImage(bitmap, size);
}
/**
* 圖片質(zhì)量壓縮
*
* @param image 傳入的bitmap
* @param size 壓縮到多大,單位kb
* @return 返回壓縮完的bitmap
*/
public static Bitmap compressImage(Bitmap image, int size) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
// 循環(huán)判斷如果壓縮后圖片是否大于size,大于繼續(xù)壓縮
while (baos.toByteArray().length / 1024 > size) {
// 重置baos即清空baos
baos.reset();
// 每次都減少10
options -= 10;
// 這里壓縮options%,把壓縮后的數(shù)據(jù)存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
// 把壓縮后的數(shù)據(jù)baos存放到ByteArrayInputStream中
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// 把ByteArrayInputStream數(shù)據(jù)生成圖片
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
/**
* bitmap保存為文件
*
* @param bm bitmap
* @param filePath 文件路徑
* @return 返回保存結(jié)果 true:成功,false:失敗
*/
public static boolean saveBitmapToFile(Bitmap bm, String filePath) {
try {
File file = new File(filePath);
file.deleteOnExit();
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
boolean b = false;
if (filePath.toLowerCase().endsWith(".png")) {
b = bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
} else {
b = bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
}
bos.flush();
bos.close();
return b;
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return false;
}