반응형

안드로이드에서 가끔 File Uri나 Absolute path uri로 나타나있는 uri를 Content Uri로 변환하는 방법을 정리해 두고자 한다.

 

이때 File Uri를 기준으로 했지만 Absolute path가 들어왔을 때는 아래 코드 도중부터 시작하면 된다.

 

Uri uri = Uri.parse(uriString);                       

// File을 이용하여 Absolute path를 구해주고 이를통해 ContentUri를 얻어낸다.
// 이때 getAbsolutePath의 리턴으로는 '/storage/emulated/0/~~/file.jpeg'같은 식으로 나온다.
File file = new File(uri.getPath());
Uri contentUri = getImageContentUri(context, file.getAbsolutePath());
public static Uri getImageContentUri(Context context, String absPath) {
    Log.v(TAG, "getImageContentUri: " + absPath);

    Cursor cursor = context.getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        , new String[] { MediaStore.Images.Media._ID }
        , MediaStore.Images.Media.DATA + "=? "
        , new String[] { absPath }, null);

    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , Integer.toString(id));

    } else if (!absPath.isEmpty()) {
         ContentValues values = new ContentValues();
         values.put(MediaStore.Images.Media.DATA, absPath);
         return context.getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
        return null;
    }
}

 

 

https://stackoverflow.com/questions/23207604/get-a-content-uri-from-a-file-uri

https://codeday.me/en/qa/20190313/15521.html

 

 

반응형