Android以最省內存的方式讀取本地資源的

方法一: spa

/**
* 獲取本地圖片並指定高度和寬度
*/
public static Bitmap getNativeImage(String imagePath)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 獲取這個圖片的寬和高
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath, options); //此時返回myBitmap爲空
//計算縮放比
int be = (int)(options.outHeight / (float)200);
int ys = options.outHeight % 200;//求餘數
float fe = ys / (float)200;
if (fe >= 0.5)
be = be + 1;
if (be <= 0)
be = 1;
options.inSampleSize = be; code

//從新讀入圖片,注意此次要把options.inJustDecodeBounds 設爲 false
options.inJustDecodeBounds = false; 圖片

myBitmap = BitmapFactory.decodeFile(imagePath, options);
return myBitmap;
} 內存

方法二: 資源

/** 
* 以最省內存的方式讀取本地資源的圖片
* @param context 
* @param resId 
* @return 
*/
public static Bitmap readBitMap(Context context, int resId)
{
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//獲取資源圖片 
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
} get

 

方法三: it

/** 
* 以最省內存的方式讀取本地資源的圖片 或者SDCard中的圖片
* @param imagePath 
* 圖片在SDCard中的路徑
* @return 
*/
public static Bitmap getSDCardImg(String imagePath)
{
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//獲取資源圖片 
return BitmapFactory.decodeFile(imagePath, opt);
} io

相關文章
相關標籤/搜索