2017-01-03 59 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 
相关问题