当前位置: 首页 > 知识库问答 >
问题:

Android:我如何将相机或图库意图联系在一起

段干高歌
2023-03-14

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

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

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

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

有什么示例代码可以做到吗?谢了。

共有3个答案

韩博厚
2023-03-14

如果您想显示手机中安装的所有可处理照片的应用程序,如照相机、多媒体资料、Dropbox等。

你可以这样做:

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.-显示带有项目列表的自定义对话框:

    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();

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

柳景胜
2023-03-14

假设您有两个意图。一个将打开一个相机,一个将打开一个画廊。我将在示例代码中将这些camaIntent和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);

正如您所问的,这就是如何将两者结合在一起(而不必创建自己的UI/对话框)。

司寇安宜
2023-03-14

如果您想从< code >相机或< code >图库一起拍照,请检查以下链接。同样的问题也贴在这里。

从画廊捕获图像

更新代码:

检查下面的代码,在这段代码中没有你想要的listview,但是它在对话框中提供了从Gallary或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();
        }
    }

}


}

还添加p在:

<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" />

将图像存储到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();
    }

}
 类似资料:
  • 我按照这个从网络视图中捕获或选择文件并上传。。。这是完美的,适用于所有android版本。。 所以在那里,我想添加作物意图。。。在相机拍摄/画廊后进行裁剪,然后从Webview上传所有这些内容 我想为Crop Image添加以下内容:。。我想在MainActivity中添加这个。。以相机和画廊的形式拍摄。。 所以我想裁剪并上传的可能是相机或画廊。。 有谁能建议我如何在主要活动中添加作物意图吗。。

  • 编辑:我调试了应用程序,并用初始化了。这消除了错误,但是现在ImageView没有得到更新,但是当我从Gallery中选择image时,它已经更新了。

  • 有个开发需求,是将管线在地图或示意图上画出来,再进行管线与图表联动,因为不能使用外网,百度地图之类的估计用不了,有没有其它的好方法可以应用?

  • 此外,我尝试使用onSaveInstanceState但没有任何效果,下面是我的代码: 多谢了。

  • 我想从摄像机中捕获视频并保存在应用程序目录中(不要将视频保存在设备库中),然后将视频路径插入数据库以加载并显示在我的应用程序中 我在活动中尝试: 但是当转到文件目录时,视频大小为0Kb!!并保存到设备库如何解决这个问题?谢谢

  • 本文向大家介绍Android相机、图册demo,包括了Android相机、图册demo的使用技巧和注意事项,需要的朋友参考一下 本文为大家分享了Android相机、图册基本demo,供大家参考,具体内容如下 下面分享具体Android 调用相机、打开相册、裁剪图片的实现代码,内容如下 以上就是关于Android相机、图册的基本操作内容,希望对大家学习Android软件编程有所帮助。