2015-06-10 60 views
0

我有一個要求,在Android應用程序中存儲圖像,它不應該出現在畫廊。所以,我決定在應用程序的「資產」文件夾中有SQLite數據庫,我會將圖像路徑存儲到數據庫中。問題是,如果沒有SDCard,那麼我如何獲得圖像路徑?或者有沒有一種方法可以隱藏我的應用拍攝的圖像出現在畫廊中。以下是我目前用來將圖像存儲在外部目錄中的代碼。圖像到SQLite,而不是畫廊

photo = new File(Environment.getExternalStoragePublicDirectory(Environment .DIRECTORY_PICTURES), imageName); 
//imageName=current timestamp 

回答

0

我用這個方法將圖像保存到內部存儲(和返回的路徑保存到您的sqlite)使用

private String saveToInternalStorage(Bitmap bitmapImage, String filename){ 
    ContextWrapper cw = new ContextWrapper(getApplicationContext()); 
    // path to /data/data/yourapp/app_data/imageDir 
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); 
    Log.d("dir", directory.toString()); 
    // Create imageDir 
    File mypath=new File(directory,filename); 
    Log.d("path", mypath.toString()); 

    FileOutputStream fos = null; 
    try { 

     fos = new FileOutputStream(mypath); 

     // Use the compress method on the BitMap object to write image to the OutputStream 
     bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); 
     fos.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    Log.d("ingesteld path", directory.getAbsolutePath()); 
    return directory.getAbsolutePath(); 
} 

加載圖像:

private void loadImageFromStorage(String path, String name) 
{ 
    try { 
     File f=new File(path, name); 
     Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); 

     // Do something with your bitmap 
    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 

} 

希望這是有用的。

+0

謝謝你Opoo。我正在使用ByteArrayOutputStream而不是FileOutputStream來寫入內存。是否可觀?另外,你能幫我理解哪個路徑被存儲到數據庫..是它的路徑 - 「/ data/data/yourapp/app_data/imageDir」? – Kittu

+1

我不知道它是否工作原理相同,在我的情況下,使用上面使用的方法存儲的路徑是「/data/data/com.example.app/app_imageDir」。 String path = saveToInternalStorage(bitmap,name); question.setImagePath(path); – Stefan