2014-06-19 57 views
0

我目前將從互聯網上下載的圖像保存到磁盤。我希望能夠在用戶關閉應用程序時刪除圖像。我想將所有圖像保存在一個文件夾中,以便刪除它們。我做了getActivity().getCacheDir().getAbsolutePath()+ File.separator + "newfoldername"以獲取文件夾的路徑。不知道如何將圖像添加到文件夾中。從文件夾中刪除緩存的圖像

public void saveImage(Context context, Bitmap b, String name_file, String path) { 
    FileOutputStream out; 
    try { 
     out = context.openFileOutput(name_file, Context.MODE_PRIVATE); 
     b.compress(Bitmap.CompressFormat.JPEG,90, out); 
     out.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public Bitmap getImageBitmap(Context context, String name) { 
    try { 
     FileInputStream fis = context.openFileInput(name); 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inSampleSize = 1; 
     Bitmap b = BitmapFactory.decodeStream(fis,null, options); 
     b.getAllocationByteCount()); 
     fis.close(); 
     return b; 
    } catch (Exception e) {} 
    return null; 
} 

回答

1

你不應該因爲你不能依靠它按照文件的緩存文件夾中保存圖像。更好的方法是將它們存儲在SD卡上。按照文檔:

public abstract File getCacheDir() 

返回到文件系統中的專用緩存目錄的絕對路徑。這些文件將在設備存儲空間不足時被首先刪除。這些文件將被刪除時無法保證。注意:您不應該依賴系統爲您刪除這些文件;對於緩存文件佔用的空間量,您應始終擁有合理的最大值(例如1 MB),並在超過該空間時修剪這些文件。

保存

private String saveToInternalSorage(Bitmap bitmapImage){ 
    File directory = getApplicationContext().getDir("MY_IMAGE_FOLDER" 
    ,Context.MODE_PRIVATE); 

    File mypath=new File(directory,"profile.jpg"); 
    FileOutputStream fos = null; 
    try {   
     fos = new FileOutputStream(mypath); 
     bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); 
     fos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return directory.getAbsolutePath(); 
} 

用於讀取

private void loadImageFromStorage(String path) 
{ 
    try { 
     File file = new File(path, "Image.jpg"); 
     Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); 
     ImageView img = (ImageView)findViewById(R.id.my_imgView); 
     img.setImageBitmap(bitmap); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

刪除:

String dir = getApplicationContext().getDir("MY_IMAGE_FOLDER" 
    ,Context.MODE_PRIVATE); 
if (dir.isDirectory()) { 
     String[] children = dir.list(); 
     for (int i = 0; i < children.length; i++) { 
      new File(dir, children[i]).delete(); 
     } 
    } 
+0

@android戰士 - 我如何閱讀這些圖像?以及如何在應用程序關閉時刪除該文件夾。 – user3757801

+0

@ user3757801閱讀圖片是什麼意思? – CodeWarrior

+0

@ AndroidWarrior-像從保存的圖像獲取位圖,所以我可以顯示它 – user3757801

相關問題