Android 如何同时调用 Camera 或 Gallery Intent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11732872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:37:58  来源:igfitidea点击:

Android How can I call Camera or Gallery Intent Together

android

提问by jjLin

If I want to capture image from native camera, I can do:

如果我想从本机相机捕获图像,我可以这样做:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, IMAGE_CAPTURE);

If I want to get image from gallery, I can do:

如果我想从画廊获取图像,我可以这样做:

Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), SELECT_PICTURE);

I am wondering how can put the above two together.
That means GET IMAGE FROM GALLERY OR CAPTURE PHOTO Select an action

我想知道如何将上述两个放在一起。
这意味着从画廊获取图像或捕获照片 Select an action

Is there any example code to do it? Thanks.

是否有任何示例代码可以做到这一点?谢谢。

回答by Rahul Patel

If you want to take picture from Cameraor GalleryIntent Together, Then check below link. Same question also posted here.

如果您想从CameraGalleryIntent Together拍照,请查看以下链接。同样的问题也贴在这里。

Capturing image from gallery & camera in android

在android中从画廊和相机捕获图像

UPDATED CODE:

更新代码:

check below code, In this code not same as you want into listview, but it gives the option in the dialogBox choose image from Gallary OR Camera.

检查下面的代码,在此代码中与您想要进入列表视图不同,但它在对话框中提供了从画廊或相机中选择图像的选项。

public class UploadImageActivity extends Activity {
ImageView img_logo;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;

    String selectedImagePath;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main1);

    img_logo= (ImageView) findViewById(R.id.imageView1);
    img_logo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            startDialog();
        }

    });
}

private void startDialog() {
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
            getActivity());
    myAlertDialog.setTitle("Upload Pictures Option");
    myAlertDialog.setMessage("How do you want to set your picture?");

    myAlertDialog.setPositiveButton("Gallery",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent pictureActionIntent = null;

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

                }
            });

    myAlertDialog.setNegativeButton("Camera",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

                    Intent intent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(f));

                     startActivityForResult(intent,
                            CAMERA_REQUEST);

                }
            });
    myAlertDialog.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    bitmap = null;
    selectedImagePath = null;

    if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {

        File f = new File(Environment.getExternalStorageDirectory()
                .toString());
        for (File temp : f.listFiles()) {
            if (temp.getName().equals("temp.jpg")) {
                f = temp;
                break;
            }
        }

        if (!f.exists()) {

            Toast.makeText(getBaseContext(),

            "Error while capturing image", Toast.LENGTH_LONG)

            .show();

            return;

        }

        try {

            bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());

            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);

            int rotate = 0;
            try {
                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                int orientation = exif.getAttributeInt(
                        ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotate = 270;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotate = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotate = 90;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Matrix matrix = new Matrix();
            matrix.postRotate(rotate);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);



            img_logo.setImageBitmap(bitmap);
            //storeImageTosdCard(bitmap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
        if (data != null) {

            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage, filePath,
                    null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            selectedImagePath = c.getString(columnIndex);
            c.close();

            if (selectedImagePath != null) {
                txt_image_path.setText(selectedImagePath);
            }

            bitmap = BitmapFactory.decodeFile(selectedImagePath); // load
            // preview image
            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false);



            img_logo.setImageBitmap(bitmap);

        } else {
            Toast.makeText(getApplicationContext(), "Cancelled",
                    Toast.LENGTH_SHORT).show();
        }
    }

}


}

Also add pemission:

还添加许可:

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

 <uses-feature
    android:name="android.hardware.camera.autofocus"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />

store Image to sdcard:

将图像存储到 SD 卡:

private void storeImageTosdCard(Bitmap processedBitmap) {
    try {
        // TODO Auto-generated method stub

        OutputStream output;
        // Find the SD Card path
        File filepath = Environment.getExternalStorageDirectory();
        // Create a new folder in SD Card
        File dir = new File(filepath.getAbsolutePath() + "/appName/");
        dir.mkdirs();

        String imge_name = "appName" + System.currentTimeMillis()
                + ".jpg";
        // Create a name for the saved image
        File file = new File(dir, imge_name);
        if (file.exists()) {
            file.delete();
            file.createNewFile();
        } else {
            file.createNewFile();

        }

        try {

            output = new FileOutputStream(file);

            // Compress into png format image from 0% - 100%
            processedBitmap
                    .compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();

            int file_size = Integer
                    .parseInt(String.valueOf(file.length() / 1024));
            System.out.println("size ===>>> " + file_size);
            System.out.println("file.length() ===>>> " + file.length());

            selectedImagePath = file.getAbsolutePath();



        }

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

}

回答by roepit

Let's say that you have two intents. One that would open a camera, one that would open a gallery. I will call these cameraIntent and gallerIntent in the example code. You can use intent chooser to combine these two:

假设您有两个意图。一个可以打开相机,一个可以打开画廊。我将在示例代码中调用这些 cameraIntent 和 gallerIntent。您可以使用意图选择器将这两者结合起来:

Kotlin:

科特林

val chooser = Intent.createChooser(galleryIntent, "Some text here")
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent))
startActivityForResult(chooser, requestCode)

Java:

爪哇

Intent chooser = Intent.createChooser(galleryIntent, "Some text here");
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { cameraIntent });
startActivityForResult(chooser, requestCode);

This is, as you asked, how you can put the two together (without having to make your own UI/ dialog).

正如您所问的,这就是如何将两者放在一起(无需制作自己的 UI/对话框)。

回答by Felix

If you want to show all the apps installed in the phone that can deal with photos such as Camera, Gallery, Dropbox, etc.

如果要显示手机中安装的所有可以处理照片的应用程序,例如相机、图库、Dropbox 等,

You can do something like:

您可以执行以下操作:

1.- Ask for all the intents available:

1.- 询问所有可用的意图:

    Intent camIntent = new Intent("android.media.action.IMAGE_CAPTURE");
    Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
    gallIntent.setType("image/*"); 

    // look for available intents
    List<ResolveInfo> info=new ArrayList<ResolveInfo>();
    List<Intent> yourIntentsList = new ArrayList<Intent>();
    PackageManager packageManager = context.getPackageManager();
    List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0);
    for (ResolveInfo res : listCam) {
        final Intent finalIntent = new Intent(camIntent);
        finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        yourIntentsList.add(finalIntent);
        info.add(res);
    }
    List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0);
    for (ResolveInfo res : listGall) {
        final Intent finalIntent = new Intent(gallIntent);
        finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        yourIntentsList.add(finalIntent);
        info.add(res);
    }

2.- Show a custom dialog with the list of items:

2.- 显示带有项目列表的自定义对话框:

    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    dialog.setTitle(context.getResources().getString(R.string.select_an_action));
    dialog.setAdapter(buildAdapter(context, activitiesInfo),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    Intent intent = intents.get(id);
                    context.startActivityForResult(intent,1);
                }
            });

    dialog.setNeutralButton(context.getResources().getString(R.string.cancel),
            new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    dialog.show();

This is a full example: https://gist.github.com/felixgborrego/7943560

这是一个完整的例子:https: //gist.github.com/felixgborrego/7943560

回答by 0gravity

Create a button in your XML layout and the add the attribute android:onClick="takeAPicture"then in your main activity create a method with the same name from the onClickattribute.

在您的 XML 布局中创建一个按钮并添加属性,android:onClick="takeAPicture"然后在您的主活动中从该onClick属性创建一个具有相同名称的方法。

public void takeAPicture(View view){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, IMAGE_CAPTURE);
}

And just do another method for when you want to get the image from the gallery:

当您想从图库中获取图像时,只需执行另一种方法:

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

回答by Leon Yuu

I think I encountered your case before. An idea is that we will create a one item list alert dialog with selectable item, and each item will do a unique function defined by your own intention. If you want an icon for each element in items list, it should take a bit more work to do. Hope it will helpful.

我想我以前遇到过你的情况。一个想法是,我们将创建一个带有可选项目的单项列表警报对话框,每个项目将执行由您自己的意图定义的独特功能。如果您想要为 items 列表中的每个元素都有一个图标,则需要做更多的工作。希望它会有所帮助。

    String title = "Open Photo";
    CharSequence[] itemlist ={"Take a Photo",
                  "Pick from Gallery",
                  "Open from File"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.icon_app);
    builder.setTitle(title);
    builder.setItems(itemlist, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case 0:// Take Photo
                // Do Take Photo task here
                break;
            case 1:// Choose Existing Photo
                // Do Pick Photo task here
                break;
            case 2:// Choose Existing File
                // Do Pick file here
                break;
            default:
                break;
            }
        }
    });
    AlertDialog alert = builder.create();
    alert.setCancelable(true);
    alert.show();

回答by yukun qian

public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> 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<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> 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;
}

回答by Loyea

In fact your dialog title is "select an action" means the dialog is a Intent chooser actually. not a user customed dialog. The every single item presents a Intent.

实际上,您的对话框标题是“选择一个操作”,这意味着该对话框实际上是一个意图选择器。不是用户自定义的对话框。每一个项目都代表一个意图。

public void click(View view) {
        File file = getExternalFilesDir(Environment.DIRECTORY_DCIM);
        Uri cameraOutputUri = Uri.fromFile(file);
        Intent intent = getPickIntent(cameraOutputUri);
        startActivityForResult(intent, -1);
    }

    private Intent getPickIntent(Uri cameraOutputUri) {
        final List<Intent> intents = new ArrayList<Intent>();

        if (true) {
            intents.add(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
        }

        if (true) {
            setCameraIntents(intents, cameraOutputUri);
        }

        if (intents.isEmpty()) return null;
        Intent result = Intent.createChooser(intents.remove(0), null);
        if (!intents.isEmpty()) {
            result.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new Parcelable[] {}));
        }
        return result;


    }

    private void setCameraIntents(List<Intent> cameraIntents, Uri output) {
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            intent.setPackage(packageName);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
            cameraIntents.add(intent);
        }
    }

You may need solve permissions by yourself if run on OS >= 23

如果在 OS >= 23 上运行,您可能需要自己解决权限

Here's my demo:(Appearance differences since OS different)
enter image description here

这是我的演示:(由于操作系统不同,外观差异)
enter image description here