我想在Android中从外部存储加载最新图像。
Do you have any ideas how to get the name of the latest image?
目前,我以这种方式从图库中加载某张图片:
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
?
答案 0 :(得分: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);
}
}
已更新:
如果您想要从为创建图像而创建的某个目录中加载图像,则需要确保在每个设备中创建某个目录。您可以使用while循环遍历所有图像,方法是检查BUCKET_DISPLAY_NAME
也称为相册与您创建的相册的名称相同。如果是,则获取第一张图片,因为您已经按日期时间降序排序。
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是我之前提到的专辑。
答案 1 :(得分:0)
你可以试试这个
String path = "/mnt/sdcard/Videos/Videoname"; // Your path
String fileName = new File(path).getName(); // you file name