2013-12-11 77 views
9

嘗試從SD卡中僅挑選一個特定圖像。我能夠從kikat中的圖庫和照片應用中挑選圖像。但未獲取文件路徑,當我從最近選擇圖像獲取文件路徑爲空。我試過https://stackoverflow.com/a/2636538/1140321[Android - Kitkat]通過編程從Android內置圖庫應用中獲取圖像

+0

你真的需要的ImagePath?你正在上傳圖片嗎?或者只是想在imageview中顯示它? –

+0

我只是想在圖像視圖中顯示.. – Meher

+0

你可以發佈你的代碼,因爲它會更容易我回答 –

回答

33

這適用於奇巧

public class BrowsePictureActivity extends Activity{ 

private static final int SELECT_PICTURE = 1; 

private String selectedImagePath; 
private ImageView imageView; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.browsepicture); 
    imageView = (ImageView)findViewById(R.id.imageView1); 

    ((Button) findViewById(R.id.button1)) 
      .setOnClickListener(new OnClickListener() { 

       public void onClick(View arg0) { 
        Intent intent = new Intent(); 
        intent.setType("image/*"); 
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        startActivityForResult(Intent.createChooser(intent, 
          "Select Picture"), SELECT_PICTURE); 
       } 
      }); 
} 

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
     if (requestCode == SELECT_PICTURE) { 
      Uri selectedImageUri = data.getData(); 
      if (Build.VERSION.SDK_INT < 19) { 
       selectedImagePath = getPath(selectedImageUri); 
       Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath); 
       imageView.setImageBitmap(bitmap); 

      } 
      else { 
       ParcelFileDescriptor parcelFileDescriptor; 
       try { 
        parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r"); 
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); 
        parcelFileDescriptor.close(); 
        imageView.setImageBitmap(image); 

       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

/** 
* helper to retrieve the path of an image URI 
*/ 
public String getPath(Uri uri) { 
     if(uri == null) { 
      return null; 
     } 
     String[] projection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = getContentResolver().query(uri, projection, null, null, null); 
     if(cursor != null){ 
      int column_index = cursor 
      .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      return cursor.getString(column_index); 
     } 
     return uri.getPath(); 
} 

} 

您需要添加權限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

+0

代碼不一樣...檢查是否檢查kitkat的if else條件:P –

+0

您是否嘗試過代碼?它爲你工作? –

+0

@SunilMishra如何從kit-kat中獲得圖像路徑? –

相關問題