Social Icons

2010年10月21日 星期四

如何在程式中呼叫相本來選取相片

上一篇文章中提到了如何在程式中呼叫照相機來拍照,這次也介紹一下如何從程式中呼叫相本來選取相片,並回傳。

呼叫相本選取照片,記得還是需要自行定義回傳碼 SELECT_IMAGE_ACTIVITY_REQUEST_CODE
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
startActivityForResult(intent, SELECT_IMAGE_ACTIVITY_REQUEST_CODE);


處理回傳的相片,在onActivityResult中,先判斷回傳碼正確,再如下處理:
if (resultCode == RESULT_OK) {
    Cursor cursor = null;
    try {
     cursor = getContentResolver().query(data.getData(), null, null, null, null);
     if (cursor.moveToFirst()) {
      int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
      String absoluteFilePath = cursor.getString(idx);
      if (absoluteFilePath != null)
       photoPath = absoluteFilePath;
     }
   } finally {
    if (cursor != null) {
     cursor.close();
    }
   }
}

1 則留言:

  1. 你好,請問一下如果只想要在特定相本裡選圖片
    那code 應該要如何?
    我這樣似乎沒有效,還是會看到所有的相片
    File file = new File(albumPath);
    intent.setDataAndType(Uri.fromFile(file), "image/*");
    謝謝!

    回覆刪除