android sdk 中的Bitmap類提供了一個執行個體方法copy用來複制位圖,該方法在複制較大圖像時
容易造成記憶體溢出;原因:該方法在複制圖像時将在記憶體中儲存兩份圖像資料。
為了解決這個問題,可以将大圖像寫入SD卡中的一個臨時檔案中,然後再從檔案中取出圖像。
根據以上思路用代碼如下:
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;
}