简体   繁体   中英

Choose an image from camera or gallery

如何为用户提供从相机或图库中选择图像并检索关联的资源ID的选项?

Try this as an intent

Intent i = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);

Here is how you retreive the returned image.

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

switch(requestCode) { 
case REQ_CODE_PICK_IMAGE:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();


        Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM