記一個 bitmap位圖壓縮。

package com.example.decodebitmap;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitMapUtil {

	public static Bitmap decodeBitmap(Resources res,int resId,int resWidth,int resHeight){
		
		BitmapFactory.Options option=new BitmapFactory.Options();
		//不產生內存,不佔用內存
		option.inJustDecodeBounds=true;
		//第一次壓縮爲了獲得原始圖片的大小
		BitmapFactory.decodeResource(res, resId, option);
		//計算要壓縮的比例
		option.inSampleSize=calculateInSampleSize(resWidth, resHeight, option);
		//真正的壓縮,佔內存
		option.inJustDecodeBounds=false;
		
		return BitmapFactory.decodeResource(res, resId, option);
		
		
		
	}
	
	public static int calculateInSampleSize(int resWidth,int resHeight,BitmapFactory.Options option){
		//獲得實際的圖片大小
		int imageHeight=option.outHeight;
		int imageWidth=option.outWidth;
		//設置壓縮的比例,1爲沒壓縮
		int sampleSize=1;
		//判斷實際大小是否大於要求大小,是久繼續
		if(imageHeight>resHeight || imageWidth>resWidth){
			if(imageHeight>imageWidth){
				sampleSize=Math.round((float)imageWidth/(float)resWidth);		//這裏看不大懂,也有說哪個小返回哪個
			}else{
				sampleSize=Math.round((float)imageHeight/(float)resHeight);
			}
			
		
		}
		
		
		return sampleSize;	//返回壓縮比例
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章