android sdk 中的Bitmap類提供了一個執行個體方法copy用來複製位元影像,該方法在複製較大映像時
容易造成記憶體溢出;原因:該方法在複製映像時將在記憶體中儲存兩份映像資料。
為瞭解決這個問題,可以將大映像寫入SD卡中的一個臨時檔案中,然後再從檔案中取出映像。
根據以上思路用代碼如下:
/**
* 根據原位元影像產生一個新的位元影像,並將原位元影像所佔空間釋放
* @param srcBmp 原位元影像
* @return 新位元影像
*/
public static Bitmap copy(Bitmap srcBmp){
Bitmap destBmp=null;
try{
//建立一個臨時檔案
File file = new File("/mnt/sdcard/temp/tmp.txt");
file.getParentFile().mkdirs();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
int width = srcBmp.getWidth();
int height = srcBmp.getHeight();
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width*height*4);
//將位元影像資訊寫進buffer
srcBmp.copyPixelsToBuffer(map);
//釋放原位元影像佔用的空間
srcBmp.recycle();
//建立一個新的位元影像
destBmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
map.position(0);
//從臨時緩衝中拷貝位元影像資訊
destBmp.copyPixelsFromBuffer(map);
channel.close();
randomAccessFile.close();
}
catch(Exception ex){
destBmp=null;
}
return destBmp;
}