如何在Android上通过编程方式从设备存储中获取照片
如何自动从下载目录设置图片?
getImageUri(String imageName){
Uri uri = Uri.parse("/download/1A258.png");
imageView.setImageURI(uri);
}
解决方案
我猜你想访问Android公共下载文件夹中的png文件。
你的 Uri.parse("/download/1A258.png") 将解析为根目录下的文件路径 /download/1A258.png,在Android设备的根目录下并不存在。在许多设备上,主共享下载目录通常位于 /storage/emulated/0/Download/。另一个问题是,在Android 10及以上版本中,直接访问文件会受到作用域存储的限制。对其中的文件的访问取决于是谁把文件放进这个目录;如果是你的应用,那么可以使用MediaStore.Downloads获取;如果是其他应用(如Chrome等),则应该使用存储访问框架(Storage Access Framework)。
- 你的应用把文件存储在下载文件夹中(使用MediaStore或 DownloadManager),然后使用MediaStore访问——无需特殊权限:
``` private void setImageFromDownloads(String imageName) { String[] projection = { MediaStore.Downloads._ID }; String selection = MediaStore.Downloads.DISPLAY_NAME + " = ?"; String[] selectionArgs = { imageName };
try (Cursor cursor = getContentResolver().query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null)) {
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(
cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID));
// give you : content://media/external/downloads/<id>
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Downloads.EXTERNAL_CONTENT_URI, id);
imageView.setImageURI(contentUri);
}
```
} }
- 如果是其他应用把文件存储在下载文件夹中,那么你应该使用SAF。你可以在这里了解:https://developer.android.com/training/data-storage/shared/media#saf-other-apps-downloads:
如果你的应用想要访问属于MediaStore.Downloads集合、但不是你创建的文件,你必须使用存储访问框架。
处理结果:
private final ActivityResultLauncher<Intent> pickImageLauncher =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
imageView.setImageURI(uri);
}
});
启动文件选择器:
private void pickImageFromDownloads() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
pickImageLauncher.launch(intent);
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。