2017-01-03 43 views
-1

我想從Android的外部存儲中加載最新的圖像。從Android的外部存儲獲取最新的圖像

File externalDirectory = Environment.getExternalStorageDirectory(); 

    File directory = new File (externalDirectory.getAbsolutePath()); 
    File file = new File(directory, "pic.jpg"); 

    FileInputStream streamIn = null; 
    try { 
     streamIn = new FileInputStream(file); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

那麼,有沒有辦法來加載latest

Do you have any ideas how to get the name of the latest image?  

目前,我從畫廊這種方式加載某些圖片?

+0

你想用戶選擇圖像或直接加載圖像 – Lucifer

+0

我想要加載的圖像。我只需要知道最近的圖像的名稱 – mafioso

+0

你有路徑嗎? – Lucifer

回答

2
String[] projection = new String[]{ 
    MediaStore.Images.ImageColumns._ID, 
    MediaStore.Images.ImageColumns.DATA, 
    MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, //the album it in 
    MediaStore.Images.ImageColumns.DATE_TAKEN, 
    MediaStore.Images.ImageColumns.MIME_TYPE 
    }; 
final Cursor cursor = getContext().getContentResolver() 
     .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, 
       null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"); 

// Put it in the image view 
if (cursor.moveToFirst()) { 
    final ImageView imageView = (ImageView) findViewById(R.id.pictureView); 
    String imageLocation = cursor.getString(1); 
    File imageFile = new File(imageLocation); 
    if (imageFile.exists()) { // TODO: is there a better way to do this? 
     Bitmap bm = BitmapFactory.decodeFile(imageLocation); 
     imageView.setImageBitmap(bm);   
    } 
} 

使用

更新

,如果你的意思是你想從一個特定的目錄中創建用於存儲圖像,你需要確保每個設備加載圖像,某些目錄被建造。您可以通過檢查BUCKET_DISPLAY_NAME(也稱爲專輯)與創建的專輯名稱相同來使用while循環遍歷所有圖像。如果是,請先獲得第一張照片,因爲您已按照日期時間按降序排序。

int albumColumn = cur.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME); 

do{ 
    String album = cur.getString(albumColumn); 
    if(album == "YOUR CREATE DIR"){ 
     break; 
    } 
}while(cursor.moveToNext()); 

將此代碼與您自己的邏輯集成到上面的代碼中。基本上BUCKET_DISPLAY_NAME是我之前提到的專輯。

+0

那麼getContext是什麼?在我的活動中,我無法訪問 – mafioso

+0

使用您的上下文來替換它。 getApplicationContext()如果你在activity中,getActivity()如果​​你在fragment中。如果你在活動中,你也可以使用這個或者Youractivity.this。 –

+0

好的作品從畫廊加載,但我的圖像總是存儲在'Environment.getExternalStorageDirectory()',所以我如何訪問該路徑?或者如何將我的照片保存在圖庫中? – mafioso

0

,你可以嘗試這個

String path = "/mnt/sdcard/Videos/Videoname"; // Your path 

String fileName = new File(path).getName(); // you file name 
相關問題