Search code examples
javaandroidmedia

Choose an image from camera or gallery


How can I offer the user the option of choosing an image from the camera or gallery and retrieve the Resource id associated?


Solution

  • 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);
        }
    }
    }
    

    (code from https://stackoverflow.com/a/2508138)