Choosing between camera and gallery for image selection

前端 未结 2 1975
攒了一身酷
攒了一身酷 2020-12-05 16:42

I am trying to allow a user to select an image, either from the gallery or by taking a picture with the camera. I tried this:

        Intent imageIntent = n         


        
2条回答
  •  孤街浪徒
    2020-12-05 17:24

    I have merged some solutions to make a complete util for picking an image from Gallery or Camera. These are the features of ImagePicker util (also in a Github lib):

    • Merged intents for Gallery and Camera resquests.
    • Resize selected big images (e.g.: 2500 x 1600)
    • Rotate image if necesary

    Screenshot:

    Edit: Here is a fragment of code to get a merged Intent for Gallery and Camera apps together. You can see the full code at ImagePicker util (also in a Github lib)

    public static Intent getPickImageIntent(Context context) {
        Intent chooserIntent = null;
    
        List intentList = new ArrayList<>();
    
        Intent pickIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePhotoIntent.putExtra("return-data", true);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
        intentList = addIntentsToList(context, intentList, pickIntent);
        intentList = addIntentsToList(context, intentList, takePhotoIntent);
    
        if (intentList.size() > 0) {
            chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                    context.getString(R.string.pick_image_intent_text));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
        }
    
        return chooserIntent;
    }
    
    private static List addIntentsToList(Context context, List list, Intent intent) {
        List resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resInfo) {
            String packageName = resolveInfo.activityInfo.packageName;
            Intent targetedIntent = new Intent(intent);
            targetedIntent.setPackage(packageName);
            list.add(targetedIntent);
        }
        return list;
    }
    

提交回复
热议问题