0

我正在尋找下載Bitmaps陣列的最佳方法,稍微修改它們,然後保存到SD卡。如何下載Bitmaps並保存到SD卡而不會耗盡內存?

我聽說ByteArrayOutputStream是一個壞主意,因爲它將圖像加載到設備的RAM中。相反,我可能應該使用類似於BufferedInputStreamFileOutputStream的東西,但是我不知道如何在使用此方法保存之前更改位圖。

感謝

回答

1

你不會喜歡的答案:你不能(至少不與Android框架)。

唯一的選擇是downscale the image,以便它適合內存;並定期撥打recycle()System.gc()儘快釋放內存。

+0

是的,這幾乎是我所害怕的。我猜我可以做的是使用BufferedInputStream下載圖像,然後做我的位圖操作。不是世界上最好的東西,但幸運的是我使用AsyncTask下載圖像,所以我可以在onPostExecute()方法中做Bitmap的東西。非常感謝:) –

+0

然後另一個建議:實現你的長時間運行的任務(下載,圖像處理)使用'IntentService'而不是'AsyncTask'(參見http://stackoverflow.com/questions/2620917/how-to-handle-an-asynctask-during-screen-rotation http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html) – rds

1

您可以從InputStream使用創建位圖:

Bitmap bm = BitmapFactory.decodeStream(inputStream); 

,然後選擇已經處理完您的Bitmap並儲存它們,你必須使用:

bm.recycle(); 
bm = null; 

避免OutOfMemoryExceptions

編輯:

對於其寫入文件:

OutputStream fos=new BufferedOutputStream(new FileOutputStream(filePath)); 
byte buf[]=new byte[1024]; 
int len; 
while((len=is.read(buf))>0) 
    fos.write(buf,0,len); 
fos.close(); 
is.close(); 
+0

是的,謝謝,我知道,但是如何在不使用ByteArrayOutputStream的情況下將位圖寫入SD卡上的文件? –

+0

感謝你的 - 但你的代碼是直接從inputStream讀取,而不是位圖:( –