簡體   English   中英

如何在Android中將`content:// media / external / images / media / Y`轉換為`file:/// storage / sdcard0 / Pictures / X.jpg`?

[英]how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

我正在嘗試從我的Android應用程序將圖像上傳到Google雲端硬盤,

基於本教程

當我調試他們的示例項目時,我看到一個典型的fileUri =

file:///storage/sdcard0/Pictures/IMG_20131117_090231.jpg

在我的應用中,我想上傳現有照片。

我這樣檢索它的路徑

     private void GetAnyImage()
        {
            File dir = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/Pictures/Screenshots"); 
                              // --> /storage/sdcard0/Pictures/Screenshots

            Log.d("File path ", dir.getPath());
            String dirPath=dir.getAbsolutePath();
            if(dir.exists() && dir.isDirectory()) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setType("image/*");
                startActivityForResult(intent,REQUEST_ID);
            }  
        }

並最終得到這個典型的文件Uri = content://media/external/images/media/74275

但是,運行此行代碼時

  private void saveFileToDrive() {

    //  progressDialog = ProgressDialog.show(this, "", "Loading...");

    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          // File's binary content
          java.io.File fileContent = new java.io.File(fileUri.getPath());
          FileContent mediaContent = new FileContent("image/jpeg", fileContent);

      // File's metadata.
      File body = new File();
      body.setTitle(fileContent.getName());
      body.setMimeType("image/jpeg");

      File file = service.files().insert(body, mediaContent).execute();

我收到一個錯誤:

java.io.FileNotFoundException: /external/images/media/74275: open failed: ENOENT (No such file or directory)

我該如何解決?

如何將content://media/external/images/media/Yfile:///storage/sdcard0/Pictures/X.jpg

這樣的事情對您有用嗎? 這是查詢內容解析器以查找為該內容條目存儲的文件路徑數據

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

這最終將為您提供一個絕對的文件路徑,您可以從中構建文件uri

如果您只想要位圖,這也可以

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

樣本uri:content:// media / external / images / media / 12345

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM