android 圖片壓縮 方法--記錄

一: 介紹下圖片存在的形式

  1.  文件的形式 (即以二進制形式存在於硬盤上)
  2.  流的形式(即以二進制形式存在於內存上)
  3.  bitmap 形式

   三者之前的區別:  12 讀圖片時不會因爲圖片大小的增加而增加所佔的內存, 但是 3 會增加。


二:兩種圖片壓縮方式

  1.    將圖片保存到本地進行壓縮,是bitmap形式  轉 file 形式。  當重新讀取壓縮 file 轉 bitmap時 所佔的內存麼有變化


  2.    將圖片從本地讀到內存時進行壓縮,即 圖片 從file 轉  bitmap 。   是通過設置採樣率,減少圖片像素,從而達到對內存中bitmap 進行壓縮。
         (我現在用這個方法,特 記錄~)

             調用下就行了 

       Bitmap bitmap = compressImageFromFile(fileName);    


private 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;//
		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 compressBmpFromBmp(bitmap);//原來的方法調用了這個方法企圖進行二次壓縮
		// 其實是無效的,大家儘管嘗試
		return bitmap;


       總結語言,去掉不必要的,留下自己要的,在此特別感謝dance_八戒  .
發佈了34 篇原創文章 · 獲贊 20 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章