圖片壓縮總結
一、圖片存儲形式
1、文件形式(以二進制儲形式存在硬盤上)
2、流形式(以二進制形式儲存在內存中)
3、Bitmap形式(數據會遠遠大於以上兩種形式)
一、常見的壓縮方式
1、將圖片保存到本地時壓縮,保存爲File文件
特點:File形式的圖片被壓縮了,但是當你重新讀取後獲得Bitmap是沒有改變的,改變的只是圖片的顯示質量。
public static void compressBmpToFile(Bitmapbmp,File file){
ByteArrayOutputStream baos = newByteArrayOutputStream();
int options = 80;//個人喜歡從80開始,
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length /1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = newFileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二、將圖片從本地讀到內存時,進行壓縮,即圖片從File形式變爲Bitmap形式
特點: 通過設置採樣率, 減少圖片的像素, 達到對內存中的Bitmap進行壓縮
private Bitmap compressImageFromFile(StringsrcPath) {
BitmapFactory.Options newOpts = newBitmapFactory.Options();
newOpts.inJustDecodeBounds = true;//只讀邊,不讀內容
Bitmap bitmap =BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds =false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = 800f;//
float ww = 480f;//
int 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;//設置採樣率
newOpts.inPreferredConfig =Config.ARGB_8888;//該模式是默認的,可不設
newOpts.inPurgeable = true;// 同時設置纔會有效
newOpts.inInputShareable =true;//。當系統內存不夠時候圖片自動被回收
bitmap =BitmapFactory.decodeFile(srcPath, newOpts);
// returncompressBmpFromBmp(bitmap);//原來的方法調用了這個方法企圖進行二次壓縮
//其實是無效的,大家儘管嘗試
return bitmap;
}