public static int computeSampleSize(BitmapFactory.Options opts, int minSideLength, int maxNumOfPixels)
{
int initialSize = computeInitialSampleSize(opts, minSideLength, maxNumOfPixels);
int roundedSize;
if(initialSize <= 8)
{
roundedSize = 1;
while(roundedSize < initialSize)
{
roundedSize<<=1;
}
}
else
{
roundedSize = (initialSize+7)/8*8;
}
return roundedSize;
}
public static int computeInitialSampleSize(BitmapFactory.Options opts, int minSideLength, int maxNumOfPixels)
{
double w = opts.outWidth;
double h = opts.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int)Math.ceil(Math.sqrt(w*h/maxNumOfPixels));
int upperBound = (maxNumOfPixels == -1) ? 128 : (int)Math.min(Math.floor(w/minSideLength)
,Math.floor(h/minSideLength));
if(upperBound < lowerBound)
{
return lowerBound;
}
if((maxNumOfPixels == -1) && (minSideLength == -1))
{
return 1;
}
else if(minSideLength == -1)
{
return lowerBound;
}
else
{
return upperBound;
}
}
public Bitmap readBitmap(String img_file)
{
Bitmap bmp = null;
Log.d(TAG, "readBitmap");
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true; //設定BitmapFactory.decodeStream不decode,只抓取原始圖片的長度和寬度
BitmapFactory.decodeFile(img_file, opt);//抓取原始圖片的長度和寬度
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
opt.inPurgeable = true;
opt.inInputShareable = true;
opt.inSampleSize = computeSampleSize(opt, -1, 128*128); //計算適合的縮放大小,避免OutOfMenery
opt.inJustDecodeBounds = false;//設定BitmapFactory.decodeStream需decodeFile
bmp = BitmapFactory.decodeFile(img_file, opt);
if(bmp != null)
{
Log.d(TAG, "decodeFile success");
return bmp;
}
else
{
Log.d(TAG, "bmp == null");
return null;
}
}
public void showPicture(String pic_path)
{
last_bmp = bmp;
bmp = readBitmap(pic_path);
if(last_bmp != null)
{
if(!last_bmp.isRecycled())
{
last_bmp.recycle();
last_bmp = null;
System.gc(); // system garbage recycle
}
}
}
public void onDestory()
{
if(bmp != null)
{
if(!bmp.isRecycled())
{
bmp.recycle();
bmp = null;
System.gc(); // system garbage recycle
}
}
}
2012年6月26日 星期二
Android 省記憶體的方式讀取檔案的圖片
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言