Android - 拍摄/选择照片并将其放在正确的图像视图中

时间:2016-04-20 14:09:08

标签: android android-intent camera

问题:用户最多可以拍摄/选择3张照片。我在弄清楚如何填写3个案件时遇到了麻烦;我不确定如何检索相应的ImageView ID。

Here is the UI

我试过putextra,因为我正在使用 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE),但似乎无法使用putextra方法(我不会检索任何额外的)

因此,让我与您分享代码,如果您采取不同的行动,请随时告诉我。非常感谢!

所以我在这里抓住点击事件并将V.getID传递给将处理与选择/拍照相关的操作的方法。

@Override
public void onClick(View v) {

    switch(v.getId()){
        case R.id.add_item_give_button:
            checkAddedItem();
            break;
        case R.id.add_item_image_1:
            selectImage(v.getId());
            break;
        case R.id.add_item_image_2:
            selectImage(v.getId());
            break;
        case R.id.add_item_image_3:
            selectImage(v.getId());
            break;
    }
}

调用selectImage方法并处理alertDialog,该方法将询问用户是想要拍照还是选择一张照片。我试图在putExtra方法中传递ID,但是在startActivityForResult中没有收到任何内容

public void selectImage(final int imageViewID){

    final CharSequence[] options = {getString(R.string.cameral_select_photo_label), getString(R.string.camera_take_photo_label), getString(R.string.common_cancel_label)};
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(getString(R.string.camera_dialog_title_label));

    builder.setItems(options, new DialogInterface.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if(options[which].equals(getString(R.string.camera_take_photo_label))){

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra("ImageViewID", imageViewID);
                startActivityForResult(intent, REQUEST_CAMERA);

            }
            else if(options[which].equals(getString(R.string.cameral_select_photo_label))){

                Utils.verifyStoragePermissions(getActivity());

                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                );

                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, getResources().getText(R.string.camera_select_image)),SELECT_FILE);

            }
            else if(options[which].equals(getString(R.string.common_cancel_label))){

                dialog.dismiss();

            }
        }
    });
    builder.show();
}

在startActivityForResult中,我没有收到ImageViewID。所以现在,我只是将图像放在第一个ImageView中,因为我无法检索到正确的ID。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == Activity.RESULT_OK){

        if(requestCode == REQUEST_CAMERA){

            Log.d("Data content", String.valueOf(data));

            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");

            FileOutputStream fo;

            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            itemPic1.setImageBitmap(thumbnail);

        } else if (requestCode == SELECT_FILE){

            Log.d("imageViewOrigin", String.valueOf(data.getIntExtra("imageViewID", 0)));

            Uri selectedImageUrl = data.getData();
            String[] projection = {MediaStore.MediaColumns.DATA};
            CursorLoader cursorLoader = new CursorLoader(getContext(), selectedImageUrl, projection, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();

            String selectedImagePath = cursor.getString(column_index);

            Bitmap bm;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(selectedImagePath, options);
            final int REQUIRED_SIZE = 200;
            int scale = 1;
            while(options.outWidth / scale / 2 >= REQUIRED_SIZE && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale += 2;
            options.inSampleSize = scale;
            options.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(selectedImagePath, options);

            itemPic1.setImageBitmap(bm);


        }

    }

}

2 个答案:

答案 0 :(得分:0)

我建议在ImageViews上设置标签。请点击链接,这是一个类似的问题What is the main purpose of setTag() getTag() methods of View?。如果您需要更多帮助,请告诉我们!

答案 1 :(得分:0)

尝试这种方式:

 private void openImageIntent(int IMAGE_TYPE) {

    // Determine Uri of camera image to save.
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "mycapturedImage" + File.separator);
    root.mkdirs();
    final String fname = getUniqueImageFilename();
    final File sdImageMainDirectory = new File(root, fname);
    outputFileUri = Uri.fromFile(sdImageMainDirectory);

    // Camera.
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    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, outputFileUri);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choisir une Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));

    startActivityForResult(chooserIntent, IMAGE_TYPE);
}

然后像这样检索每个图像:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_CANCELED) {
        if (resultCode == RESULT_OK) {
            if (requestCode == FIRST_IMAGE_INTENT) {
                final boolean isCamera;
                if (data == null) {
                    isCamera = true;

                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }


                if (isCamera) {

                    selectedCaptureUri = outputFileUri; 

                } else {

                    selectedCaptureUri = data == null ? null : data.getData();


                }

   //Display image here 

            } else if (requestCode == SECOND_PICTURE_INTENT) {...}