1. 程式人生 > >Android中關於圖片壓縮的小結

Android中關於圖片壓縮的小結

Android中如何進行圖片壓縮處理

一、我遇到的問題

工作中遇到的問題,有天領導讓我把工程中所有需要上傳圖片的部分都要進行優化,把圖片壓縮後上傳。我上網查了下發現有兩種方式。一、質量壓縮二、尺寸壓縮

二、網上的錯誤之處

關於這兩個壓縮的具體定義我就不多描述了,但是我查閱資料的時候發現網上好多文章都存在誤解。大多數就認為先進行尺寸壓縮後再進行質量壓縮,後一步是無效。其實,這個說法是錯誤的,我為什麼這樣說呢?因為就算是先進行尺寸壓縮再進行質量壓縮也是有效的。

三、Android中圖片的存在形式

一、檔案形式(即以二進位制形式存於硬碟上)二、流的形式三、bitmap形式。三種形式的區別:檔案和流的形式對圖片體積大小並沒有影響,也就是說,如果你手機SD卡上的如果是100K,那麼通過流的形式都到記憶體也是100K。但是當圖片以bitmap形式存在時,其佔用的記憶體會瞬間變大

。這也就造成了當進行質量壓縮後return bitmap形式後覺得壓縮無效的錯覺。重點就在於你return的是bitmap!

四、下面貼出我寫的圖片壓縮程式碼(用了兩種壓縮方式

public class BitmapCompress {

public static byte[] BitmapCompressToString(String srcPath) {

Bitmap bmp = compressImageFromFile(srcPath);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bmp.compress(Bitmap.CompressFormat.JPEG

, 100, baos);

int options = 100;

while (baos.toByteArray().length / 1024 > 150) {

options -= 10;// 每次都減少10

// 迴圈判斷如果壓縮後圖片是否大於150kb,大於繼續壓縮

baos.reset();// 重置baos即清空baos

bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);

Log.d("ROTK","baos"+baos.toByteArray().length);

// 這裡壓縮options%,把壓縮後的資料存放到baos

}

byte[] b = baos.toByteArray();

return b;

}

private static Bitmap compressImageFromFile(String srcPath) {

BitmapFactory.Options newOpts = new BitmapFactory.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;//壓縮為800*480的尺寸

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);

return bitmap;//這裡輸出的事bitmap因為我們還要進行質量壓縮的

}

}


恩,以上!