首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 從 MediaStore URI 取得真實檔案路徑

     編輯:程式設計綜合問答

在 Android 應用中透過 ACTION_PICK 或 ACTION_GET_CONTENT 選取圖片時,回傳的 Uri 通常為 content:// 結構,無法直接作為檔案路徑使用。若需將圖片載入 Bitmap 或進行檔案操作,必須透過 ContentResolver 查詢 MediaStore 取得實際路徑(_data 欄位)。

核心方法

public String getRealPathFromURI(Context context, Uri contentUri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            return cursor.getString(columnIndex);
        }
    } finally {
        if (cursor != null) cursor.close();
    }
    return null;
}

注意事項

  • 權限:Android 10 (API 29) 以上建議改用 MediaStore 直接開啟 InputStream,避免依賴檔案路徑。
  • 非同步處理:查詢操作應在背景執行緒進行,避免阻塞 UI。
  • 相容性:部分裝置或雲端相簿(如 Google Photos)可能不支援 _data 欄位,需加入 fallback 機制。

現代替代方案

API 29+ 可直接使用 ContentResolver.openInputStream(uri) 讀取位圖,無需解析路徑:

InputStream is = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();

掌握 URI 轉路徑技巧,能讓圖片選取與載入流程更穩健,適應各 Android 版本與儲存架構變化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved