android 大位元影像複製

來源:互聯網
上載者:User

     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;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.