Android의 파일 경로에서 컨텐츠 uri 가져오기
이미지의 절대 경로를 알고 있습니다(예: /sdcard/cats.jpg).이 파일에 대한 내용 uri를 얻을 수 있는 방법이 있습니까?
실제로 제 코드에서는 이미지를 다운로드하여 특정 위치에 저장합니다.ImageView 인스턴스에서 이미지를 설정하려면 현재 경로를 사용하여 파일을 열고 바이트를 가져와 비트맵을 만든 다음 ImageView 인스턴스에서 비트맵을 설정합니다.이것은 매우 느린 프로세스입니다. 대신 컨텐츠 uri를 얻을 수 있다면 매우 쉽게 방법을 사용할 수 있습니다.imageView.setImageUri(uri)
사용:
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
또는 다음과 함께:
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
갱신하다
여기에서는 미디어(이미지/비디오)가 이미 콘텐츠 미디어 공급자에 추가된 것으로 가정합니다.그렇지 않으면 원하는 콘텐츠 URL을 정확하게 가져올 수 없습니다.대신 URI 파일이 있을 것입니다.
파일 탐색기 활동에 대해서도 같은 질문이 있었습니다.파일에 대한 Contenturi는 이미지, 오디오 및 비디오와 같은 미디어 저장소 데이터만 지원합니다.sdcard에서 이미지를 선택하여 이미지 콘텐츠를 얻는 코드를 알려드립니다.이 코드를 사용해 보세요, 아마도 당신에게 효과가 있을 것입니다...
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
안드로이드 Q 지원용
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
Uri picCollection = MediaStore.Images.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentValues picDetail = new ContentValues();
picDetail.put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.getName());
picDetail.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
picDetail.put(MediaStore.Images.Media.RELATIVE_PATH,"DCIM/" + UUID.randomUUID().toString());
picDetail.put(MediaStore.Images.Media.IS_PENDING,1);
Uri finaluri = resolver.insert(picCollection, picDetail);
picDetail.clear();
picDetail.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(picCollection, picDetail, null, null);
return finaluri;
}else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
} else {
return null;
}
}
}
허용된 솔루션이 귀사의 목적에 가장 적합할 수도 있지만 실제로 제목에 있는 질문에 답하는 것은 다음과 같습니다.
내 앱에서, 나는 URI에서 경로를 가져와야 하고 경로에서 URI를 가져와야 합니다.전자:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
후자(비디오용이지만 MediaStore를 대체하여 오디오, 파일 또는 다른 유형의 저장된 콘텐츠에도 사용할 수 있습니다.MediaStore용 오디오(등).비디오):
/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
기본적으로,DATA
의 열.MediaStore
파일 경로를 저장하므로 해당 정보를 사용하여 검색할 수 있습니다.
이 코드는 2.2 이미지에 대해 작동합니다. 다른 미디어 유형이 있는지는 확실하지 않습니다.
//Your file path - Example here is "/sdcard/cats.jpg"
final String filePathThis = imagePaths.get(position).toString();
MediaScannerConnectionClient mediaScannerClient = new
MediaScannerConnectionClient() {
private MediaScannerConnection msc = null;
{
msc = new MediaScannerConnection(getApplicationContext(), this);
msc.connect();
}
public void onMediaScannerConnected(){
msc.scanFile(filePathThis, null);
}
public void onScanCompleted(String path, Uri uri) {
//This is where you get your content uri
Log.d(TAG, uri.toString());
msc.disconnect();
}
};
컨텐츠 URI를 만드는 가장 쉽고 강력한 방법content://
파일에서 파일 공급자를 사용합니다.File Provider에서 제공하는 URI는 다른 앱과 파일을 공유하기 위한 URI도 제공할 수 있습니다.의 절대 경로에서 파일 URI를 가져오려면 다음과 같이 하십시오.File
DocumentFile.fromFile(새 파일(경로, 이름))을 사용할 수 있으며 API 22에 추가되었으며 아래 버전에 대해 null을 반환합니다.
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
사용을 기준으로 이 두 가지 방법을 사용할 수 있습니다.
Uri uri = Uri.parse("String file location");
또는
Uri uri = Uri.fromFile(new File("string file location"));
저는 두 가지 방법과 두 가지 일을 모두 시도했습니다.
늦었지만, 미래에 누군가를 도울 수도 있습니다.
파일의 컨텐츠 URI를 가져오려면 다음 방법을 사용할 수 있습니다.
FileProvider.getUriForFile(Context context, String authority, File file)
컨텐츠 URI를 반환합니다.
설정 방법에 대해 알아보려면 이 항목을 참조하십시오.FileProvider
코드를 작성하지 않고 adb 셸 CLI 명령을 사용하여 파일 ID 가져오기:
adb shell content query --uri "content://media/external/video/media" | grep FILE_NAME | grep -Eo " _id=([0-9]+)," | grep -Eo "[0-9]+"
Android N 이전 버전을 지원하려면 검증을 사용하는 것이 좋습니다. 예:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = Uri.parse(filepath);
} else{
imageUri = Uri.fromFile(new File(filepath));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
} else{
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
}
아래 코드 스니펫을 시도할 수 있습니다.
public Uri getUri(ContentResolver cr, String path){
Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Files.getContentUri(VOLUME_NAME,id);
}
if(ca != null) {
ca.close();
}
return null;
}
언급URL : https://stackoverflow.com/questions/3004713/get-content-uri-from-file-path-in-android
'programing' 카테고리의 다른 글
Angular 2에서 부트스트랩 navbar "active" 클래스를 설정하는 방법은 무엇입니까? (0) | 2023.07.30 |
---|---|
드롭다운에서 공백 뒤에 데이터 목록이 완전한 이름을 표시하지 않음 (0) | 2023.07.30 |
JavaScript에서 const와 const {}의 차이점은 무엇입니까? (0) | 2023.07.30 |
MySQL과 함께 사용하는 node.js 비동기/wait (0) | 2023.07.30 |
웹 브라우저(클라이언트 측)에서 TCP 소켓 연결을 설정하는 방법은 무엇입니까? (0) | 2023.07.30 |