Android 从手机相册获取图片 uri 路径 从相机获取照片

从手机相册获取图片

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(IMAGE_TYPE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (resultCode != RESULT_OK) {        //此处的 RESULT_OK 是系统自定义得一个常量
        Log.e(TAG,"ActivityResult resultCode error");
        return;
    }

    Bitmap bm = null;

    //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
    ContentResolver resolver = getContentResolver();

    //此处的用于判断接收的Activity是不是你想要的那个
    if (requestCode == IMAGE_CODE) {
        try {
            Uri originalUri = data.getData();        //获得图片的uri 

            bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片

            //获取图片的路径:

            String[] proj = {MediaStore.Images.Media.DATA};

            //好像是android多媒体数据库的封装接口,具体的看Android文档
            Cursor cursor = managedQuery(originalUri, proj, null, null, null); 
            //按我个人理解 这个是获得用户选择的图片的索引值
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            //将光标移至开头 ,这个很重要,不小心很容易引起越界
            cursor.moveToFirst();
            //最后根据索引值获取图片路径
            String path = cursor.getString(column_index);
        }catch (IOException e) {
            Log.e(TAG,e.toString()); 
        }
    }
}

从相机获取照片

public final static int REQUEST_IMAGE_CAPTURE = 1;

//start
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

//receive
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
      Log.d(TAG, "canceled or other exception!");
      return;
    }

    if (requestCode == REQUEST_IMAGE_CAPTURE) {
      Log.d(TAG, "REQUEST_IMAGE_CAPTURE");
      Bitmap bitmap;
      try {
        bitmap = data.getExtras().getParcelable("data"); 
        //TODO:do something with bitmap, Do NOT forget call Bitmap.recycler();
      } catch (ClassCastException e){
           //do something with exceptions
        e.printStackTrace();
      } 
    }

  }

你可能感兴趣的:(Android 从手机相册获取图片 uri 路径 从相机获取照片)