簡體   English   中英

Android如何將Camera或Gallery Intent一起調用

[英]Android How can I call Camera or Gallery Intent Together

如果我想從原生相機捕捉圖像,我可以這樣做:

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

我想知道如何把上面兩個放在一起。
這意味着從畫廊或捕捉照片獲取圖像 選擇一個動作

有沒有示例代碼可以做到這一點? 謝謝。

如果您想從CameraGallery Intent Together Camera ,請查看以下鏈接。 同樣的問題也貼在這里。

在android中捕獲圖庫和相機中的圖像

更新的代碼:

檢查下面的代碼,在這段代碼中你不想進入listview,但它在dialogBox中給出了選項,從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();
        }
    }

}


}

還要添加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" />

將圖像存儲到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();
    }

}

假設你有兩個意圖。 一個可以打開相機,一個可以打開一個畫廊。 我將在示例代碼中調用這些cameraIntent和gallerIntent。 您可以使用意圖選擇器來組合這兩個:

科特林

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 /對話框)。

如果您想要顯示手機中安裝的所有可以處理相機,圖庫,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

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

當你想從圖庫中獲取圖像時,只需另外一種方法:

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

我想我之前遇到過你的情況。 我們的想法是,我們將創建一個帶有可選項的單項列表警告對話框,每個項目將執行由您自己的意圖定義的唯一功能。 如果您想要項目列表中每個元素的圖標,則需要做更多的工作。 希望它會有所幫助。

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

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

實際上你的對話標題是“選擇一個動作”意味着對話框實際上是一個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);
        }
    }

如果在OS> = 23上運行,您可能需要自己解決權限

這是我的演示:(由於OS不同,外觀差異)
在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM