2015-05-29 57 views
41

我的應用程序能夠從圖庫中選擇照片。確切地說我想從這個選擇文件路徑。使用新的Google相冊應用程序選擇照片已損壞

這是創建用於選擇照片的意圖代碼:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, 
     MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    photoPickerIntent.setType("image/*"); 
    startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO); 

這是從URI獲取文件路徑的代碼:

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

前谷歌照片昨日更新的應用程序一切都工作正常精細。 現在path解析URI後爲空。

URI與此類似:content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL

我也試圖創建Intent.ACTION_GET_CONTENT行動的意圖 - 沒有運氣。

回答

41

下面的代碼爲我工作到谷歌最新的照片獲取內容URI爲好。 我曾嘗試寫入臨時文件並返回臨時映像URI,如果它具有內容URI的權限。

您可以嘗試相同的:

public static String getImageUrlWithAuthority(Context context, Uri uri) { 
    InputStream is = null; 
    if (uri.getAuthority() != null) { 
     try { 
      is = context.getContentResolver().openInputStream(uri); 
      Bitmap bmp = BitmapFactory.decodeStream(is); 
      return writeToTempImageAndGetPathUri(context, bmp).toString(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     }finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return null; 
} 

public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 
+2

崩潰我已經接受了這個答案,雖然對於我們的流程這是一個解決方法。但它允許應用程序恢復到完全工作狀態,所以這很重要。一個注意:我沒有做一個從InputStream的位圖解碼 - 我已經將它複製到一些'File tempFile = new File(「path_to_my_temp_directory」);'然後用最後一個爲所有的東西。 –

+0

@Akhil非常感謝! – Petro

+0

'is = context.getContentResolver()。openInputStream(uri);'返回null。我似乎無法找到從Google照片應用中挑選圖片的任何解決方案。如果有人有工作解決方案,請分享。 – ArJ

6

這肯定是一個解決辦法,但你可以提取實內容URI這顯然成爲嵌入式出於某種原因:content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209

我能夠創建一個新的URI與authority=media and path=external/images/media/xxx和內容解析返回一個真正的URL。

示例代碼:

String unusablePath = contentUri.getPath(); 
int startIndex = unusablePath.indexOf("external/"); 
int endIndex = unusablePath.indexOf("/ACTUAL"); 
String embeddedPath = unusablePath.substring(startIndex, endIndex); 

Uri.Builder builder = contentUri.buildUpon(); 
builder.path(embeddedPath); 
builder.authority("media"); 
Uri newUri = builder.build(); 
+1

你可以共享任何的源代碼是什麼? –

+0

您能否分享此解決方案的來源?現在在這個問題上停留了幾天! – Vishy

+2

新增示例代碼 –

相關問題